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 _get_regex(data, position, dummy0, dummy1): """Decode a BSON regex to bson.regex.Regex or a python pattern object."""
pattern, position = _get_c_string(data, position) bson_flags, position = _get_c_string(data, position) bson_re = Regex(pattern, bson_flags) return bson_re, position
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _encode_mapping(name, value, check_keys, opts): """Encode a mapping type."""
data = b"".join([_element_to_bson(key, val, check_keys, opts) for key, val in iteritems(value)]) return b"\x03" + name + _PACK_INT(len(data) + 5) + data + b"\x00"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _encode_code(name, value, dummy, opts): """Encode bson.code.Code."""
cstring = _make_c_string(value) cstrlen = len(cstring) if not value.scope: return b"\x0D" + name + _PACK_INT(cstrlen) + cstring scope = _dict_to_bson(value.scope, False, opts, False) full_length = _PACK_INT(8 + cstrlen + len(scope)) return b"\x0F" + name + full_length + _PACK_INT(cstrle...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def simToReg(self, sim): """Convert simplified domain expression to regular expression"""
# remove initial slash if present res = re.sub('^/', '', sim) res = re.sub('/$', '', res) return '^/?' + re.sub('\*', '[^/]+', res) + '/?$'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def match(self, dom, act): """ Check if the given `domain` and `act` are allowed by this capability """
return self.match_domain(dom) and self.match_action(act)
<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_list(self): '''convert an actions bitmask into a list of action strings''' res = [] for a in self.__class__.ACTIONS: aBit = self.__class__.action_bitmask(a) if ((self & aBit) == aBit): res.append(a) return res
<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_list(cls, actions): '''convert list of actions into the corresponding bitmask''' bitmask = 0 for a in actions: bitmask |= cls.action_bitmask(a) return Action(bitmask)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def str_val(val): """ Format the value of a metric value to a string :param val: number to be formatted :return: a string with the formatted value """
str_val = val if val is None: str_val = "NA" elif type(val) == float: str_val = '%0.2f' % val else: str_val = str(val) return str_val
<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_cfg(path, envvar_prefix='LIBREANT_', debug=False): '''wrapper of config_utils.load_configs''' try: return load_configs(envvar_prefix, path=path) except Exception as e: if debug: raise else: die(str(e))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def files_in_subdir(dir, subdir): """Find all files in a directory."""
paths = [] for (path, dirs, files) in os.walk(os.path.join(dir, subdir)): for file in files: paths.append(os.path.relpath(os.path.join(path, file), dir)) return paths
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def overview(index, start, end): """Compute metrics in the overview section for enriched git indexes. Returns a dictionary. Each key in the dictionary is the nam...
results = { "activity_metrics": [Commits(index, start, end)], "author_metrics": [Authors(index, start, end)], "bmi_metrics": [], "time_to_close_metrics": [], "projects_metrics": [] } return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def project_activity(index, start, end): """Compute the metrics for the project activity section of the enriched git index. Returns a dictionary containing a "me...
results = { "metrics": [Commits(index, start, end), Authors(index, start, end)] } return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def project_community(index, start, end): """Compute the metrics for the project community section of the enriched git index. Returns a dictionary containing "au...
results = { "author_metrics": [Authors(index, start, end)], "people_top_metrics": [Authors(index, start, end)], "orgs_top_metrics": [Organizations(index, start, end)], } return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def aggregations(self): """ Override parent method. Obtain list of the terms and their corresponding values using "terms" aggregations for the previous time peri...
prev_month_start = get_prev_month(self.end, self.query.interval_) self.query.since(prev_month_start) self.query.get_terms("author_name") return self.query.get_list(dataframe=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 project_activity(index, start, end): """Compute the metrics for the project activity section of the enriched github issues index. Returns a dictionary contai...
results = { "metrics": [OpenedIssues(index, start, end), ClosedIssues(index, start, end)] } return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def aggregations(self): """Get the aggregation value for BMI with respect to the previous time interval."""
prev_month_start = get_prev_month(self.end, self.closed.query.interval_) self.closed.query.since(prev_month_start, field="closed_at") closed_agg = self.closed.aggregations() self.opened.query.since(prev_month_sta...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def c_log(level, message): """python logger to be called from fortran"""
c_level = level level = LEVELS_F2PY[c_level] logger.log(level, message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def struct2dict(struct): """convert a ctypes structure to a dictionary"""
return {x: getattr(struct, x) for x in dict(struct._fields_).keys()}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def structs2records(structs): """convert one or more structs and generate dictionaries"""
try: n = len(structs) except TypeError: # no array yield struct2dict(structs) # just 1 return for i in range(n): struct = structs[i] yield struct2dict(struct)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def structs2pandas(structs): """convert ctypes structure or structure array to pandas data frame"""
try: import pandas records = list(structs2records(structs)) df = pandas.DataFrame.from_records(records) # TODO: do this for string columns, for now just for id # How can we check for string columns, this is not nice: # df.columns[df.dtypes == object] if 'id' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wrap(func): """Return wrapped function with type conversion and sanity checks. """
@functools.wraps(func, assigned=('restype', 'argtypes')) def wrapped(*args): if len(args) != len(func.argtypes): logger.warn("{} {} not of same length", args, func.argtypes) typed_args = [] for (arg, argtype) in zip(args, func.argtypes): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _libname(self): """Return platform-specific modelf90 shared library name."""
prefix = 'lib' suffix = '.so' if platform.system() == 'Darwin': suffix = '.dylib' if platform.system() == 'Windows': prefix = '' suffix = '.dll' return prefix + self.engine + suffix
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _library_path(self): """Return full path to the shared library. A couple of regular unix paths like ``/usr/lib/`` is searched by default. If your library is ...
# engine is an existing library name # TODO change add directory to library path if os.path.isfile(self.engine): return self.engine pathname = 'LD_LIBRARY_PATH' separator = ':' if platform.system() == 'Darwin': pathname = 'DYLD_LIBRARY_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 _load_library(self): """Return the fortran library, loaded with """
path = self._library_path() logger.info("Loading library from path {}".format(path)) library_dir = os.path.dirname(path) if platform.system() == 'Windows': import win32api olddir = os.getcwd() os.chdir(library_dir) win32api.SetDllDirectory...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def finalize(self): """Shutdown the library and clean up the model. Note that the Fortran library's cleanup code is not up to snuff yet, so the cleanup is not pe...
self.library.finalize.argtypes = [] self.library.finalize.restype = c_int ierr = wrap(self.library.finalize)() # always go back to previous directory logger.info('cd {}'.format(self.original_dir)) # This one doesn't work. os.chdir(self.original_dir) if ie...
<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_var_count(self): """ Return number of variables """
n = c_int() self.library.get_var_count.argtypes = [POINTER(c_int)] self.library.get_var_count(byref(n)) return n.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 inq_compound_field(self, name, index): """ Lookup the type,rank and shape of a compound field """
typename = create_string_buffer(name) index = c_int(index + 1) fieldname = create_string_buffer(MAXSTRLEN) fieldtype = create_string_buffer(MAXSTRLEN) rank = c_int() arraytype = ndpointer(dtype='int32', ndim=1, ...
<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_compound_ctype(self, varname): """ Create a ctypes type that corresponds to a compound type in memory. """
# look up the type name compoundname = self.get_var_type(varname) nfields = self.inq_compound(compoundname) # for all the fields look up the type, rank and shape fields = [] for i in range(nfields): (fieldname, fieldtype, fieldrank, fieldshape) ...
<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_var_rank(self, name): """ Return array rank or 0 for scalar. """
name = create_string_buffer(name) rank = c_int() self.library.get_var_rank.argtypes = [c_char_p, POINTER(c_int)] self.library.get_var_rank.restype = None self.library.get_var_rank(name, byref(rank)) return rank.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 get_var_shape(self, name): """ Return shape of the array. """
rank = self.get_var_rank(name) name = create_string_buffer(name) arraytype = ndpointer(dtype='int32', ndim=1, shape=(MAXDIMS, ), flags='F') shape = np.empty((MAXDIMS, ), dtype='int32', order='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_start_time(self): """ returns start time """
start_time = c_double() self.library.get_start_time.argtypes = [POINTER(c_double)] self.library.get_start_time.restype = None self.library.get_start_time(byref(start_time)) return start_time.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 get_end_time(self): """ returns end time of simulation """
end_time = c_double() self.library.get_end_time.argtypes = [POINTER(c_double)] self.library.get_end_time.restype = None self.library.get_end_time(byref(end_time)) return end_time.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 get_current_time(self): """ returns current time of simulation """
current_time = c_double() self.library.get_current_time.argtypes = [POINTER(c_double)] self.library.get_current_time.restype = None self.library.get_current_time(byref(current_time)) return current_time.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 get_time_step(self): """ returns current time step of simulation """
time_step = c_double() self.library.get_time_step.argtypes = [POINTER(c_double)] self.library.get_time_step.restype = None self.library.get_time_step(byref(time_step)) return time_step.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 get_var(self, name): """Return an nd array from model library"""
# How many dimensions. rank = self.get_var_rank(name) # The shape array is fixed size shape = np.empty((MAXDIMS, ), dtype='int32', order='F') shape = self.get_var_shape(name) # there should be nothing here... assert sum(shape[rank:]) == 0 # variable 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 set_logger(self, logger): """subscribe to fortran log messages"""
# we don't expect anything back try: self.library.set_logger.restype = None except AttributeError: logger.warn("Tried to set logger but method is not implemented in %s", self.engine) return # as an argument we need a pointer to a fortran log func... ...
<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_current_time(self, current_time): """ sets current time of simulation """
current_time = c_double(current_time) try: self.library.set_current_time.argtypes = [POINTER(c_double)] self.library.set_current_time.restype = None self.library.set_current_time(byref(current_time)) except AttributeError: logger.warn("Tried to se...
<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_db(self, wait_for_ready=True): ''' Create and configure index If `wait_for_ready` is True, this function will block until status for `self.index_name` will be `yellow` ''' if self.es.indices.exists(self.index_name): try: self.update...
<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_index(self, indexname=None, index_conf=None): ''' Create the index Create the index with given configuration. If `indexname` is provided it will be used as the new index name instead of the class one (:py:attr:`DB.index_name`) :param index_conf: confi...
<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_index(self, new_indexname, index_conf=None): '''Clone current index All entries of the current index will be copied into the newly created one named `new_indexname` :param index_conf: Configuration to be used in the new index creation. T...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def reindex(self, new_index=None, index_conf=None): '''Rebuilt the current index This function could be useful in the case you want to change some index settings/mappings and you don't want to loose all the entries belonging to that index. This function is built in such a way ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def mlt(self, _id): ''' High-level method to do "more like this". Its exact implementation can vary. ''' query = { 'query': {'more_like_this': { 'like': {'_id': _id}, 'min_term_freq': 1, 'min_doc_freq'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def file_is_attached(self, url): '''return true if at least one book has file with the given url as attachment ''' body = self._get_search_field('_attachments.url', url) return self.es.count(index=self.index_name, body=body)['count'] > 0
<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_all(self): '''Delete all books from the index''' def delete_action_gen(): scanner = scan(self.es, index=self.index_name, query={'query': {'match_all':{}}}) for v in scanner: yield { '_op_type': 'dele...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def update_book(self, id, body, doc_type='book'): ''' Update a book The "body" is merged with the current one. Yes, it is NOT overwritten. In case of concurrency conflict this function could raise `elasticsearch.ConflictError` ''' # note that we ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def modify_book(self, id, body, doc_type='book', version=None): ''' replace the entire book body Instead of `update_book` this function will overwrite the book content with param body If param `version` is given, it will be checked that the changes are applied 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 increment_download_count(self, id, attachmentID, doc_type='book'): ''' Increment the download counter of a specific file ''' body = self.es.get(index=self.index_name, id=id, doc_type='book', _source_include='_attachments')['_source'] for attachment in body['_attachments']: ...
<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_types(self, raw_conf): """ Convert to int, boolean, list, None types config items """
typed_conf = {} for s in raw_conf.keys(): typed_conf[s] = {} for option in raw_conf[s]: val = raw_conf[s][option] if len(val) > 1 and (val[0] == '"' and val[-1] == '"'): # It is a string typed_conf[s][opti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Elasticsearch(*args, **kwargs): """Elasticsearch wrapper function Wrapper function around the official Elasticsearch class that adds a simple version check u...
check_version = kwargs.pop('check_version', True) es = Elasticsearch_official(*args, **kwargs) if check_version: es_version = es.info()['version']['number'].split('.') if(int(es_version[0]) != int(es_pylib_version[0])): raise RuntimeError("The Elasticsearch python library versio...
<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_envvars(prefix=None, environ=None, envvars=None, as_json=True): """Load environment variables in a dictionary Values are parsed as JSON. If parsing fail...
conf = {} if environ is None: environ = os.environ if prefix is None and envvars is None: raise RuntimeError('Must either give prefix or envvars argument') # if it's a list, convert to dict if isinstance(envvars, list): envvars = {k: k for k in envvars} if not envvars:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calculate_bmi(closed, submitted): """ BMI is the ratio of the number of closed items to the number of total items submitted in a particular period of analysi...
if sorted(closed.keys()) != sorted(submitted.keys()): raise AttributeError("The buckets supplied are not congruent!") dates = closed.index.values closed_values = closed['value'] submitted_values = submitted['value'] ratios = [] for x, y in zip(closed_values, submitted_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 add_query(self, key_val={}): """ Add an es_dsl query object to the es_dsl Search object :param key_val: a key-value pair(dict) containing the query to be add...
q = Q("match", **key_val) self.search = self.search.query(q) return self
<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_inverse_query(self, key_val={}): """ Add an es_dsl inverse query object to the es_dsl Search object :param key_val: a key-value pair(dict) containing the...
q = Q("match", **key_val) self.search = self.search.query(~q) return self
<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_sum(self, field=None): """ Create a sum aggregation object and add it to the aggregation dict :param field: the field present in the index that is to be ...
if not field: raise AttributeError("Please provide field to apply aggregation to!") agg = A("sum", field=field) self.aggregations['sum_' + field] = agg return self
<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_average(self, field=None): """ Create an avg aggregation object and add it to the aggregation dict :param field: the field present in the index that is t...
if not field: raise AttributeError("Please provide field to apply aggregation to!") agg = A("avg", field=field) self.aggregations['avg_' + field] = agg return self
<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_percentiles(self, field=None, percents=None): """ Create a percentile aggregation object and add it to the aggregation dict :param field: the field prese...
if not field: raise AttributeError("Please provide field to apply aggregation to!") if not percents: percents = [1.0, 5.0, 25.0, 50.0, 75.0, 95.0, 99.0] agg = A("percentiles", field=field, percents=percents) self.aggregations['percentiles_' + field] = 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 get_terms(self, field=None): """ Create a terms aggregation object and add it to the aggregation dict :param field: the field present in the index that is to...
if not field: raise AttributeError("Please provide field to apply aggregation to!") agg = A("terms", field=field, size=self.size, order={"_count": "desc"}) self.aggregations['terms_' + field] = agg return self
<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_min(self, field=None): """ Create a min aggregation object and add it to the aggregation dict :param field: the field present in the index that is to be ...
if not field: raise AttributeError("Please provide field to apply aggregation to!") agg = A("min", field=field) self.aggregations['min_' + field] = agg return self
<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_max(self, field=None): """ Create a max aggregation object and add it to the aggregation dict :param field: the field present in the index that is to be ...
if not field: raise AttributeError("Please provide field to apply aggregation to!") agg = A("max", field=field) self.aggregations['max_' + field] = agg return self
<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_cardinality(self, field=None): """ Create a cardinality aggregation object and add it to the aggregation dict :param field: the field present in the inde...
if not field: raise AttributeError("Please provide field to apply aggregation to!") agg = A("cardinality", field=field, precision_threshold=self.precision_threshold) self.aggregations['cardinality_' + field] = agg return self
<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_extended_stats(self, field=None): """ Create an extended_stats aggregation object and add it to the aggregation dict :param field: the field present in t...
if not field: raise AttributeError("Please provide field to apply aggregation to!") agg = A("extended_stats", field=field) self.aggregations['extended_stats_' + field] = agg return self
<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_custom_aggregation(self, agg, name=None): """ Takes in an es_dsl Aggregation object and adds it to the aggregation dict. Can be used to add custom aggreg...
agg_name = name if name else 'custom_agg' self.aggregations[agg_name] = agg return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def since(self, start, field=None): """ Add the start date to query data starting from that date sets the default start date for each query :param start: date to...
if not field: field = "grimoire_creation_date" self.start_date = start date_dict = {field: {"gte": "{}".format(self.start_date.isoformat())}} self.search = self.search.filter("range", **date_dict) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def until(self, end, field=None): """ Add the end date to query data upto that date sets the default end date for each query :param end: date to stop looking at ...
if not field: field = "grimoire_creation_date" self.end_date = end date_dict = {field: {"lte": "{}".format(self.end_date.isoformat())}} self.search = self.search.filter("range", **date_dict) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def by_organizations(self, field=None): """ Used to seggregate the data acording to organizations. This method pops the latest aggregation from the self.aggregat...
# this functions is currently only for issues and PRs agg_field = field if field else "author_org_name" agg_key = "terms_" + agg_field if agg_key in self.aggregations.keys(): agg = self.aggregations[agg_key] else: agg = A("terms", field=agg_field, missin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def by_period(self, field=None, period=None, timezone=None, start=None, end=None): """ Create a date histogram aggregation using the last added aggregation for t...
hist_period = period if period else self.interval_ time_zone = timezone if timezone else "UTC" start_ = start if start else self.start_date end_ = end if end else self.end_date bounds = self.get_bounds(start_, end_) date_field = field if field else "grimoire_creation_...
<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_bounds(self, start=None, end=None): """ Get bounds for the date_histogram method :param start: start date to set the extended_bounds min field :param end...
bounds = {} if start or end: # Extend bounds so we have data until start and end start_ts = None end_ts = None if start: start = start.replace(microsecond=0) start_ts = start.replace(tzinfo=timezone.utc).timestamp() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset_aggregations(self): """ Remove all aggregations added to the search object """
temp_search = self.search.to_dict() if 'aggs' in temp_search.keys(): del temp_search['aggs'] self.search.from_dict(temp_search) self.parent_agg_counter = 0 self.child_agg_counter = 0 self.child_agg_counter_dict = defaultdict(int)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch_aggregation_results(self): """ Loops though the self.aggregations dict and adds them to the Search object in order in which they were created. Queries ...
self.reset_aggregations() for key, val in self.aggregations.items(): self.search.aggs.bucket(self.parent_agg_counter, val) self.parent_agg_counter += 1 self.search = self.search.extra(size=0) response = self.search.execute() self.flush_aggregations() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch_results_from_source(self, *fields, dataframe=False): """ Get values for specific fields in the elasticsearch index, from source :param fields: a list o...
if not fields: raise AttributeError("Please provide the fields to get from elasticsearch!") self.reset_aggregations() self.search = self.search.extra(_source=fields) self.search = self.search.extra(size=self.size) response = self.search.execute() hits = 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 get_timeseries(self, child_agg_count=0, dataframe=False): """ Get time series data for the specified fields and period of analysis :param child_agg_count: th...
res = self.fetch_aggregation_results() ts = {"date": [], "value": [], "unixtime": []} if 'buckets' not in res['aggregations'][str(self.parent_agg_counter - 1)]: raise RuntimeError("Aggregation results have no buckets in time series results.") for bucket in res['aggregati...
<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_aggs(self): """ Compute the values for single valued aggregations :returns: the single aggregation value """
res = self.fetch_aggregation_results() if 'aggregations' in res and 'values' in res['aggregations'][str(self.parent_agg_counter - 1)]: try: agg = res['aggregations'][str(self.parent_agg_counter - 1)]['values']["50.0"] if agg == 'NaN': # E...
<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_list(self, dataframe=False): """ Compute the value for multi-valued aggregations :returns: a dict containing 'keys' and their corresponding 'values' """
res = self.fetch_aggregation_results() keys = [] values = [] for bucket in res['aggregations'][str(self.parent_agg_counter - 1)]['buckets']: keys.append(bucket['key']) values.append(bucket['doc_count']) result = {"keys": keys, "values": 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 upgrade(check_only, yes): ''' Upgrade libreant database. This command can be used after an update of libreant in order to upgrade the database and make it aligned with the new version. ''' from utils.es import Elasticsearch from libreantdb import DB, migration from libreantdb.except...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def insert_volume(language, filepath, notes, metadata): ''' Add a new volume to libreant. The metadata of the volume are taken from a json file whose path must be passed as argument. Passing "-" as argument will read the file from stdin. language is an exception, because it must be set using --lang...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def attach_list(filepaths, notes): ''' all the arguments are lists returns a list of dictionaries; each dictionary "represent" an attachment ''' assert type(filepaths) in (list, tuple) assert type(notes) in (list, tuple) # this if clause means "if those lists are not of the same length" ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _param_fields(kwargs, fields): """ Normalize the "fields" argument to most find methods """
if fields is None: return if type(fields) in [list, set, frozenset, tuple]: fields = {x: True for x in fields} if type(fields) == dict: fields.setdefault("_id", False) kwargs["projection"] = 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 patch_cursor(cursor, batch_size=None, limit=None, skip=None, sort=None, **kwargs): """ Adds batch_size, limit, sort parameters to a DB cursor """
if type(batch_size) == int: cursor.batch_size(batch_size) if limit is not None: cursor.limit(limit) if sort is not None: cursor.sort(sort) if skip is not None: cursor.skip(skip)
<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, query, **args): """ Returns True if the search matches at least one document """
return bool(self.find(query, **args).limit(1).count())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _collection_with_options(self, kwargs): """ Returns a copy of the pymongo collection with various options set up """
# class DocumentClassWithFields(self.document_class): # _fetched_fields = kwargs.get("projection") # mongokat_collection = self read_preference = kwargs.get("read_preference") or getattr(self.collection, "read_preference", None) or ReadPreference.PRIMARY if "read_pref...
<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_by_b64id(self, _id, **kwargs): """ Pass me a base64-encoded ObjectId """
return self.find_one({"_id": ObjectId(base64.b64decode(_id))}, **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 find_by_b64ids(self, _ids, **kwargs): """ Pass me a list of base64-encoded ObjectId """
return self.find_by_ids([ObjectId(base64.b64decode(_id)) for _id in _ids], **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 iter_column(self, query=None, field="_id", **kwargs): """ Return one field as an iterator. Beware that if your query returns records where the field is not s...
find_kwargs = { "projection": {"_id": False} } find_kwargs["projection"][field] = True cursor = self._collection_with_options(kwargs).find(query, **find_kwargs) # We only want 1 field: bypass the ORM patch_cursor(cursor, **kwargs) return (dotdict(x)[field...
<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_random(self, **kwargs): """ return one random document from the collection """
import random max = self.count(**kwargs) if max: num = random.randint(0, max - 1) return next(self.find(**kwargs).skip(num))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insert(self, data, return_object=False): """ Inserts the data as a new document. """
obj = self(data) # pylint: disable=E1102 obj.save() if return_object: return obj else: return obj["_id"]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def trigger(self, event, filter=None, update=None, documents=None, ids=None, replacements=None): """ Trigger the after_save hook on documents, if present. """
if not self.has_trigger(event): return if documents is not None: pass elif ids is not None: documents = self.find_by_ids(ids, read_use="primary") elif filter is not None: documents = self.find(filter, read_use="primary") else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def usage(ecode, msg=''): """ Print usage and msg and exit with given code. """
print >> sys.stderr, __doc__ if msg: print >> sys.stderr, msg sys.exit(ecode)
<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(msgid, transtr, fuzzy): """ Add a non-fuzzy translation to the dictionary. """
global MESSAGES if not fuzzy and transtr and not transtr.startswith('\0'): MESSAGES[msgid] = transtr
<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(): """ Return the generated output. """
global MESSAGES keys = MESSAGES.keys() # the keys are sorted in the .mo file keys.sort() offsets = [] ids = strs = '' for _id in keys: # For each string, we need size and file offset. Each string is NUL # terminated; the NUL does not count into the size. offsets.app...
<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_es_requirements(es_version): '''Get the requirements string for elasticsearch-py library Returns a suitable requirements string for the elsaticsearch-py library according to the elasticsearch version to be supported (es_version)''' # accepts version range in the form `2.x` es_version = es_...
<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(self): """ Compile all message catalogs .po files into .mo files. Skips not changed file based on source mtime. """
# thanks to deluge guys ;) po_dir = os.path.join(os.path.dirname(__file__), 'webant', 'translations') print('Compiling po files from "{}"...'.format(po_dir)) for lang in os.listdir(po_dir): sys.stdout.write("\tCompiling {}... ".format(lang)) sys.stdout.flush() ...
<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_response_element_data(self, key1, key2): """ For each origin an elements object is created in the ouput. For each destination, an object is created ins...
if not self.dict_response[key1][key2]: l = self.response for i, orig in enumerate(self.origins): self.dict_response[key1][key2][orig] = {} for j, dest in enumerate(self.destinations): if l[i]['elements'][j]['status'] == 'OK': ...
<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_closest_points(self, max_distance=None, origin_index=0, origin_raw=None): """ Get closest points to a given origin. Returns a list of 2 element tuples wh...
if not self.dict_response['distance']['value']: self.get_distance_values() if origin_raw: origin = copy.deepcopy(self.dict_response['distance']['value'][origin_raw]) else: origin = copy.deepcopy(self.dict_response['distance']['value'][self.origins[origin_ind...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rename_node(self, prefix): """ Rename AMR graph nodes to prefix + node_index to avoid nodes with the same name in two different AMRs. """
node_map_dict = {} # map each node to its new name (e.g. "a1") for i in range(0, len(self.nodes)): node_map_dict[self.nodes[i]] = prefix + str(i) # update node name for i, v in enumerate(self.nodes): self.nodes[i] = node_map_dict[v] # update node ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bar3_chart(self, title, labels, data1, file_name, data2, data3, legend=["", ""]): """ Generate a bar plot with three columns in each x position and save it t...
colors = ["orange", "grey"] data1 = self.__convert_none_to_zero(data1) data2 = self.__convert_none_to_zero(data2) data3 = self.__convert_none_to_zero(data3) fig, ax = plt.subplots(1) xpos = np.arange(len(data1)) width = 0.28 plt.title(title) y...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sections(self): """ Get the sections of the report and howto build them. :return: a dict with the method to be called to fill each section of the report """
secs = OrderedDict() secs['Overview'] = self.sec_overview secs['Communication Channels'] = self.sec_com_channels secs['Detailed Activity by Project'] = self.sec_projects return secs
<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_text(filepath, to_replace, replacement): """ Replaces a string in a given file with another string :param file: the file in which the string has to b...
with open(filepath) as file: s = file.read() s = s.replace(to_replace, replacement) with open(filepath, 'w') as file: file.write(s)
<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_text_dir(self, directory, to_replace, replacement, file_type=None): """ Replaces a string with its replacement in all the files in the directory :par...
if not file_type: file_type = "*.tex" for file in glob.iglob(os.path.join(directory, file_type)): self.replace_text(file, to_replace, replacement)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pprint_table(table): """ Print a table in pretty format """
col_paddings = [] for i in range(len(table[0])): col_paddings.append(get_max_width(table,i)) for row in table: print(row[0].ljust(col_paddings[0] + 1), end="") for i in range(1, len(row)): col = str(row[i]).rjust(col_paddings[i]+2) print(col, end='') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cb(option, value, parser): """ Callback function to handle variable number of arguments in optparse """
arguments = [value] for arg in parser.rargs: if arg[0] != "-": arguments.append(arg) else: del parser.rargs[:len(arguments)] break if getattr(parser.values, option.dest): arguments.extend(getattr(parser.values, option.dest)) setattr(parser.val...