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 check_ns_run_logls(run, dup_assert=False, dup_warn=False): """Check run logls are unique and in the correct order. Parameters run: dict nested sampling run t...
assert np.array_equal(run['logl'], run['logl'][np.argsort(run['logl'])]) if dup_assert or dup_warn: unique_logls, counts = np.unique(run['logl'], return_counts=True) repeat_logls = run['logl'].shape[0] - unique_logls.shape[0] msg = ('{} duplicate logl values (out of a total of {}). This...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_ns_run_threads(run): """Check thread labels and thread_min_max have expected properties. Parameters run: dict Nested sampling run to check. Raises ----...
assert run['thread_labels'].dtype == int uniq_th = np.unique(run['thread_labels']) assert np.array_equal( np.asarray(range(run['thread_min_max'].shape[0])), uniq_th), \ str(uniq_th) # Check thread_min_max assert np.any(run['thread_min_max'][:, 0] == -np.inf), ( 'Run should h...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def count_samples(ns_run, **kwargs): r"""Number of samples in run. Unlike most estimators this does not require log weights, but for convenience will not throw a...
kwargs.pop('logw', None) kwargs.pop('simulate', None) if kwargs: raise TypeError('Unexpected **kwargs: {0}'.format(kwargs)) return ns_run['logl'].shape[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 get_latex_name(func_in, **kwargs): """ Produce a latex formatted name for each function for use in labelling results. Parameters func_in: function kwargs: di...
if isinstance(func_in, functools.partial): func = func_in.func assert not set(func_in.keywords) & set(kwargs), ( 'kwargs={0} and func_in.keywords={1} contain repeated keys' .format(kwargs, func_in.keywords)) kwargs.update(func_in.keywords) else: func = fu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def weighted_quantile(probability, values, weights): """ Get quantile estimate for input probability given weighted samples using linear interpolation. Parameter...
assert 1 > probability > 0, ( 'credible interval prob= ' + str(probability) + ' not in (0, 1)') assert values.shape == weights.shape assert values.ndim == 1 assert weights.ndim == 1 sorted_inds = np.argsort(values) quantiles = np.cumsum(weights[sorted_inds]) - (0.5 * weights[sorted_inds...
<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_list_error_values(run_list, estimator_list, estimator_names, n_simulate=100, **kwargs): """Gets a data frame with calculation values and error diagnostic...
thread_pvalue = kwargs.pop('thread_pvalue', False) bs_stat_dist = kwargs.pop('bs_stat_dist', False) parallel = kwargs.pop('parallel', True) if kwargs: raise TypeError('Unexpected **kwargs: {0}'.format(kwargs)) assert len(estimator_list) == len(estimator_names), ( 'len(estimator_list...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def estimator_values_df(run_list, estimator_list, **kwargs): """Get a dataframe of estimator values. NB when parallelised the results will not be produced in ord...
estimator_names = kwargs.pop( 'estimator_names', ['est_' + str(i) for i in range(len(estimator_list))]) parallel = kwargs.pop('parallel', True) if kwargs: raise TypeError('Unexpected **kwargs: {0}'.format(kwargs)) values_list = pu.parallel_apply( nestcheck.ns_run_utils.r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def error_values_summary(error_values, **summary_df_kwargs): """Get summary statistics about calculation errors, including estimated implementation errors. Param...
df = pf.summary_df_from_multi(error_values, **summary_df_kwargs) # get implementation stds imp_std, imp_std_unc, imp_frac, imp_frac_unc = \ nestcheck.error_analysis.implementation_std( df.loc[('values std', 'value')], df.loc[('values std', 'uncertainty')], df.loc...
<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_list_error_summary(run_list, estimator_list, estimator_names, n_simulate, **kwargs): """Wrapper which runs run_list_error_values then applies error_value...
true_values = kwargs.pop('true_values', None) include_true_values = kwargs.pop('include_true_values', False) include_rmse = kwargs.pop('include_rmse', False) error_values = run_list_error_values(run_list, estimator_list, estimator_names, n_simulate, **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 bs_values_df(run_list, estimator_list, estimator_names, n_simulate, **kwargs): """Computes a data frame of bootstrap resampled values. Parameters run_list: l...
tqdm_kwargs = kwargs.pop('tqdm_kwargs', {'desc': 'bs values'}) assert len(estimator_list) == len(estimator_names), ( 'len(estimator_list) = {0} != len(estimator_names = {1}' .format(len(estimator_list), len(estimator_names))) bs_values_list = pu.parallel_apply( nestcheck.error_analy...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def thread_values_df(run_list, estimator_list, estimator_names, **kwargs): """Calculates estimator values for the constituent threads of the input runs. Paramete...
tqdm_kwargs = kwargs.pop('tqdm_kwargs', {'desc': 'thread values'}) assert len(estimator_list) == len(estimator_names), ( 'len(estimator_list) = {0} != len(estimator_names = {1}' .format(len(estimator_list), len(estimator_names))) # get thread results thread_vals_arrays = pu.parallel_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 pairwise_dists_on_cols(df_in, earth_mover_dist=True, energy_dist=True): """Computes pairwise statistical distance measures. parameters df_in: pandas data fra...
df = pd.DataFrame() for col in df_in.columns: df[col] = nestcheck.error_analysis.pairwise_distances( df_in[col].values, earth_mover_dist=earth_mover_dist, energy_dist=energy_dist) return df
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _backtick_columns(cols): """ Quote the column names """
def bt(s): b = '' if s == '*' or not s else '`' return [_ for _ in [b + (s or '') + b] if _] formatted = [] for c in cols: if c[0] == '#': formatted.append(c[1:]) elif c.startswith('(') and c.endswith(')'): # WHERE...
<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_columns(self, columns): """ Allow select.group and select.order accepting string and list """
return columns if self.isstr(columns) else self._backtick_columns(columns)
<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_whitespace(txt): """ Returns a list containing the whitespace to the left and right of a string as its two elements """
# if the entire parameter is whitespace rall = re.search(r'^([\s])+$', txt) if rall: tmp = txt.split('\n', 1) if len(tmp) == 2: return (tmp[0], '\n' + tmp[1]) # left, right else: return ('', tmp[0]) # left, right left = '' # find whitespace to the ...
<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_whitespace_pattern(self): """ Try to find a whitespace pattern in the existing parameters to be applied to a newly added parameter """
name_ws = [] value_ws = [] for entry in self._entries: name_ws.append(get_whitespace(entry.name)) if entry.value != '': value_ws.append(get_whitespace(entry._value)) # _value is unstripped if len(value_ws) >= 1: value_ws = most_common...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _path_for_file(self, project_name, date): """ Generate the path on disk for a specified project and date. :param project_name: the PyPI project name for the ...
return os.path.join( self.cache_path, '%s_%s.json' % (project_name, date.strftime('%Y%m%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 get(self, project, date): """ Get the cache data for a specified project for the specified date. Returns None if the data cannot be found in the cache. :para...
fpath = self._path_for_file(project, date) logger.debug('Cache GET project=%s date=%s - path=%s', project, date.strftime('%Y-%m-%d'), fpath) try: with open(fpath, 'r') as fh: data = json.loads(fh.read()) except: logger.debug('...
<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(self, project, date, data, data_ts): """ Set the cache data for a specified project for the specified date. :param project: project name to set data for ...
data['cache_metadata'] = { 'project': project, 'date': date.strftime('%Y%m%d'), 'updated': time.time(), 'version': VERSION, 'data_ts': data_ts } fpath = self._path_for_file(project, date) logger.debug('Cache SET project=%s date...
<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_dates_for_project(self, project): """ Return a list of the dates we have in cache for the specified project, sorted in ascending date order. :param proje...
file_re = re.compile(r'^%s_([0-9]{8})\.json$' % project) all_dates = [] for f in os.listdir(self.cache_path): if not os.path.isfile(os.path.join(self.cache_path, f)): continue m = file_re.match(f) if m is None: continue ...
<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_log_level_format(level, format): """ Set logger level and format. :param level: logging level; see the :py:mod:`logging` constants. :type level: int :par...
formatter = logging.Formatter(fmt=format) logger.handlers[0].setFormatter(formatter) logger.setLevel(level)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pypi_get_projects_for_user(username): """ Given the username of a PyPI user, return a list of all of the user's projects from the XMLRPC interface. See: htt...
client = xmlrpclib.ServerProxy('https://pypi.python.org/pypi') pkgs = client.user_packages(username) # returns [role, package] return [x[1] for x in pkgs]
<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_graph(self): """ Generate the graph; return a 2-tuple of strings, script to place in the head of the HTML document and div content for the graph its...
logger.debug('Generating graph for %s', self._graph_id) # tools to use tools = [ PanTool(), BoxZoomTool(), WheelZoomTool(), SaveTool(), ResetTool(), ResizeTool() ] # generate the stacked area graph ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _line_for_patches(self, data, chart, renderer, series_name): """ Add a line along the top edge of a Patch in a stacked Area Chart; return the new Glyph for a...
# @TODO this method needs a major refactor # get the original x and y values, and color xvals = deepcopy(renderer.data_source.data['x_values'][0]) yvals = deepcopy(renderer.data_source.data['y_values'][0]) line_color = renderer.glyph.fill_color # save original values fo...
<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_empty_cache_record(self, rec): """ Return True if the specified cache record has no data, False otherwise. :param rec: cache record returned by :py:meth:...
# these are taken from DataQuery.query_one_table() for k in [ 'by_version', 'by_file_type', 'by_installer', 'by_implementation', 'by_system', 'by_distro', 'by_country' ]: if k in rec and len(rec[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 _cache_get(self, date): """ Return cache data for the specified day; cache locally in this class. :param date: date to get data for :type date: datetime.date...
if date in self.cache_data: logger.debug('Using class-cached data for date %s', date.strftime('%Y-%m-%d')) return self.cache_data[date] logger.debug('Getting data from cache for date %s', date.strftime('%Y-%m-%d')) data = sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def per_version_data(self): """ Return download data by version. :return: dict of cache data; keys are datetime objects, values are dict of version (str) to coun...
ret = {} for cache_date in self.cache_dates: data = self._cache_get(cache_date) if len(data['by_version']) == 0: data['by_version'] = {'other': 0} ret[cache_date] = data['by_version'] return 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 per_file_type_data(self): """ Return download data by file type. :return: dict of cache data; keys are datetime objects, values are dict of file type (str) t...
ret = {} for cache_date in self.cache_dates: data = self._cache_get(cache_date) if len(data['by_file_type']) == 0: data['by_file_type'] = {'other': 0} ret[cache_date] = data['by_file_type'] return 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 per_installer_data(self): """ Return download data by installer name and version. :return: dict of cache data; keys are datetime objects, values are dict of ...
ret = {} for cache_date in self.cache_dates: data = self._cache_get(cache_date) ret[cache_date] = {} for inst_name, inst_data in data['by_installer'].items(): for inst_ver, count in inst_data.items(): k = self._compound_column_valu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def per_implementation_data(self): """ Return download data by python impelementation name and version. :return: dict of cache data; keys are datetime objects, v...
ret = {} for cache_date in self.cache_dates: data = self._cache_get(cache_date) ret[cache_date] = {} for impl_name, impl_data in data['by_implementation'].items(): for impl_ver, count in impl_data.items(): k = self._compound_column...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def per_system_data(self): """ Return download data by system. :return: dict of cache data; keys are datetime objects, values are dict of system (str) to count (...
ret = {} for cache_date in self.cache_dates: data = self._cache_get(cache_date) ret[cache_date] = { self._column_value(x): data['by_system'][x] for x in data['by_system'] } if len(ret[cache_date]) == 0: 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 per_country_data(self): """ Return download data by country. :return: dict of cache data; keys are datetime objects, values are dict of country (str) to coun...
ret = {} for cache_date in self.cache_dates: data = self._cache_get(cache_date) ret[cache_date] = {} for cc, count in data['by_country'].items(): k = '%s (%s)' % (self._alpha2_to_country(cc), cc) ret[cache_date][k] = 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 per_distro_data(self): """ Return download data by distro name and version. :return: dict of cache data; keys are datetime objects, values are dict of distro...
ret = {} for cache_date in self.cache_dates: data = self._cache_get(cache_date) ret[cache_date] = {} for distro_name, distro_data in data['by_distro'].items(): if distro_name.lower() == 'red hat enterprise linux server': distro_nam...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def downloads_per_day(self): """ Return the number of downloads per day, averaged over the past 7 days of data. :return: average number of downloads per day :rty...
count, num_days = self._downloads_for_num_days(7) res = ceil(count / num_days) logger.debug("Downloads per day = (%d / %d) = %d", count, num_days, res) 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 downloads_per_week(self): """ Return the number of downloads in the last 7 days. :return: number of downloads in the last 7 days; if we have less than 7 days...
if len(self.cache_dates) < 7: logger.error("Only have %d days of data; cannot calculate " "downloads per week", len(self.cache_dates)) return None count, _ = self._downloads_for_num_days(7) logger.debug("Downloads per week = %d", count) r...
<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_project_id(self): """ Get our projectId from the ``GOOGLE_APPLICATION_CREDENTIALS`` creds JSON file. :return: project ID :rtype: str """
fpath = os.environ.get('GOOGLE_APPLICATION_CREDENTIALS', None) if fpath is None: raise Exception('ERROR: No project ID specified, and ' 'GOOGLE_APPLICATION_CREDENTIALS env var is not set') fpath = os.path.abspath(os.path.expanduser(fpath)) logger....
<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_bigquery_service(self): """ Connect to the BigQuery service. Calling ``GoogleCredentials.get_application_default`` requires that you either be running i...
logger.debug('Getting Google Credentials') credentials = GoogleCredentials.get_application_default() logger.debug('Building BigQuery service instance') bigquery_service = build('bigquery', 'v2', credentials=credentials) return bigquery_service
<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_query(self, query): """ Run one query against BigQuery and return the result. :param query: the query to run :type query: str :return: list of per-row r...
query_request = self.service.jobs() logger.debug('Running query: %s', query) start = datetime.now() resp = query_request.query( projectId=self.project_id, body={'query': query} ).execute() duration = datetime.now() - start logger.debug('Query response...
<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_newest_ts_in_table(self, table_name): """ Return the timestamp for the newest record in the given table. :param table_name: name of the table to query :...
logger.debug( 'Querying for newest timestamp in table %s', table_name ) q = "SELECT TIMESTAMP_TO_SEC(MAX(timestamp)) AS max_ts %s;" % ( self._from_for_table(table_name) ) res = self._run_query(q) ts = int(res[0]['max_ts']) logger.debug('Ne...
<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_by_installer(self, table_name): """ Query for download data broken down by installer, for one day. :param table_name: table name to query against :typ...
logger.info('Querying for downloads by installer in table %s', table_name) q = "SELECT file.project, details.installer.name, " \ "details.installer.version, COUNT(*) as dl_count " \ "%s " \ "%s " \ "GROUP BY file.project, details.insta...
<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_by_system(self, table_name): """ Query for download data broken down by system, for one day. :param table_name: table name to query against :type tabl...
logger.info('Querying for downloads by system in table %s', table_name) q = "SELECT file.project, details.system.name, COUNT(*) as dl_count " \ "%s " \ "%s " \ "GROUP BY file.project, details.system.name;" % ( self._from_for_table(...
<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_by_distro(self, table_name): """ Query for download data broken down by OS distribution, for one day. :param table_name: table name to query against :...
logger.info('Querying for downloads by distro in table %s', table_name) q = "SELECT file.project, details.distro.name, " \ "details.distro.version, COUNT(*) as dl_count " \ "%s " \ "%s " \ "GROUP BY file.project, details.distro.name, " \ "deta...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _have_cache_for_date(self, dt): """ Return True if we have cached data for all projects for the specified datetime. Return False otherwise. :param dt: dateti...
for p in self.projects: if self.cache.get(p, dt) is None: 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 backfill_history(self, num_days, available_table_names): """ Backfill historical data for days that are missing. :param num_days: number of days of historica...
if num_days == -1: # skip the first date, under the assumption that data may be # incomplete logger.info('Backfilling all available history') start_table = available_table_names[1] else: logger.info('Backfilling %d days of history', num_days) ...
<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_queries(self, backfill_num_days=7): """ Run the data queries for the specified projects. :param backfill_num_days: number of days of historical data to b...
available_tables = self._get_download_table_ids() logger.debug('Found %d available download tables: %s', len(available_tables), available_tables) today_table = available_tables[-1] yesterday_table = available_tables[-2] self.query_one_table(today_table) ...
<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_html(self): """ Generate the HTML for the specified graphs. :return: :rtype: """
logger.debug('Generating templated HTML') env = Environment( loader=PackageLoader('pypi_download_stats', 'templates'), extensions=['jinja2.ext.loopcontrols']) env.filters['format_date_long'] = filter_format_date_long env.filters['format_date_ymd'] = filter_format...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _limit_data(self, data): """ Find the per-day average of each series in the data over the last 7 days; drop all but the top 10. :param data: original graph d...
if len(data.keys()) <= 10: logger.debug("Data has less than 10 keys; not limiting") return data # average last 7 days of each series avgs = {} for k in data: if len(data[k]) <= 7: vals = data[k] else: vals =...
<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_graph(self, name, title, stats_data, y_name): """ Generate a downloads graph; append it to ``self._graphs``. :param name: HTML name of the graph, a...
logger.debug('Generating chart data for %s graph', name) orig_data, labels = self._data_dict_to_bokeh_chart_data(stats_data) data = self._limit_data(orig_data) logger.debug('Generating %s graph', name) script, div = FancyAreaGraph( name, '%s %s' % (self.project_name,...
<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_badges(self): """ Generate download badges. Append them to ``self._badges``. """
daycount = self._stats.downloads_per_day day = self._generate_badge('Downloads', '%d/day' % daycount) self._badges['per-day'] = day weekcount = self._stats.downloads_per_week if weekcount is None: # we don't have enough data for week (or month) return ...
<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_badge(self, subject, status): """ Generate SVG for one badge via shields.io. :param subject: subject; left-hand side of badge :type subject: str :p...
url = 'https://img.shields.io/badge/%s-%s-brightgreen.svg' \ '?style=flat&maxAge=3600' % (subject, status) logger.debug("Getting badge for %s => %s (%s)", subject, status, url) res = requests.get(url) if res.status_code != 200: raise Exception("Error: got statu...
<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(self): """ Generate all output types and write to disk. """
logger.info('Generating graphs') self._generate_graph( 'by-version', 'Downloads by Version', self._stats.per_version_data, 'Version' ) self._generate_graph( 'by-file-type', 'Downloads by File Type', 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 datetime_from_iso(iso_string): """ Create a DateTime object from a ISO string .. code :: python reusables.datetime_from_iso('2017-03-10T12:56:55.031863') dat...
try: assert datetime_regex.datetime.datetime.match(iso_string).groups()[0] except (ValueError, AssertionError, IndexError, AttributeError): raise TypeError("String is not in ISO format") try: return datetime.datetime.strptime(iso_string, "%Y-%m-%dT%H:%M:%S.%f") except ValueError...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def now(utc=False, tz=None): """ Get a current DateTime object. By default is local. .. code:: python reusables.now() # DateTime(2016, 12, 8, 22, 5, 2, 517000) r...
return datetime.datetime.utcnow() if utc else datetime.datetime.now(tz=tz)
<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(command, input=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=None, copy_local_env=False, **kwargs): """ Cross platform compatible subproc...
if copy_local_env: # Copy local env first and overwrite with anything manually specified env = os.environ.copy() env.update(kwargs.get('env', {})) else: env = kwargs.get('env') if sys.version_info >= (3, 5): return subprocess.run(command, input=input, stdout=stdout,...
<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_in_pool(target, iterable, threaded=True, processes=4, asynchronous=False, target_kwargs=None): """ Run a set of iterables to a function in a Threaded or ...
my_pool = pool.ThreadPool if threaded else pool.Pool if target_kwargs: target = partial(target, **target_kwargs if target_kwargs else None) p = my_pool(processes) try: results = (p.map_async(target, iterable) if asynchronous else p.map(target, iterable)) finally...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tree_view(dictionary, level=0, sep="| "): """ View a dictionary as a tree. """
return "".join(["{0}{1}\n{2}".format(sep * level, k, tree_view(v, level + 1, sep=sep) if isinstance(v, dict) else "") for k, v in dictionary.items()])
<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, in_dict=None): """ Turn the Namespace and sub Namespaces back into a native python dictionary. :param in_dict: Do not use, for self recursion :...
in_dict = in_dict if in_dict else self out_dict = dict() for k, v in in_dict.items(): if isinstance(v, Namespace): v = v.to_dict() out_dict[k] = v return out_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 list(self, item, default=None, spliter=",", strip=True, mod=None): """ Return value of key as a list :param item: key of value to transform :param mod: funct...
try: item = self.__getattr__(item) except AttributeError as err: if default is not None: return default raise err if strip: item = item.lstrip("[").rstrip("]") out = [x.strip() if strip else x for x in item.split(spliter)] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download(url, save_to_file=True, save_dir=".", filename=None, block_size=64000, overwrite=False, quiet=False): """ Download a given URL to either file or mem...
if save_to_file: if not filename: filename = safe_filename(url.split('/')[-1]) if not filename: filename = "downloaded_at_{}.file".format(time.time()) save_location = os.path.abspath(os.path.join(save_dir, filename)) if os.path.exists(save_location) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def url_to_ips(url, port=None, ipv6=False, connect_type=socket.SOCK_STREAM, proto=socket.IPPROTO_TCP, flags=0): """ Provide a list of IP addresses, uses `socket....
try: results = socket.getaddrinfo(url, port, (socket.AF_INET if not ipv6 else socket.AF_INET6), connect_type, proto, flag...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ip_to_url(ip_addr): """ Resolve a hostname based off an IP address. This is very limited and will probably not return any results if it is a shared IP addres...
try: return socket.gethostbyaddr(ip_addr)[0] except (socket.gaierror, socket.herror): logger.exception("Could not resolve hostname")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self): """Create a background thread for httpd and serve 'forever'"""
self._process = threading.Thread(target=self._background_runner) self._process.start()
<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_stream_handler(stream=sys.stderr, level=logging.INFO, log_format=log_formats.easy_read): """ Returns a set up stream handler to add to a logger. :param s...
sh = logging.StreamHandler(stream) sh.setLevel(level) sh.setFormatter(logging.Formatter(log_format)) return sh
<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_file_handler(file_path="out.log", level=logging.INFO, log_format=log_formats.easy_read, handler=logging.FileHandler, **handler_kwargs): """ Set up a file...
fh = handler(file_path, **handler_kwargs) fh.setLevel(level) fh.setFormatter(logging.Formatter(log_format)) return fh
<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_logger(module_name=None, level=logging.INFO, stream=sys.stderr, file_path=None, log_format=log_formats.easy_read, suppress_warning=True): """ Grabs the...
new_logger = logging.getLogger(module_name) if stream: new_logger.addHandler(get_stream_handler(stream, level, log_format)) elif not file_path and suppress_warning and not new_logger.handlers: new_logger.addHandler(logging.NullHandler()) if file_path: new_logger.addHandler...
<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_stream_handler(logger=None, stream=sys.stderr, level=logging.INFO, log_format=log_formats.easy_read): """ Addes a newly created stream handler to the spe...
if not isinstance(logger, logging.Logger): logger = logging.getLogger(logger) logger.addHandler(get_stream_handler(stream, level, log_format))
<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_file_handler(logger=None, file_path="out.log", level=logging.INFO, log_format=log_formats.easy_read): """ Addes a newly created file handler to the speci...
if not isinstance(logger, logging.Logger): logger = logging.getLogger(logger) logger.addHandler(get_file_handler(file_path, level, log_format))
<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_rotating_file_handler(logger=None, file_path="out.log", level=logging.INFO, log_format=log_formats.easy_read, max_bytes=10*sizes.mb, backup_count=5, **han...
if not isinstance(logger, logging.Logger): logger = logging.getLogger(logger) logger.addHandler(get_file_handler(file_path, level, log_format, handler=RotatingFileHandler, maxBytes=max_bytes, ...
<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_timed_rotating_file_handler(logger=None, file_path="out.log", level=logging.INFO, log_format=log_formats.easy_read, when='w0', interval=1, backup_count=5,...
if not isinstance(logger, logging.Logger): logger = logging.getLogger(logger) logger.addHandler(get_file_handler(file_path, level, log_format, handler=TimedRotatingFileHandler, when=when, ...
<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_stream_handlers(logger=None): """ Remove only stream handlers from the specified logger :param logger: logging name or object to modify, defaults to r...
if not isinstance(logger, logging.Logger): logger = logging.getLogger(logger) new_handlers = [] for handler in logger.handlers: # FileHandler is a subclass of StreamHandler so # 'if not a StreamHandler' does not work if (isinstance(handler, logging.FileHandler) or ...
<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_file_handlers(logger=None): """ Remove only file handlers from the specified logger. Will go through and close each handler for safety. :param logger:...
if not isinstance(logger, logging.Logger): logger = logging.getLogger(logger) new_handlers = [] for handler in logger.handlers: if isinstance(handler, logging.FileHandler): handler.close() else: new_handlers.append(handler) logger.handlers = new_handlers
<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_all_handlers(logger=None): """ Safely remove all handlers from the logger :param logger: logging name or object to modify, defaults to root logger """
if not isinstance(logger, logging.Logger): logger = logging.getLogger(logger) remove_file_handlers(logger) logger.handlers = []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def change_logger_levels(logger=None, level=logging.DEBUG): """ Go through the logger and handlers and update their levels to the one specified. :param logger: l...
if not isinstance(logger, logging.Logger): logger = logging.getLogger(logger) logger.setLevel(level) for handler in logger.handlers: handler.level = level
<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_registered_loggers(hide_children=False, hide_reusables=False): """ Find the names of all loggers currently registered :param hide_children: only return t...
return [logger for logger in logging.Logger.manager.loggerDict.keys() if not (hide_reusables and "reusables" in logger) and not (hide_children and "." in logger)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unique(max_retries=10, wait=0, alt_return="-no_alt_return-", exception=Exception, error_text=None): """ Wrapper. Makes sure the function's return value has n...
def func_wrap(func): @wraps(func) def wrapper(*args, **kwargs): msg = (error_text if error_text else "No result was unique for function '{func}'") if not error_text: msg = _add_args(msg, *args, **kwargs) for i in range(max_retri...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lock_it(lock=g_lock): """ Wrapper. Simple wrapper to make sure a function is only run once at a time. .. code: python import reusables import time def func_o...
def func_wrapper(func): @wraps(func) def wrapper(*args, **kwargs): with lock: return func(*args, **kwargs) return wrapper return func_wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def time_it(log=None, message=None, append=None): """ Wrapper. Time the amount of time it takes the execution of the function and print it. If log is true, make ...
def func_wrapper(func): @wraps(func) def wrapper(*args, **kwargs): # Can't use nonlocal in 2.x msg = (message if message else "Function '{func}' took a total of {seconds} seconds") if not message: msg = _add_args(msg, *args, **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 queue_it(queue=g_queue, **put_args): """ Wrapper. Instead of returning the result of the function, add it to a queue. .. code: python import reusables import...
def func_wrapper(func): @wraps(func) def wrapper(*args, **kwargs): queue.put(func(*args, **kwargs), **put_args) return wrapper return func_wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_exception(log="reusables", message=None, exceptions=(Exception, ), level=logging.ERROR, show_traceback=True): """ Wrapper. Log the traceback to any excep...
def func_wrapper(func): @wraps(func) def wrapper(*args, **kwargs): msg = message if message else "Exception in '{func}': {err}" if not message: msg = _add_args(msg, *args, **kwargs) try: return func(*args, **kwargs) ex...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def catch_it(exceptions=(Exception, ), default=None, handler=None): """ If the function encounters an exception, catch it, and return the specified default or se...
def func_wrapper(func): @wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except exceptions as err: if handler: return handler(err, func, *args, **kwargs) return default 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 retry_it(exceptions=(Exception, ), tries=10, wait=0, handler=None, raised_exception=ReusablesError, raised_message=None): """ Retry a function if an exceptio...
def func_wrapper(func): @wraps(func) def wrapper(*args, **kwargs): msg = (raised_message if raised_message else "Max retries exceeded for function '{func}'") if not raised_message: msg = _add_args(msg, *args, **kwargs) try: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract(archive_file, path=".", delete_on_success=False, enable_rar=False): """ Automatically detect archive type and extract all files to specified path. .....
if not os.path.exists(archive_file) or not os.path.getsize(archive_file): logger.error("File {0} unextractable".format(archive_file)) raise OSError("File does not exist or has zero size") arch = None if zipfile.is_zipfile(archive_file): logger.debug("File {0} detected as a zip fil...
<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_json(json_file, **kwargs): """ Open and load data from a JSON file .. code:: python reusables.load_json("example.json") # {u'key_1': u'val_1', u'key_for...
with open(json_file) as f: return json.load(f, **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_json(data, json_file, indent=4, **kwargs): """ Takes a dictionary and saves it to a file as JSON .. code:: python my_dict = {"key_1": "val_1", "key_for_...
with open(json_file, "w") as f: json.dump(data, f, indent=indent, **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 config_namespace(config_file=None, auto_find=False, verify=True, **cfg_options): """ Return configuration options as a Namespace. .. code:: python reusables....
return ConfigNamespace(**config_dict(config_file, auto_find, verify, **cfg_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 _walk(directory, enable_scandir=False, **kwargs): """ Internal function to return walk generator either from os or scandir :param directory: directory to tra...
walk = os.walk if python_version < (3, 5) and enable_scandir: import scandir walk = scandir.walk return walk(directory, **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 os_tree(directory, enable_scandir=False): """ Return a directories contents as a dictionary hierarchy. .. code:: python reusables.os_tree(".") # {'doc': {'bu...
if not os.path.exists(directory): raise OSError("Directory does not exist") if not os.path.isdir(directory): raise OSError("Path is not a directory") full_list = [] for root, dirs, files in _walk(directory, enable_scandir=enable_scandir): full_list.extend([os.path.join(root, 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 file_hash(path, hash_type="md5", block_size=65536, hex_digest=True): """ Hash a given file with md5, or any other and return the hex digest. You can run `has...
hashed = hashlib.new(hash_type) with open(path, "rb") as infile: buf = infile.read(block_size) while len(buf) > 0: hashed.update(buf) buf = infile.read(block_size) return hashed.hexdigest() if hex_digest else hashed.digest()
<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_files(directory=".", ext=None, name=None, match_case=False, disable_glob=False, depth=None, abspath=False, enable_scandir=False): """ Walk through a fil...
if ext or not name: disable_glob = True if not disable_glob: disable_glob = not glob.has_magic(name) if ext and isinstance(ext, str): ext = [ext] elif ext and not isinstance(ext, (list, tuple)): raise TypeError("extension must be either one extension or a list") if ...
<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_empty_directories(root_directory, dry_run=False, ignore_errors=True, enable_scandir=False): """ Remove all empty folders from a path. Returns list of ...
listdir = os.listdir if python_version < (3, 5) and enable_scandir: import scandir as _scandir def listdir(directory): return list(_scandir.scandir(directory)) directory_list = [] for root, directories, files in _walk(root_directory, ...
<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_empty_files(root_directory, dry_run=False, ignore_errors=True, enable_scandir=False): """ Remove all empty files from a path. Returns list of the empt...
file_list = [] for root, directories, files in _walk(root_directory, enable_scandir=enable_scandir): for file_name in files: file_path = join_paths(root, file_name, strict=True) if os.path.isfile(file_path) and not os.path.getsize(file_p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dup_finder(file_path, directory=".", enable_scandir=False): """ Check a directory for duplicates of the specified file. This is meant for a single file only,...
size = os.path.getsize(file_path) if size == 0: for empty_file in remove_empty_files(directory, dry_run=True): yield empty_file else: with open(file_path, 'rb') as f: first_twenty = f.read(20) file_sha256 = file_hash(file_path, "sha256") for root, di...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def directory_duplicates(directory, hash_type='md5', **kwargs): """ Find all duplicates in a directory. Will return a list, in that list are lists of duplicate f...
size_map, hash_map = defaultdict(list), defaultdict(list) for item in find_files(directory, **kwargs): file_size = os.path.getsize(item) size_map[file_size].append(item) for possible_dups in (v for v in size_map.values() if len(v) > 1): for each_item in possible_dups: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def join_paths(*paths, **kwargs): """ Join multiple paths together and return the absolute path of them. If 'safe' is specified, this function will 'clean' the p...
path = os.path.abspath(paths[0]) for next_path in paths[1:]: path = os.path.join(path, next_path.lstrip("\\").lstrip("/").strip()) path.rstrip(os.sep) return path if not kwargs.get('safe') else safe_path(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 join_here(*paths, **kwargs): """ Join any path or paths as a sub directory of the current file's directory. .. code:: python reusables.join_here("Makefile") ...
path = os.path.abspath(".") for next_path in paths: next_path = next_path.lstrip("\\").lstrip("/").strip() if not \ kwargs.get('strict') else next_path path = os.path.abspath(os.path.join(path, next_path)) return path if not kwargs.get('safe') else safe_path(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 safe_path(path, replacement="_"): """ Replace unsafe path characters with underscores. Do NOT use this with existing paths that cannot be modified, this to t...
if not isinstance(path, str): raise TypeError("path must be a string") if os.sep not in path: return safe_filename(path, replacement=replacement) filename = safe_filename(os.path.basename(path)) dirname = os.path.dirname(path) safe_dirname = "" regexp = regex.path.windows.safe i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def change_task_size(self, size): """Blocking request to change number of running tasks"""
self._pause.value = True self.log.debug("About to change task size to {0}".format(size)) try: size = int(size) except ValueError: self.log.error("Cannot change task size, non integer size provided") return False if size < 0: self.l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop(self): """Hard stop the server and sub process"""
self._end.value = True if self.background_process: try: self.background_process.terminate() except Exception: pass for task_id, values in self.current_tasks.items(): try: values['proc'].terminate() 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_state(self): """Get general information about the state of the class"""
return {"started": (True if self.background_process and self.background_process.is_alive() else False), "paused": self._pause.value, "stopped": self._end.value, "tasks": len(self.current_tasks), "busy_tasks": len(self.b...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main_loop(self, stop_at_empty=False): """Blocking function that can be run directly, if so would probably want to specify 'stop_at_empty' to true, or have a ...
try: while True: self.hook_pre_command() self._check_command_queue() if self.run_until and self.run_until < datetime.datetime.now(): self.log.info("Time limit reached") break if self._end.value: ...