text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def res(self): """Get all target values found and corresponding parametes."""
params = [dict(zip(self.keys, p)) for p in self.params] return [ {"target": target, "params": param} for target, param in zip(self.target, params) ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_bounds(self, new_bounds): """ A method that allows changing the lower and upper searching bounds Parameters new_bounds : dict A dictionary with the param...
for row, key in enumerate(self.keys): if key in new_bounds: self._bounds[row] = new_bounds[key]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_data(): """Synthetic binary classification dataset."""
data, targets = make_classification( n_samples=1000, n_features=45, n_informative=12, n_redundant=7, random_state=134985745, ) return data, targets
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def svc_cv(C, gamma, data, targets): """SVC cross validation. This function will instantiate a SVC classifier with parameters C and gamma. Combined with data and...
estimator = SVC(C=C, gamma=gamma, random_state=2) cval = cross_val_score(estimator, data, targets, scoring='roc_auc', cv=4) return cval.mean()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rfc_cv(n_estimators, min_samples_split, max_features, data, targets): """Random Forest cross validation. This function will instantiate a random forest class...
estimator = RFC( n_estimators=n_estimators, min_samples_split=min_samples_split, max_features=max_features, random_state=2 ) cval = cross_val_score(estimator, data, targets, scoring='neg_log_loss', cv=4) return cval.mean()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def optimize_svc(data, targets): """Apply Bayesian Optimization to SVC parameters."""
def svc_crossval(expC, expGamma): """Wrapper of SVC cross validation. Notice how we transform between regular and log scale. While this is not technically necessary, it greatly improves the performance of the optimizer. """ C = 10 ** expC gamma = 10 ** expGa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def optimize_rfc(data, targets): """Apply Bayesian Optimization to Random Forest parameters."""
def rfc_crossval(n_estimators, min_samples_split, max_features): """Wrapper of RandomForest cross validation. Notice how we ensure n_estimators and min_samples_split are casted to integer before we pass them along. Moreover, to avoid max_features taking values outside the (0, 1) ra...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_logs(optimizer, logs): """
import json if isinstance(logs, str): logs = [logs] for log in logs: with open(log, "r") as j: while True: try: iteration = next(j) except StopIteration: break iteration = json.loads(itera...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ensure_rng(random_state=None): """ Creates a random number generator based on an optional seed. This can be an integer or another random state for a seeded r...
if random_state is None: random_state = np.random.RandomState() elif isinstance(random_state, int): random_state = np.random.RandomState(random_state) else: assert isinstance(random_state, np.random.RandomState) return random_state
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expand_abbreviations(template, abbreviations): """Expand abbreviations in a template name. :param template: The project template name. :param abbreviations: ...
if template in abbreviations: return abbreviations[template] # Split on colon. If there is no colon, rest will be empty # and prefix will be the whole template prefix, sep, rest = template.partition(':') if prefix in abbreviations: return abbreviations[prefix].format(rest) ret...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def repository_has_cookiecutter_json(repo_directory): """Determine if `repo_directory` contains a `cookiecutter.json` file. :param repo_directory: The candidate ...
repo_directory_exists = os.path.isdir(repo_directory) repo_config_exists = os.path.isfile( os.path.join(repo_directory, 'cookiecutter.json') ) return repo_directory_exists and repo_config_exists
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def determine_repo_dir(template, abbreviations, clone_to_dir, checkout, no_input, password=None): """ Locate the repository directory from a template reference. ...
template = expand_abbreviations(template, abbreviations) if is_zip_file(template): unzipped_dir = unzip( zip_uri=template, is_url=is_repo_url(template), clone_to_dir=clone_to_dir, no_input=no_input, password=password ) reposit...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_template(repo_dir): """Determine which child directory of `repo_dir` is the project template. :param repo_dir: Local directory of newly cloned repo. :re...
logger.debug('Searching {} for the project template.'.format(repo_dir)) repo_dir_contents = os.listdir(repo_dir) project_template = None for item in repo_dir_contents: if 'cookiecutter' in item and '{{' in item and '}}' in item: project_template = item break if pr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_copy_only_path(path, context): """Check whether the given `path` should only be copied and not rendered. Returns True if `path` matches a pattern in the g...
try: for dont_render in context['cookiecutter']['_copy_without_render']: if fnmatch.fnmatch(path, dont_render): return True except KeyError: return False return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply_overwrites_to_context(context, overwrite_context): """Modify the given context in place based on the overwrite_context."""
for variable, overwrite in overwrite_context.items(): if variable not in context: # Do not include variables which are not used in the template continue context_value = context[variable] if isinstance(context_value, list): # We are dealing with a choice...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_context(context_file='cookiecutter.json', default_context=None, extra_context=None): """Generate the context for a Cookiecutter project template. Lo...
context = OrderedDict([]) try: with open(context_file) as file_handle: obj = json.load(file_handle, object_pairs_hook=OrderedDict) except ValueError as e: # JSON decoding error. Let's throw a new exception that is more # friendly for the developer or user. full...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_file(project_dir, infile, context, env): """Render filename of infile as name of outfile, handle infile correctly. Dealing with infile appropriately...
logger.debug('Processing file {}'.format(infile)) # Render the path to the output file (not including the root project dir) outfile_tmpl = env.from_string(infile) outfile = os.path.join(project_dir, outfile_tmpl.render(**context)) file_name_is_empty = os.path.isdir(outfile) if file_name_is_em...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_and_create_dir(dirname, context, output_dir, environment, overwrite_if_exists=False): """Render name of a directory, create the directory, return its ...
name_tmpl = environment.from_string(dirname) rendered_dirname = name_tmpl.render(**context) dir_to_create = os.path.normpath( os.path.join(output_dir, rendered_dirname) ) logger.debug('Rendered dir {} must exist in output_dir {}'.format( dir_to_create, output_dir )) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _run_hook_from_repo_dir(repo_dir, hook_name, project_dir, context, delete_project_on_failure): """Run hook from repo directory, clean project directory if ho...
with work_in(repo_dir): try: run_hook(hook_name, project_dir, context) except FailedHookException: if delete_project_on_failure: rmtree(project_dir) logger.error( "Stopping generation because {} hook " "script didn'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _expand_path(path): """Expand both environment variables and user home in the given path."""
path = os.path.expandvars(path) path = os.path.expanduser(path) return path
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_config(config_path): """Retrieve the config from the specified path, returning a config dict."""
if not os.path.exists(config_path): raise ConfigDoesNotExistException logger.debug('config_path is {0}'.format(config_path)) with io.open(config_path, encoding='utf-8') as file_handle: try: yaml_dict = poyo.parse_string(file_handle.read()) except poyo.exceptions.PoyoExc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_user_config(config_file=None, default_config=False): """Return the user config as a dict. If ``default_config`` is True, ignore ``config_file`` and retur...
# Do NOT load a config. Return defaults instead. if default_config: return copy.copy(DEFAULT_CONFIG) # Load the given config file if config_file and config_file is not USER_CONFIG_PATH: return get_config(config_file) try: # Does the user set up a config environment variabl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_sure_path_exists(path): """Ensure that a directory exists. :param path: A directory path. """
logger.debug('Making sure path exists: {}'.format(path)) try: os.makedirs(path) logger.debug('Created directory at: {}'.format(path)) except OSError as exception: if exception.errno != errno.EEXIST: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def work_in(dirname=None): """Context manager version of os.chdir. When exited, returns to the working directory prior to entering. """
curdir = os.getcwd() try: if dirname is not None: os.chdir(dirname) yield finally: os.chdir(curdir)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_executable(script_path): """Make `script_path` executable. :param script_path: The file to change """
status = os.stat(script_path) os.chmod(script_path, status.st_mode | stat.S_IEXEC)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unzip(zip_uri, is_url, clone_to_dir='.', no_input=False, password=None): """Download and unpack a zipfile at a given URI. This will download the zipfile to t...
# Ensure that clone_to_dir exists clone_to_dir = os.path.expanduser(clone_to_dir) make_sure_path_exists(clone_to_dir) if is_url: # Build the name of the cached zipfile, # and prompt to delete if it already exists. identifier = zip_uri.rsplit('/', 1)[1] zip_path = os.pat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cookiecutter( template, checkout=None, no_input=False, extra_context=None, replay=False, overwrite_if_exists=False, output_dir='.', config_file=None, default_...
if replay and ((no_input is not False) or (extra_context is not None)): err_msg = ( "You can not use both replay and no_input or extra_context " "at the same time." ) raise InvalidModeException(err_msg) config_dict = get_user_config( config_file=config_f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_user_choice(var_name, options): """Prompt the user to choose from several options for the given variable. The first item will be returned if no input ha...
# Please see http://click.pocoo.org/4/api/#click.prompt if not isinstance(options, list): raise TypeError if not options: raise ValueError choice_map = OrderedDict( (u'{}'.format(i), value) for i, value in enumerate(options, 1) ) choices = choice_map.keys() default...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_user_dict(var_name, default_value): """Prompt the user to provide a dictionary of data. :param str var_name: Variable as specified in the context :param...
# Please see http://click.pocoo.org/4/api/#click.prompt if not isinstance(default_value, dict): raise TypeError default_display = 'default' user_value = click.prompt( var_name, default=default_display, type=click.STRING, value_proc=process_json, ) if u...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prompt_choice_for_config(cookiecutter_dict, env, key, options, no_input): """Prompt the user which option to choose from the given. Each of the possible choi...
rendered_options = [ render_variable(env, raw, cookiecutter_dict) for raw in options ] if no_input: return rendered_options[0] return read_user_choice(key, rendered_options)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prompt_for_config(context, no_input=False): """ Prompts the user to enter new config, using context as a source for the field names and sample values. :param...
cookiecutter_dict = OrderedDict([]) env = StrictEnvironment(context=context) # First pass: Handle simple and raw variables, plus choices. # These must be done first because the dictionaries keys and # values might refer to them. for key, raw in iteritems(context[u'cookiecutter']): if k...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _read_extensions(self, context): """Return list of extensions as str to be passed on to the Jinja2 env. If context does not contain the relevant info, return...
try: extensions = context['cookiecutter']['_extensions'] except KeyError: return [] else: return [str(ext) for ext in extensions]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configure_logger(stream_level='DEBUG', debug_file=None): """Configure logging for cookiecutter. Set up logging to stdout with given level. If ``debug_file`` ...
# Set up 'cookiecutter' logger logger = logging.getLogger('cookiecutter') logger.setLevel(logging.DEBUG) # Remove all attached handlers, in case there was # a logger with using the name 'cookiecutter' del logger.handlers[:] # Create a file handler if a log file is provided if debug_fi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def identify_repo(repo_url): """Determine if `repo_url` should be treated as a URL to a git or hg repo. Repos can be identified by prepending "hg+" or "git+" to ...
repo_url_values = repo_url.split('+') if len(repo_url_values) == 2: repo_type = repo_url_values[0] if repo_type in ["git", "hg"]: return repo_type, repo_url_values[1] else: raise UnknownRepoType else: if 'git' in repo_url: return 'git', re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clone(repo_url, checkout=None, clone_to_dir='.', no_input=False): """Clone a repo to the current directory. :param repo_url: Repo URL of unknown type. :param...
# Ensure that clone_to_dir exists clone_to_dir = os.path.expanduser(clone_to_dir) make_sure_path_exists(clone_to_dir) # identify the repo_type repo_type, repo_url = identify_repo(repo_url) # check that the appropriate VCS for the repo_type is installed if not is_vcs_installed(repo_type): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def valid_hook(hook_file, hook_name): """Determine if a hook file is valid. :param hook_file: The hook file to consider for validity :param hook_name: The hook t...
filename = os.path.basename(hook_file) basename = os.path.splitext(filename)[0] matching_hook = basename == hook_name supported_hook = basename in _HOOKS backup_file = filename.endswith('~') return matching_hook and supported_hook and not backup_file
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_hook(hook_name, hooks_dir='hooks'): """Return a dict of all hook scripts provided. Must be called with the project template as the current working direc...
logger.debug('hooks_dir is {}'.format(os.path.abspath(hooks_dir))) if not os.path.isdir(hooks_dir): logger.debug('No hooks/ dir in template_dir') return None for hook_file in os.listdir(hooks_dir): if valid_hook(hook_file, hook_name): return os.path.abspath(os.path.joi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_script(script_path, cwd='.'): """Execute a script from a working directory. :param script_path: Absolute path to the script to run. :param cwd: The direc...
run_thru_shell = sys.platform.startswith('win') if script_path.endswith('.py'): script_command = [sys.executable, script_path] else: script_command = [script_path] utils.make_executable(script_path) try: proc = subprocess.Popen( script_command, shel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_script_with_context(script_path, cwd, context): """Execute a script after rendering it with Jinja. :param script_path: Absolute path to the script to run...
_, extension = os.path.splitext(script_path) contents = io.open(script_path, 'r', encoding='utf-8').read() with tempfile.NamedTemporaryFile( delete=False, mode='wb', suffix=extension ) as temp: env = StrictEnvironment( context=context, keep_trai...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_hook(hook_name, project_dir, context): """ Try to find and execute a hook from the specified project directory. :param hook_name: The hook to execute. :p...
script = find_hook(hook_name) if script is None: logger.debug('No {} hook found'.format(hook_name)) return logger.debug('Running hook {}'.format(hook_name)) run_script_with_context(script, project_dir, context)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def version_msg(): """Return the Cookiecutter version, location and Python powering it."""
python_version = sys.version[:3] location = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) message = u'Cookiecutter %(version)s from {} (Python {})' return message.format(location, python_version)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_extra_context(ctx, param, value): """Validate extra context."""
for s in value: if '=' not in s: raise click.BadParameter( 'EXTRA_CONTEXT should contain items of the form key=value; ' "'{}' doesn't match that form".format(s) ) # Convert tuple -- e.g.: (u'program_name=foobar', u'startsecs=66') # to dict --...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mounted(cls, unmounted): # noqa: N802 """ Mount the UnmountedType instance """
assert isinstance(unmounted, UnmountedType), ("{} can't mount {}").format( cls.__name__, repr(unmounted) ) return cls( unmounted.get_type(), *unmounted.args, _creation_counter=unmounted.creation_counter, **unmounted.kwargs )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replace( self, name=_void, kind=_void, annotation=_void, default=_void, _partial_kwarg=_void, ): """Creates a customized copy of the Parameter."""
if name is _void: name = self._name if kind is _void: kind = self._kind if annotation is _void: annotation = self._annotation if default is _void: default = self._default if _partial_kwarg is _void: _partial_kwarg ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_function(cls, func): """Constructs Signature for the given python function"""
if not isinstance(func, types.FunctionType): raise TypeError("{!r} is not a Python function".format(func)) Parameter = cls._parameter_cls # Parameter information. func_code = func.__code__ pos_count = func_code.co_argcount arg_names = func_code.co_varnames...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _bind(self, args, kwargs, partial=False): """Private method. Don't use directly."""
arguments = OrderedDict() parameters = iter(self.parameters.values()) parameters_ex = () arg_vals = iter(args) if partial: # Support for binding arguments to 'functools.partial' objects. # See 'functools.partial' case in 'signature()' implementation ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bind_partial(self, *args, **kwargs): """Get a BoundArguments object, that partially maps the passed `args` and `kwargs` to the function's signature. Raises `...
return self._bind(args, kwargs, partial=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_node(objecttype): """ Check if the given objecttype has Node as an interface """
if not isclass(objecttype): return False if not issubclass(objecttype, ObjectType): return False for i in objecttype._meta.interfaces: if issubclass(i, Node): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_complete_version(version=None): """Returns a tuple of the graphene version. If version argument is non-empty, then checks for correctness of the tuple pr...
if version is None: from graphene import VERSION as version else: assert len(version) == 5 assert version[3] in ("alpha", "beta", "rc", "final") return version
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_field_as(value, _as=None): """ Get type mounted """
if isinstance(value, MountedType): return value elif isinstance(value, UnmountedType): if _as is None: return value return _as.mounted(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scan_aggs(search, source_aggs, inner_aggs={}, size=10): """ Helper function used to iterate over all possible bucket combinations of ``source_aggs``, returni...
def run_search(**kwargs): s = search[:0] s.aggs.bucket('comp', 'composite', sources=source_aggs, size=size, **kwargs) for agg_name, agg in inner_aggs.items(): s.aggs['comp'][agg_name] = agg return s.execute() response = run_search() while response.aggregations.c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean(self): """ Automatically construct the suggestion input and weight by taking all possible permutation of Person's name as ``input`` and taking their po...
self.suggest = { 'input': [' '.join(p) for p in permutations(self.name.split())], 'weight': self.popularity }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __list_fields(cls): """ Get all the fields defined for our class, if we have an Index, try looking at the index mappings as well, mark the fields from Index ...
for name in cls._doc_type.mapping: field = cls._doc_type.mapping[name] yield name, field, False if hasattr(cls.__class__, '_index'): if not cls._index._mapping: return for name in cls._index._mapping: # don't return fields...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_dict(self, **kwargs): """ Serialize the search into the dictionary that will be sent over as the request'ubq body. All additional keyword arguments will b...
d = {} if self.query: d["query"] = self.query.to_dict() if self._script: d['script'] = self._script d.update(self._extra) d.update(kwargs) return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _collect_fields(self): """ Iterate over all Field objects within, including multi fields. """
for f in itervalues(self.properties.to_dict()): yield f # multi fields if hasattr(f, 'fields'): for inner_f in itervalues(f.fields.to_dict()): yield inner_f # nested and inner objects if hasattr(f, '_collect_fields'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def analyzer(self, *args, **kwargs): """ Explicitly add an analyzer to an index. Note that all custom analyzers defined in mappings will also be created. This is...
analyzer = analysis.analyzer(*args, **kwargs) d = analyzer.get_analysis_definition() # empty custom analyzer, probably already defined out of our control if not d: return # merge the definition merge(self._analysis, d, True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, using=None, **kwargs): """ Creates the index in elasticsearch. Any additional keyword arguments will be passed to ``Elasticsearch.indices.create...
self._get_connection(using).indices.create(index=self._name, body=self.to_dict(), **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, using=None): """ Sync the index definition with elasticsearch, creating the index if it doesn't exist and updating its settings and mappings if it...
if not self.exists(using=using): return self.create(using=using) body = self.to_dict() settings = body.pop('settings', {}) analysis = settings.pop('analysis', None) current_settings = self.get_settings(using=using)[self._name]['settings']['index'] if analysi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def analyze(self, using=None, **kwargs): """ Perform the analysis process on a text and return the tokens breakdown of the text. Any additional keyword arguments...
return self._get_connection(using).indices.analyze(index=self._name, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def refresh(self, using=None, **kwargs): """ Preforms a refresh operation on the index. Any additional keyword arguments will be passed to ``Elasticsearch.indice...
return self._get_connection(using).indices.refresh(index=self._name, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flush(self, using=None, **kwargs): """ Preforms a flush operation on the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.fl...
return self._get_connection(using).indices.flush(index=self._name, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, using=None, **kwargs): """ The get index API allows to retrieve information about the index. Any additional keyword arguments will be passed to ``E...
return self._get_connection(using).indices.get(index=self._name, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open(self, using=None, **kwargs): """ Opens the index in elasticsearch. Any additional keyword arguments will be passed to ``Elasticsearch.indices.open`` unc...
return self._get_connection(using).indices.open(index=self._name, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self, using=None, **kwargs): """ Closes the index in elasticsearch. Any additional keyword arguments will be passed to ``Elasticsearch.indices.close`` ...
return self._get_connection(using).indices.close(index=self._name, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, using=None, **kwargs): """ Deletes the index in elasticsearch. Any additional keyword arguments will be passed to ``Elasticsearch.indices.delete...
return self._get_connection(using).indices.delete(index=self._name, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exists(self, using=None, **kwargs): """ Returns ``True`` if the index already exists in elasticsearch. Any additional keyword arguments will be passed to ``E...
return self._get_connection(using).indices.exists(index=self._name, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def put_mapping(self, using=None, **kwargs): """ Register specific mapping definition for a specific type. Any additional keyword arguments will be passed to ``E...
return self._get_connection(using).indices.put_mapping(index=self._name, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_mapping(self, using=None, **kwargs): """ Retrieve specific mapping definition for a specific type. Any additional keyword arguments will be passed to ``E...
return self._get_connection(using).indices.get_mapping(index=self._name, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_field_mapping(self, using=None, **kwargs): """ Retrieve mapping definition of a specific field. Any additional keyword arguments will be passed to ``Elas...
return self._get_connection(using).indices.get_field_mapping(index=self._name, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def put_alias(self, using=None, **kwargs): """ Create an alias for the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.put_alia...
return self._get_connection(using).indices.put_alias(index=self._name, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exists_alias(self, using=None, **kwargs): """ Return a boolean indicating whether given alias exists for this index. Any additional keyword arguments will be...
return self._get_connection(using).indices.exists_alias(index=self._name, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_alias(self, using=None, **kwargs): """ Retrieve a specified alias. Any additional keyword arguments will be passed to ``Elasticsearch.indices.get_alias``...
return self._get_connection(using).indices.get_alias(index=self._name, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_alias(self, using=None, **kwargs): """ Delete specific alias. Any additional keyword arguments will be passed to ``Elasticsearch.indices.delete_alias`...
return self._get_connection(using).indices.delete_alias(index=self._name, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_settings(self, using=None, **kwargs): """ Retrieve settings for the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.get...
return self._get_connection(using).indices.get_settings(index=self._name, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def put_settings(self, using=None, **kwargs): """ Change specific index level settings in real time. Any additional keyword arguments will be passed to ``Elastic...
return self._get_connection(using).indices.put_settings(index=self._name, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stats(self, using=None, **kwargs): """ Retrieve statistics on different operations happening on the index. Any additional keyword arguments will be passed to...
return self._get_connection(using).indices.stats(index=self._name, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_query(self, using=None, **kwargs): """ Validate a potentially expensive query without executing it. Any additional keyword arguments will be passed ...
return self._get_connection(using).indices.validate_query(index=self._name, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear_cache(self, using=None, **kwargs): """ Clear all caches or specific cached associated with the index. Any additional keyword arguments will be passed t...
return self._get_connection(using).indices.clear_cache(index=self._name, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def recovery(self, using=None, **kwargs): """ The indices recovery API provides insight into on-going shard recoveries for the index. Any additional keyword argu...
return self._get_connection(using).indices.recovery(index=self._name, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upgrade(self, using=None, **kwargs): """ Upgrade the index to the latest format. Any additional keyword arguments will be passed to ``Elasticsearch.indices.u...
return self._get_connection(using).indices.upgrade(index=self._name, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_upgrade(self, using=None, **kwargs): """ Monitor how much of the index is upgraded. Any additional keyword arguments will be passed to ``Elasticsearch.in...
return self._get_connection(using).indices.get_upgrade(index=self._name, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shard_stores(self, using=None, **kwargs): """ Provides store information for shard copies of the index. Store information reports on which nodes shard copies...
return self._get_connection(using).indices.shard_stores(index=self._name, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def forcemerge(self, using=None, **kwargs): """ The force merge API allows to force merging of the index through an API. The merge relates to the number of segme...
return self._get_connection(using).indices.forcemerge(index=self._name, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configure(self, **kwargs): """ Configure multiple connections at once, useful for passing in config dictionaries obtained from other sources, like Django's s...
for k in list(self._conns): # try and preserve existing client to keep the persistent connections alive if k in self._kwargs and kwargs.get(k, None) == self._kwargs[k]: continue del self._conns[k] self._kwargs = kwargs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_connection(self, alias): """ Remove connection from the registry. Raises ``KeyError`` if connection wasn't found. """
errors = 0 for d in (self._conns, self._kwargs): try: del d[alias] except KeyError: errors += 1 if errors == 2: raise KeyError('There is no connection with alias %r.' % alias)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_connection(self, alias='default', **kwargs): """ Construct an instance of ``elasticsearch.Elasticsearch`` and register it under given alias. """
kwargs.setdefault('serializer', serializer) conn = self._conns[alias] = Elasticsearch(**kwargs) return conn
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup(): """ Create the index template in elasticsearch specifying the mappings and any settings to be used. This can be run at any time, ideally at every ne...
# create an index template index_template = BlogPost._index.as_template(ALIAS, PATTERN) # upload the template into elasticsearch # potentially overriding the one already there index_template.save() # create the first index if it doesn't exist if not BlogPost._index.exists(): migrat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def simulate(self, text, using='default', explain=False, attributes=None): """ Use the Analyze API of elasticsearch to test the outcome of this analyzer. :arg te...
es = connections.get_connection(using) body = {'text': text, 'explain': explain} if attributes: body['attributes'] = attributes definition = self.get_analysis_definition() analyzer_def = self.get_definition() for section in ('tokenizer', 'char_filter', 'fi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_answers(self): """ Get answers either from inner_hits already present or by searching elasticsearch. """
if 'inner_hits' in self.meta and 'answer' in self.meta.inner_hits: return self.meta.inner_hits.answer.hits return list(self.search_answers())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_aggregation(self): """ Return the aggregation object. """
agg = A(self.agg_type, **self._params) if self._metric: agg.metric('metric', self._metric) return agg
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_filter(self, filter_values): """ Construct a filter. """
if not filter_values: return f = self.get_value_filter(filter_values[0]) for v in filter_values[1:]: f |= self.get_value_filter(v) return f
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_values(self, data, filter_values): """ Turn the raw bucket data into a list of tuples containing the key, number of documents and a flag indicating wheth...
out = [] for bucket in data.buckets: key = self.get_value(bucket) out.append(( key, self.get_metric(bucket), self.is_filtered(key, filter_values) )) return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_filter(self, name, filter_values): """ Add a filter for a facet. """
# normalize the value into a list if not isinstance(filter_values, (tuple, list)): if filter_values is None: return filter_values = [filter_values, ] # remember the filter values for use in FacetedResponse self.filter_values[name] = filter_values...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search(self): """ Returns the base Search object to which the facets are added. You can customize the query by overriding this method and returning a modifie...
s = Search(doc_type=self.doc_types, index=self.index, using=self.using) return s.response_class(FacetedResponse)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query(self, search, query): """ Add query part to ``search``. Override this if you wish to customize the query used. """
if query: if self.fields: return search.query('multi_match', fields=self.fields, query=query) else: return search.query('multi_match', query=query) return search
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def aggregate(self, search): """ Add aggregations representing the facets selected, including potential filters. """
for f, facet in iteritems(self.facets): agg = facet.get_aggregation() agg_filter = MatchAll() for field, filter in iteritems(self._filters): if f == field: continue agg_filter &= filter search.aggs.bucket( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter(self, search): """ Add a ``post_filter`` to the search request narrowing the results based on the facet filters. """
if not self._filters: return search post_filter = MatchAll() for f in itervalues(self._filters): post_filter &= f return search.post_filter(post_filter)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def highlight(self, search): """ Add highlighting for all the fields """
return search.highlight(*(f if '^' not in f else f.split('^', 1)[0] for f in self.fields))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort(self, search): """ Add sorting information to the request. """
if self._sort: search = search.sort(*self._sort) return search
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute(self): """ Execute the search and return the response. """
r = self._s.execute() r._faceted_search = self return r