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 load(self, value): """ enforce env > value when loading from file """
self.reset( value, validator=self.__dict__.get('validator'), env=self.__dict__.get('env'), )
<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_img_path(instance, filename): """ Sets upload_to dynamically """
upload_path = '/'.join( ['img', instance._meta.app_label, str(now.year), str(now.month), filename] ) return upload_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 save(self, *args, **kwargs): """ Clean text and save formatted version. """
self.text = clean_text(self.text) self.text_formatted = format_text(self.text) super(BaseUserContentModel, self).save(*args, **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 enqueue(self, job): """Enqueue a job for later processing, returns the new length of the queue """
if job.queue_name(): raise EnqueueError("job %s already queued!" % job.job_id) new_len = self.redis.lpush(self.queue_name, job.serialize()) job.notify_queued(self) return new_len
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def next_job(self, timeout_seconds=None): """Retuns the next job in the queue, or None if is nothing there """
if timeout_seconds is not None: timeout = timeout_seconds else: timeout = BLOCK_SECONDS response = self.lua_next(keys=[self.queue_name]) if not response: return job = Job.from_serialized(response) if not job: self.log.warn("could not deserialize job from: %s", serialized_job) return job
<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_headline_from_description(sender, instance, *args, **kwargs): ''' Auto generate the headline of the node from the first lines of the description. ''' lines = instance.description.split('\n') headline = truncatewords(lines[0], 20) if headline[:-3] == '...': headline = truncatechars(headline.replace(' ...', ''), 250) # Just in case the words exceed char limit. else: headline = truncatechars(headline, 250) instance.headline = headline
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def story_root_for_new_outline(sender, instance, created, *args, **kwargs): ''' If a new instance of a Outline is created, also create the root node of the story tree. ''' if created and isinstance(instance, Outline): streeroot = StoryElementNode.add_root(outline=instance, story_element_type='root') streeroot.save() instance.refresh_from_db()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def story_node_add_arc_element_update_characters_locations(sender, instance, created, *args, **kwargs): ''' If an arc element is added to a story element node, add any missing elements or locations. ''' arc_node = ArcElementNode.objects.get(pk=instance.pk) logger.debug('Scanning arc_node %s' % arc_node) if arc_node.arc_element_type == 'root': logger.debug("root node. skipping...") else: logger.debug('Checking arc node for story element relationship...') if arc_node.story_element_node: logger.debug('Found a story element node for arc element...') # This change was initiated by the arc element node as opposed to the story node. story_node = arc_node.story_element_node if arc_node.assoc_characters.count() > 0: logger.debug('Found %d characters to add...' % arc_node.assoc_characters.count()) for character in arc_node.assoc_characters.all(): story_node.assoc_characters.add(character) if arc_node.assoc_locations.count() > 0: logger.debug('Found %d locations to add...' % arc_node.assoc_locations.count()) for location in arc_node.assoc_locations.all(): story_node.assoc_locations.add(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 validate_arc_links_same_outline(sender, instance, *args, **kwargs): ''' Evaluates attempts to link an arc to a story node from another outline. ''' if instance.story_element_node: if instance.story_element_node.outline != instance.parent_outline: raise IntegrityError(_('An arc cannot be associated with an story element from another outline.'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def validate_character_instance_valid_for_arc(sender, instance, action, reverse, pk_set, *args, **kwargs): ''' Evaluate attempts to assign a character instance to ensure it is from same outline. ''' if action == 'pre_add': if reverse: # Fetch arc definition through link. for apk in pk_set: arc_node = ArcElementNode.objects.get(pk=apk) if arc_node.parent_outline != instance.outline: raise IntegrityError(_('Character Instance and Arc Element must be from same outline.')) else: for cpk in pk_set: char_instance = CharacterInstance.objects.get(pk=cpk) if char_instance.outline != instance.parent_outline: raise IntegrityError(_('Character Instance and Arc Element must be from the same outline.'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def validate_location_instance_valid_for_arc(sender, instance, action, reverse, pk_set, *args, **kwargs): ''' Evaluates attempts to add location instances to arc, ensuring they are from same outline. ''' if action == 'pre_add': if reverse: # Fetch arc definition through link. for apk in pk_set: arc_node = ArcElementNode.objects.get(pk=apk) if arc_node.parent_outline != instance.outline: raise IntegrityError(_('Location instance must be from same outline as arc element.')) else: for lpk in pk_set: loc_instance = LocationInstance.objects.get(pk=lpk) if loc_instance.outline != instance.parent_outline: raise IntegrityError(_('Location Instance must be from the same outline as arc element.'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def validate_character_for_story_element(sender, instance, action, reverse, pk_set, *args, **kwargs): ''' Validates that character is from the same outline as the story node. ''' if action == 'pre_add': if reverse: for spk in pk_set: story_node = StoryElementNode.objects.get(pk=spk) if instance.outline != story_node.outline: raise IntegrityError(_('Character Instance must be from the same outline as story node.')) else: for cpk in pk_set: char_instance = CharacterInstance.objects.get(pk=cpk) if char_instance.outline != instance.outline: raise IntegrityError(_('Character Instance must be from the same outline as story 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 validate_location_for_story_element(sender, instance, action, reverse, pk_set, *args, **kwargs): ''' Validates that location is from same outline as story node. ''' if action == 'pre_add': if reverse: for spk in pk_set: story_node = StoryElementNode.objects.get(pk=spk) if instance.outline != story_node.outline: raise IntegrityError(_('Location must be from same outline as story node.')) else: for lpk in pk_set: loc_instance = LocationInstance.objects.get(pk=lpk) if instance.outline != loc_instance.outline: raise IntegrityError(_('Location must be from the same outline as story 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 options(self, request, *args, **kwargs): """ Handles responding to requests for the OPTIONS HTTP verb """
response = HttpResponse() response['Allow'] = ', '.join(self.allowed_methods) response['Content-Length'] = 0 return 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 is_python2_identifier(possible_identifier): """ Returns `True` if the given `possible_identifier` can be used as an identifier in Python 2. """
match = _python2_identifier_re.match(possible_identifier) return bool(match) and not iskeyword(possible_identifier)
<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_python3_identifier(possible_identifier): """ Returns `True` if the given `possible_identifier` can be used as an identifier in Python 3. """
possible_identifier = unicodedata.normalize('NFKC', possible_identifier) return ( bool(possible_identifier) and _is_in_id_start(possible_identifier[0]) and all(map(_is_in_id_continue, possible_identifier[1:])) ) and not iskeyword(possible_identifier)
<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(iterable): """ Returns an iterator that yields the first occurence of a hashable item in `iterable`. """
seen = set() for obj in iterable: if obj not in seen: yield obj seen.add(obj)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def contains(self, x, y) -> bool: """" Checks if the given x, y position is within the area of this region. """
if x < self._left or x > self._right or y < self._top or y > self._bottom: 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 is_in_bounds(self, width, height) -> bool: """ Check if this entire region is contained within the bounds of a given stage size."""
if self._top < 0 \ or self._bottom > height \ or self._left < 0 \ or self._right > width: 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 canvas_resize(self, scale): """ Resize this region against the entire axis space. """
self._top *= scale self._bottom *= scale self._left *= scale self._right *= scale self._calibrate_to_rect()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def distance(r1: 'Region', r2: 'Region'): """ Calculate distance between the x and y of the two regions."""
return math.sqrt((r2.x - r1.x) ** 2 + (r2.y - r1.y) ** 2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fast_distance(r1: 'Region', r2: 'Region'): """ A quicker way of calculating approximate distance. Lower accuracy but faster results."""
return abs(r1.x - r2.x) + abs(r1.y - r2.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 rms(x): """"Root Mean Square" Arguments: x (seq of float): A sequence of numerical values Returns: The square root of the average of the squares of the values math.sqrt(sum(x_i**2 for x_i in x) / len(x)) or return (np.array(x) ** 2).mean() ** 0.5 3.0 """
try: return (np.array(x) ** 2).mean() ** 0.5 except: x = np.array(dropna(x)) invN = 1.0 / len(x) return (sum(invN * (x_i ** 2) for x_i in x)) ** .5
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rmse(target, prediction, relative=False, percent=False): """Root Mean Square Error This seems like a simple formula that you'd never need to create a function for. But my mistakes on coding challenges have convinced me that I do need it, as a reminder of important tweaks, if nothing else. 3.0 """
relative = relative or percent prediction = pd.np.array(prediction) target = np.array(target) err = prediction - target if relative: denom = target # Avoid ZeroDivisionError: divide by prediction rather than target where target==0 denom[denom == 0] = prediction[denom == 0] # If the prediction and target are both 0, then the error is 0 and should be included in the RMSE # Otherwise, the np.isinf() below would remove all these zero-error predictions from the array. denom[(denom == 0) & (target == 0)] = 1 err = (err / denom) err = err[(~ np.isnan(err)) & (~ np.isinf(err))] return 100 * rms(err) if percent else rms(err)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pandas_mesh(df): """Create numpy 2-D "meshgrid" from 3+ columns in a Pandas DataFrame Arguments: df (DataFrame): Must have 3 or 4 columns of numerical data Returns: OrderedDict: column labels from the data frame are the keys, values are 2-D matrices All matrices have shape NxM, where N = len(set(df.iloc[:,0])) and M = len(set(df.iloc[:,1])) [array([[ 0, 6, 12], [ 0, 6, 12], [ 0, 6, 12]]), array([[ 1, 1, 1], [ 7, 7, 7], [13, 13, 13]]), array([[ 2., nan, nan], [ nan, 8., nan], [ nan, nan, 14.]]), array([[ 3., nan, nan], [ nan, 9., nan], [ nan, nan, 15.]]), array([[ 4., nan, nan], [ nan, 10., nan], [ nan, nan, 16.]]), array([[ 5., nan, nan], [ nan, 11., nan], [ nan, nan, 17.]])] """
xyz = [df[c].values for c in df.columns] index = pd.MultiIndex.from_tuples(zip(xyz[0], xyz[1]), names=['x', 'y']) # print(index) series = [pd.Series(values, index=index) for values in xyz[2:]] # print(series) X, Y = np.meshgrid(sorted(list(set(xyz[0]))), sorted(list(set(xyz[1])))) N, M = X.shape Zs = [] # print(Zs) for k, s in enumerate(series): Z = np.empty(X.shape) Z[:] = np.nan for i, j in itertools.product(range(N), range(M)): Z[i, j] = s.get((X[i, j], Y[i, j]), np.NAN) Zs += [Z] return OrderedDict((df.columns[i], m) for i, m in enumerate([X, Y] + Zs))
<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_integrator(integrator): """Return the scipy.integrator indicated by an index, name, or integrator_function >> get_integrator(0) """
integrator_types = set(['trapz', 'cumtrapz', 'simps', 'romb']) integrator_funcs = [integrate.trapz, integrate.cumtrapz, integrate.simps, integrate.romb] if isinstance(integrator, int) and 0 <= integrator < len(integrator_types): integrator = integrator_types[integrator] if isinstance(integrator, basestring) and integrator in integrator_types: return getattr(integrate, integrator) elif integrator in integrator_funcs: return integrator else: print('Unsupported integration rule: {0}'.format(integrator)) print('Expecting one of these sample-based integration rules: %s' % (str(list(integrator_types)))) raise AttributeError return integrator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def square_off(series, time_delta=None, transition_seconds=1): """Insert samples in regularly sampled data to produce stairsteps from ramps when plotted. New samples are 1 second (1e9 ns) before each existing samples, to facilitate plotting and sorting 2014-01-31 00:00:00 0 2014-01-31 00:00:05.500000 0 2015-04-30 00:00:00 1 2015-04-30 00:00:05.500000 1 2016-07-31 00:00:00 2 2016-07-31 00:00:05.500000 2 dtype: int64 2014-01-01 00:00:00 0 2014-01-01 00:14:57.500000 0 2014-01-01 00:15:00 1 2014-01-01 00:29:57.500000 1 dtype: int64 """
if time_delta: # int, float means delta is in seconds (not years!) if isinstance(time_delta, (int, float)): time_delta = datetime.timedelta(0, time_delta) new_times = series.index + time_delta else: diff = np.diff(series.index) time_delta = np.append(diff, [diff[-1]]) new_times = series.index + time_delta new_times = pd.DatetimeIndex(new_times) - datetime.timedelta(0, transition_seconds) return pd.concat([series, pd.Series(series.values, index=new_times)]).sort_index()
<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_time_series(serieses, ignore_year=False, T_s=None, aggregator='mean'): """Combine a dict of pd.Series objects into a single pd.DataFrame with optional downsampling FIXME: For ignore_year and multi-year data, the index (in seconds) is computed assuming 366 days per year (leap year). So 3 out of 4 years will have a 1-day (86400 s) gap Arguments: series (dict of Series): dictionary of named timestamp-indexed Series objects ignore_year (bool): ignore the calendar year, but not the season (day of year) If True, the DataFrame index will be seconds since the beginning of the year in each Series index, i.e. midnight Jan 1, 2014 will have index=0 as will Jan 1, 2010 if two Series start on those two dates. T_s (float): sample period in seconds (for downsampling) aggregator (str or func): e.g. 'mean', 'sum', np.std """
if ignore_year: df = pd.DataFrame() for name, ts in serieses.iteritems(): # FIXME: deal with leap years sod = np.array(map(lambda x: (x.hour * 3600 + x.minute * 60 + x.second), ts.index.time)) # Coerce soy to an integer so that merge/join operations identify same values # (floats don't equal!?) soy = (ts.index.dayofyear + 366 * (ts.index.year - ts.index.year[0])) * 3600 * 24 + sod ts2 = pd.Series(ts.values, index=soy) ts2 = ts2.dropna() ts2 = ts2.sort_index() df2 = pd.DataFrame({name: ts2.values}, index=soy) df = df.join(df2, how='outer') if T_s and aggregator: df = df.groupby(lambda x: int(x / float(T_s))).aggregate(dict((name, aggregator) for name in df.columns)) else: df = pd.DataFrame(serieses) if T_s and aggregator: x0 = df.index[0] df = df.groupby(lambda x: int((x - x0).total_seconds() / float(T_s))).aggregate(dict((name, aggregator) for name in df.columns)) # FIXME: convert seconds since begninning of first year back into Timestamp instances 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 smooth(x, window_len=11, window='hanning', fill='reflect'): """smooth the data using a window with requested size. Convolve a normalized window with the signal. input: x: signal to be smoothed window_len: the width of the smoothing window window: the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman' flat window will produce a moving average smoothing. fill: 'reflect' means that the signal is reflected onto both ends before filtering output: the smoothed signal example: t = linspace(-2, 2, 0.1) x = sin(t) + 0.1 * randn(len(t)) y = smooth(x) import seaborn pd.DataFrame({'x': x, 'y': y}, index=t).plot() SEE ALSO: numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman numpy.convolve scipy.signal.lfilter TODO: the window parameter could be the window itself if an array instead of a string NOTE: length(output) != length(input), to correct this: instead of just y. References: http://wiki.scipy.org/Cookbook/SignalSmooth """
# force window_len to be an odd integer so it can be symmetrically applied window_len = int(window_len) window_len += int(not (window_len % 2)) half_len = (window_len - 1) / 2 if x.ndim != 1: raise ValueError("smooth only accepts 1 dimension arrays.") if x.size < window_len: raise ValueError("Input vector needs to be bigger than window size.") if window_len < 3: return x if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']: raise ValueError("The window arg ({}) should be 'flat', 'hanning', 'hamming', 'bartlett', or 'blackman'" .format(window)) s = np.r_[x[window_len - 1:0:-1], x, x[-1:-window_len:-1]] window = window.strip().lower() if window is None or window == 'flat': w = np.ones(window_len, 'd') else: w = getattr(np, window)(window_len) y = np.convolve(w / w.sum(), s, mode='valid') return y[half_len + 1:-half_len]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fuzzy_index_match(possiblities, label, **kwargs): """Find the closest matching column label, key, or integer indexed value Returns: type(label): sequence of immutable objects corresponding to best matches to each object in label if label is an int returns the object (value) in the list of possibilities at that index if label is a str returns the closest str match in possibilities 'B' '2' '2' '5' 0 """
possibilities = list(possiblities) if isinstance(label, basestring): return fuzzy_get(possibilities, label, **kwargs) if isinstance(label, int): return possibilities[label] if isinstance(label, list): return [fuzzy_get(possibilities, lbl) for lbl in label]
<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_dataframe(obj, columns=None, exclude=None, limit=1e8): """Coerce an iterable, queryset, list or rows, dict of columns, etc into a Pandas DataFrame"""
try: obj = obj.objects.all()[:limit] except: pass if isinstance(obj, (pd.Series, list, tuple)): return make_dataframe(pd.DataFrame(obj), columns, exclude, limit) # if the obj is a named tuple, DataFrame, dict of columns, django QuerySet, sql alchemy query result # retrieve the "include"d field/column names from its keys/fields/attributes if columns is None: columns = get_column_labels(obj) if exclude is not None and columns is not None and columns and exclude: columns = [i for i in columns if i not in exclude] try: return pd.DataFrame(list(obj.values(*columns)[:limit])) except: pass try: return pd.DataFrame(obj)[fuzzy_get(obj, columns)] except: pass return pd.DataFrame(obj)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter(self, destination_object=None, source_object=None, **kwargs): """ See ``QuerySet.filter`` for full documentation This adds support for ``destination_object`` and ``source_object`` as kwargs. This converts those objects into the values necessary to handle the ``GenericForeignKey`` fields. """
if destination_object: kwargs.update({ "destination_id": destination_object.pk, "destination_type": get_for_model(destination_object), }) if source_object: kwargs.update({ "source_id": source_object.pk, "source_type": get_for_model(source_object), }) return super(RelatedContentQuerySet, self).filter(**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 _set_module_names_for_sphinx(modules: List, new_name: str): """ Trick sphinx into displaying the desired module in these objects' documentation. """
for obj in modules: obj.__module__ = new_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 run_skeleton(skeleton_path, tasks, watch=True): """loads and executes tasks from a given skeleton file skeleton_path: path to the skeleton file tasks: a list of string identifiers of tasks to be executed watch: boolean flag of if the skeleton should be watched for changes and automatically updated """
build_context = load_context_from_skeleton(skeleton_path); # for t in build_context.tasks: # print t, str(build_context.tasks[t]) for task in tasks: build_context.build_task(task) # print json.dumps( # dict((name, # str(task.value)[0:100] + "..." # if 100 < len(str(task.value)) # else str(task.value)) # for name, task in build_context.tasks.iteritems()), # indent=2) if watch: print print "resolving watch targets" # establish watchers observer = Observer() buildcontexteventhandler = BuildContextFsEventHandler(build_context) built_tasks = ((taskname, task) for taskname, task in build_context.tasks.iteritems() if task.last_build_time > 0) for taskname, task in built_tasks: for f in task.task.file_watch_targets: if os.path.isdir(f): print "%s: watching %s" % (taskname, f) observer.schedule( buildcontexteventhandler, f, recursive=True) else: print "%s: watching %s for %s" % (taskname, os.path.dirname(f), os.path.basename(f)) dirname = os.path.dirname(f) observer.schedule( buildcontexteventhandler, dirname if dirname != "" else ".", recursive=True) print print "watching for changes" observer.start() try: while True: sleep(0.5) except KeyboardInterrupt: observer.stop() observer.join()
<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_fresh_content(top=4, additional=10, featured=False): """ Requires articles, photos and video packages to be installed. Returns published *Featured* content (articles, galleries, video, etc) and an additional batch of fresh regular (featured or not) content. The number of objects returned is defined when the tag is called. The top item type is defined in the sites admin for sites that have the supersites app enabled. If "featured" is True, will limit to only featured content. Usage:: {% get_fresh_content 5 10 %} Would return five top objects and 10 additional {% get_fresh_content 4 8 featured %} Would return four top objects and 8 additional, limited to featured content. What you get:: 'top_item': the top featured item 'top_item_type': the content type for the top item (article, gallery, video) 'featured': Additional featured items. If you asked for 5 featureed items, there will be four -- five minus the one that's in `top_item`. 'articles': featured articles, minus the top item 'galleries': featured galleries, minus the top item 'vids': featured video, minus the top item, 'more_articles': A stack of articles, excluding what's in featured, sliced to the number passed for <num_regular>, 'more_galleries': A stack of galleries, excluding what's in featured, sliced to the number passed for <num_regular>, 'additional': A mixed list of articles and galleries, excluding what's in featured, sliced to the number passed for <num_regular>, """
from articles.models import Article from photos.models import Gallery from video.models import Video articles = Article.published.only('title', 'summary', 'slug', 'created') galleries = Gallery.published.only('title', 'summary', 'slug', 'created') videos = Video.published.only('title', 'summary', 'slug', 'created') if featured: articles = articles.filter(featured=True) galleries = galleries.filter(featured=True) videos = videos.filter(featured=True) # now slice to maximum possible for each group # and go ahead and make them lists for chaining max_total = top + additional articles = list(articles[:max_total]) galleries = list(galleries[:max_total]) videos = list(videos[:max_total]) # chain the lists now content = chain(articles, galleries, videos) content = sorted(content, key=lambda instance: instance.created) content.reverse() top_content = content[:top] additional_content = content[top:max_total] return { 'top_content': top_content, 'additional_content': additional_content, 'MEDIA_URL': settings.MEDIA_URL, }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def markdown(value, arg=''): """ Runs Markdown over a given value, optionally using various extensions python-markdown supports. Derived from django.contrib.markdown, which was deprecated from django. ALWAYS CLEAN INPUT BEFORE TRUSTING IT. Syntax:: To enable safe mode, which strips raw HTML and only returns HTML generated by actual Markdown syntax, pass "safe" as the first extension in the list. If the version of Markdown in use does not support extensions, they will be silently ignored. """
import warnings warnings.warn('The markdown filter has been deprecated', category=DeprecationWarning) try: import markdown except ImportError: if settings.DEBUG: raise template.TemplateSyntaxError( "Error in 'markdown' filter: The Python markdown library isn't installed." ) return force_text(value) else: markdown_vers = getattr(markdown, "version_info", 0) if markdown_vers < (2, 1): if settings.DEBUG: raise template.TemplateSyntaxError( """ Error in 'markdown' filter: Django does not support versions of the Python markdown library < 2.1. """ ) return force_text(value) else: extensions = [e for e in arg.split(",") if e] if extensions and extensions[0] == "safe": extensions = extensions[1:] return mark_safe(markdown.markdown( force_text(value), extensions, safe_mode=True, enable_attributes=False)) else: return mark_safe(markdown.markdown( force_text(value), extensions, safe_mode=False))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def file_path(self): """ The path to the file where passwords are stored. This property may be overridden by the subclass or at the instance level. """
return os.path.join(keyring.util.platform.data_root(), self.filename)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def account(self, account=None): ''' Fetches account information and stores the result in a class variable. Returns that variable if the account has not changed. ''' for num_of_retries in range(default.max_retry): if account is None: account = self.mainaccount if account == self.checkedaccount: return self.accountinfo self.checkedaccount = account try: self.accountinfo = self.steem_instance().get_account(account) except Exception as e: self.util.retry(("COULD NOT GET ACCOUNT INFO FOR " + str(account)), e, num_of_retries, default.wait_time) self.s = None else: if self.accountinfo is None: self.msg.error_message("COULD NOT FIND ACCOUNT: " + str(account)) return False else: return self.accountinfo
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def steem_instance(self): ''' Returns the steem instance if it already exists otherwise uses the goodnode method to fetch a node and instantiate the Steem class. ''' if self.s: return self.s for num_of_retries in range(default.max_retry): node = self.util.goodnode(self.nodes) try: self.s = Steem(keys=self.keys, nodes=[node]) except Exception as e: self.util.retry("COULD NOT GET STEEM INSTANCE", e, num_of_retries, default.wait_time) self.s = None else: return self.s return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def verify_key (self, acctname=None, tokenkey=None): ''' This can be used to verify either a private posting key or to verify a steemconnect refresh token and retreive the access token. ''' if (re.match( r'^[A-Za-z0-9]+$', tokenkey) and tokenkey is not None and len(tokenkey) <= 64 and len(tokenkey) >= 16): pubkey = PrivateKey(tokenkey).pubkey or 0 pubkey2 = self.account(acctname) if (str(pubkey) == str(pubkey2['posting']['key_auths'][0][0])): self.privatekey = tokenkey self.refreshtoken = None self.accesstoken = None return True else: return False elif (re.match( r'^[A-Za-z0-9\-\_\.]+$', tokenkey) and tokenkey is not None and len(tokenkey) > 64): self.privatekey = None self.accesstoken = self.connect.get_token(tokenkey) if self.accesstoken: self.username = self.connect.username self.refreshtoken = self.connect.refresh_token return True else: return False else: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def reward_pool_balances(self): ''' Fetches and returns the 3 values needed to calculate the reward pool and other associated values such as rshares. Returns the reward balance, all recent claims and the current price of steem. ''' if self.reward_balance > 0: return self.reward_balance else: reward_fund = self.steem_instance().get_reward_fund() self.reward_balance = Amount( reward_fund["reward_balance"]).amount self.recent_claims = float(reward_fund["recent_claims"]) self.base = Amount( self.steem_instance( ).get_current_median_history_price()["base"] ).amount return [self.reward_balance, self.recent_claims, self.base]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def rshares_to_steem (self, rshares): ''' Gets the reward pool balances then calculates rshares to steem ''' self.reward_pool_balances() return round( rshares * self.reward_balance / self.recent_claims * self.base, 4)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def global_props(self): ''' Retrieves the global properties used to determine rates used for calculations in converting steempower to vests etc. Stores these in the Utilities class as that is where the conversions take place, however SimpleSteem is the class that contains steem_instance, so to to preserve heirarchy and to avoid "spaghetti code", this method exists in this class. ''' if self.util.info is None: self.util.info = self.steem_instance().get_dynamic_global_properties() self.util.total_vesting_fund_steem = Amount(self.util.info["total_vesting_fund_steem"]).amount self.util.total_vesting_shares = Amount(self.util.info["total_vesting_shares"]).amount self.util.vote_power_reserve_rate = self.util.info["vote_power_reserve_rate"] return self.util.info
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def current_vote_value(self, **kwargs): ''' Ensures the needed variables are created and set to defaults although a variable number of variables are given. ''' try: kwargs.items() except: pass else: for key, value in kwargs.items(): setattr(self, key, value) try: self.lastvotetime except: self.lastvotetime=None try: self.steempower except: self.steempower=0 try: self.voteweight except: self.voteweight=100 try: self.votepoweroverride except: self.votepoweroverride=0 try: self.accountname except: self.accountname=None if self.accountname is None: self.accountname = self.mainaccount if self.check_balances(self.accountname) is not False: if self.voteweight > 0 and self.voteweight < 101: self.voteweight = self.util.scale_vote(self.voteweight) if self.votepoweroverride > 0 and self.votepoweroverride < 101: self.votepoweroverride = self.util.scale_vote(self.votepoweroverride) else: self.votepoweroverride = (self.votepower + self.util.calc_regenerated( self.lastvotetime)) self.vpow = round(self.votepoweroverride / 100, 2) self.global_props() self.rshares = self.util.sp_to_rshares(self.steempower, self.votepoweroverride, self.voteweight) self.votevalue = self.rshares_to_steem(self.rshares) return self.votevalue return None
<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_balances(self, account=None): ''' Fetches an account balance and makes necessary conversions ''' a = self.account(account) if a is not False and a is not None: self.sbdbal = Amount(a['sbd_balance']).amount self.steembal = Amount(a['balance']).amount self.votepower = a['voting_power'] self.lastvotetime = a['last_vote_time'] vs = Amount(a['vesting_shares']).amount dvests = Amount(a['delegated_vesting_shares']).amount rvests = Amount(a['received_vesting_shares']).amount vests = (float(vs) - float(dvests)) + float(rvests) try: self.global_props() self.steempower_delegated = self.util.vests_to_sp(dvests) self.steempower_raw = self.util.vests_to_sp(vs) self.steempower = self.util.vests_to_sp(vests) except Exception as e: self.msg.error_message(e) else: return [self.sbdbal, self.steembal, self.steempower, self.votepower, self.lastvotetime] return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def transfer_funds(self, to, amount, denom, msg): ''' Transfer SBD or STEEM to the given account ''' try: self.steem_instance().commit.transfer(to, float(amount), denom, msg, self.mainaccount) except Exception as e: self.msg.error_message(e) return False else: 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 get_my_history(self, account=None, limit=10000): ''' Fetches the account history from most recent back ''' if not account: account = self.mainaccount try: h = self.steem_instance().get_account_history( account, -1, limit) except Exception as e: self.msg.error_message(e) return False else: return 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 reply(self, permlink, msgbody): ''' Used for creating a reply to a post. Waits 20 seconds after posting as that is the required amount of time between posting. ''' for num_of_retries in range(default.max_retry): try: self.steem_instance().post("message", msgbody, self.mainaccount, None, permlink, None, None, "", None, None, False) except Exception as e: self.util.retry("COULD NOT REPLY TO " + permlink, e, num_of_retries, default.wait_time) self.s = None else: self.msg.message("Replied to " + permlink) time.sleep(20) 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 follow(self, author): ''' Follows the given account ''' try: self.steem_instance().commit.follow(author, ['blog'], self.mainaccount) except Exception as e: self.msg.error_message(e) return False else: 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 following(self, account=None, limit=100): ''' Gets a list of all the followers of a given account. If no account is given the followers of the mainaccount are returned. ''' if not account: account = self.mainaccount followingnames = [] try: self.followed = self.steem_instance().get_following(account, '', 'blog', limit) except Exception as e: self.msg.error_message(e) return False else: for a in self.followed: followingnames.append(a['following']) return followingnames
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def vote_history(self, permlink, author=None): ''' Returns the raw vote history of a given post from a given account ''' if author is None: author = self.mainaccount return self.steem_instance().get_active_votes(author, permlink)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dex_ticker(self): ''' Simply grabs the ticker using the steem_instance method and adds it to a class variable. ''' self.dex = Dex(self.steem_instance()) self.ticker = self.dex.get_ticker(); return self.ticker
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def steem_to_sbd(self, steemamt=0, price=0, account=None): ''' Uses the ticker to get the highest bid and moves the steem at that price. ''' if not account: account = self.mainaccount if self.check_balances(account): if steemamt == 0: steemamt = self.steembal elif steemamt > self.steembal: self.msg.error_message("INSUFFICIENT FUNDS. CURRENT STEEM BAL: " + str(self.steembal)) return False if price == 0: price = self.dex_ticker()['highest_bid'] try: self.dex.sell(steemamt, "STEEM", price, account=account) except Exception as e: self.msg.error_message("COULD NOT SELL STEEM FOR SBD: " + str(e)) return False else: self.msg.message("TRANSFERED " + str(steemamt) + " STEEM TO SBD AT THE PRICE OF: $" + str(price)) return True else: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def sbd_to_steem(self, sbd=0, price=0, account=None): ''' Uses the ticker to get the lowest ask and moves the sbd at that price. ''' if not account: account = self.mainaccount if self.check_balances(account): if sbd == 0: sbd = self.sbdbal elif sbd > self.sbdbal: self.msg.error_message("INSUFFICIENT FUNDS. CURRENT SBD BAL: " + str(self.sbdbal)) return False if price == 0: price = 1 / self.dex_ticker()['lowest_ask'] try: self.dex.sell(sbd, "SBD", price, account=account) except Exception as e: self.msg.error_message("COULD NOT SELL SBD FOR STEEM: " + str(e)) return False else: self.msg.message("TRANSFERED " + str(sbd) + " SBD TO STEEM AT THE PRICE OF: $" + str(price)) return True else: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def vote_witness(self, witness, account=None): ''' Uses the steem_instance method to vote on a witness. ''' if not account: account = self.mainaccount try: self.steem_instance().approve_witness(witness, account=account) except Exception as e: self.msg.error_message("COULD NOT VOTE " + witness + " AS WITNESS: " + e) return False else: 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 unvote_witness(self, witness, account=None): ''' Uses the steem_instance method to unvote a witness. ''' if not account: account = self.mainaccount try: self.steem_instance().disapprove_witness(witness, account=account) except Exception as e: self.msg.error_message("COULD NOT UNVOTE " + witness + " AS WITNESS: " + e) return False else: 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 voted_me_witness(self, account=None, limit=100): ''' Fetches all those a given account is following and sees if they have voted that account as witness. ''' if not account: account = self.mainaccount self.has_voted = [] self.has_not_voted = [] following = self.following(account, limit) for f in following: wv = self.account(f)['witness_votes'] voted = False for w in wv: if w == account: self.has_voted.append(f) voted = True if not voted: self.has_not_voted.append(f) return self.has_voted
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def muted_me(self, account=None, limit=100): ''' Fetches all those a given account is following and sees if they have muted that account. ''' self.has_muted = [] if account is None: account = self.mainaccount following = self.following(account, limit) if following is False: self.msg.error_message("COULD NOT GET FOLLOWING FOR MUTED") return False for f in following: h = self.get_my_history(f) for a in h: if a[1]['op'][0] == "custom_json": j = a[1]['op'][1]['json'] d = json.loads(j) try: d[1] except: pass else: for i in d[1]: if i == "what": if len(d[1]['what']) > 0: if d[1]['what'][0] == "ignore": if d[1]['follower'] == account: self.msg.message("MUTED BY " + f) self.has_muted.append(f) return self.has_muted
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def delegate(self, to, steempower): ''' Delegates based on Steem Power rather than by vests. ''' self.global_props() vests = self.util.sp_to_vests(steempower) strvests = str(vests) strvests = strvests + " VESTS" try: self.steem_instance().commit.delegate_vesting_shares(to, strvests, account=self.mainaccount) except Exception as e: self.msg.error_message("COULD NOT DELEGATE " + str(steempower) + " SP TO " + to + ": " + str(e)) return False else: self.msg.message("DELEGATED " + str(steempower) + " STEEM POWER TO " + str(to)) 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 start_logging(gconfig, logpath): '''Turn on logging and set up the global config. This expects the :mod:`yakonfig` global configuration to be unset, and establishes it. It starts the log system via the :mod:`dblogger` setup. In addition to :mod:`dblogger`'s defaults, if `logpath` is provided, a :class:`logging.handlers.RotatingFileHandler` is set to write log messages to that file. This should not be called if the target worker is :class:`rejester.workers.ForkWorker`, since that manages logging on its own. :param dict gconfig: the :mod:`yakonfig` global configuration :param str logpath: optional location to write a log file ''' yakonfig.set_default_config([rejester, dblogger], config=gconfig) if logpath: formatter = dblogger.FixedWidthFormatter() # TODO: do we want byte-size RotatingFileHandler or TimedRotatingFileHandler? handler = logging.handlers.RotatingFileHandler( logpath, maxBytes=10000000, backupCount=3) handler.setFormatter(formatter) logging.getLogger('').addHandler(handler)
<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_worker(which_worker, config={}): '''Start some worker class. :param str which_worker: name of the worker :param dict config: ``rejester`` config block ''' if which_worker == 'multi_worker': cls = MultiWorker elif which_worker == 'fork_worker': cls = ForkWorker else: # Don't complain too hard, just fall back cls = ForkWorker return run_worker(cls, config)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def go(gconfig, args): '''Actually run the worker. This does some required housekeeping, like setting up logging for :class:`~rejester.workers.MultiWorker` and establishing the global :mod:`yakonfig` configuration. This expects to be called with the :mod:`yakonfig` configuration unset. :param dict gconfig: the :mod:`yakonfig` global configuration :param args: command-line arguments ''' rconfig = gconfig['rejester'] which_worker = rconfig.get('worker', 'fork_worker') if which_worker == 'fork_worker': yakonfig.set_default_config([rejester], config=gconfig) else: start_logging(gconfig, args.logpath) return start_worker(which_worker, rconfig)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def fork_worker(gconfig, args): '''Run the worker as a daemon process. This uses :mod:`daemon` to run the standard double-fork, so it can return immediately and successfully in the parent process having forked. :param dict gconfig: the :mod:`yakonfig` global configuration :param args: command-line arguments ''' if args.pidfile: pidfile_lock = lockfile.FileLock(args.pidfile) else: pidfile_lock = None with daemon.DaemonContext(pidfile=pidfile_lock, detach_process=True): try: if args.pidfile: with open(args.pidfile, 'w') as f: f.write(str(os.getpid())) go(gconfig, args) except Exception, exc: logp = logpath or os.path.join('/tmp', 'rejester-failure.log') open(logp, 'a').write(traceback.format_exc(exc)) raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transient_change_detect(self, *class_build_args, **class_build_kwargs): """ This should be called when we want to detect a change in the status of the system regarding the transient list This function also applies changes due to regex_set updates if needed _transient_change_detect -> _transient_change_diff -> _update_transients """
transient_detected = set(self.get_transients_available()) #TODO : unify that last_got_set with the *_available. they are essentially the same tst_gone = self.last_transients_detected - transient_detected # print("INTERFACING + {transient_detected}".format(**locals())) # print("INTERFACING - {tst_gone}".format(**locals())) dt = self.transient_change_diff( # we start interfacing with new matches, # but we also need to update old matches that match regex now transient_appeared=transient_detected, transient_gone=tst_gone, *class_build_args, **class_build_kwargs ) self.last_transients_detected.update(transient_detected) if tst_gone: self.last_transients_detected.difference_update(tst_gone) return dt
<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_function_doc(function, config=default_config): """Return doc for a function."""
if config.exclude_function: for ex in config.exclude_function: if ex.match(function.__name__): return None return _doc_object(function, 'function', config=config)
<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_class_doc(klass, config=default_config): """Return doc for a class."""
if config.exclude_class: for ex in config.exclude_class: if ex.match(klass.__name__): return None nested_doc = [] class_dict = klass.__dict__ for item in dir(klass): if item in class_dict.keys(): appended = None if isinstance(class_dict[item], type) and config.nested_class: appended = get_class_doc(class_dict[item], config) elif isinstance(class_dict[item], types.FunctionType): appended = get_function_doc(class_dict[item], config) if appended is not None: nested_doc.append(appended) return _doc_object(klass, 'class', nested_doc, config)
<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_module_doc(module, config=default_config, already_met=None): """Return doc for a module."""
# Avoid recursion loops (init) if already_met is None: already_met = set() if config.exclude_module: for ex in config.exclude_module: if ex.match(module.__name__): return None # Force load submodules into module's dict if hasattr(module, '__path__'): subm = [ modname for importer, modname, ispkg in pkgutil.iter_modules(module.__path__) ] __import__(module.__name__, fromlist=subm) # We don't want to include imported items, # so we parse the code to blacklist them. # Be sure to parse .py and not .pyc file on Python 2.X if hasattr(module, '__file__'): module_file = module.__file__ else: module_file = inspect.getsourcefile(module) path, ext = os.path.splitext(module_file) if ext == '.pyc': module_file = path + '.py' try: code = open(module_file).read() body = ast.parse(code).body except SyntaxError: code = open(module_file).read().encode('utf-8') body = ast.parse(code).body imported = [] for node in body: if isinstance(node, (ast.Import, ast.ImportFrom)): imported.extend([n.name for n in node.names]) nested_doc = [] module_dict = module.__dict__ for item in dir(module): if item not in imported and item in module_dict.keys(): # Avoid recursion loops if id(item) in already_met: continue already_met.add(id(item)) appended = None if isinstance(module_dict[item], types.ModuleType): appended = get_module_doc(module_dict[item], config, already_met) # noqa elif isinstance(module_dict[item], type): appended = get_class_doc(module_dict[item], config) elif isinstance(module_dict[item], types.FunctionType): appended = get_function_doc(module_dict[item], config) if appended is not None: nested_doc.append(appended) return _doc_object(module, 'module', nested_doc, config)
<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, name): """ Check if given name matches. Args: name (str): name to check. Returns: bool: matches name. """
if self.method == Ex.Method.PREFIX: return name.startswith(self.value) elif self.method == Ex.Method.SUFFIX: return name.endswith(self.value) elif self.method == Ex.Method.CONTAINS: return self.value in name elif self.method == Ex.Method.EXACT: return self.value == name elif self.method == Ex.Method.REGEX: return re.search(self.value, name) return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def autocommand(func): """ A simplified decorator for making a single function a Command instance. In the future this will leverage PEP0484 to do really smart function parsing and conversion to argparse actions. """
name = func.__name__ title, desc = command.parse_docstring(func) if not title: title = 'Auto command for: %s' % name if not desc: # Prevent Command from using docstring of AutoCommand desc = ' ' return AutoCommand(title=title, desc=desc, name=name, func=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 run(self, args): """ Convert the unordered args into function arguments. """
args = vars(args) positionals = [] keywords = {} for action in self.argparser._actions: if not hasattr(action, 'label'): continue if action.label == 'positional': positionals.append(args[action.dest]) elif action.label == 'varargs': positionals.extend(args[action.dest]) elif action.label == 'keyword': keywords[action.dest] = args[action.dest] elif action.label == 'varkwargs': kwpairs = iter(args[action.dest] or []) for key in kwpairs: try: key, value = key.split('=', 1) except ValueError: value = next(kwpairs) key = key.strip('-') keywords[key] = value return self.func(*positionals, **keywords)
<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_to(self, im, path, format=None): """Save the image for testing. """
format = format or im.format if not format: _, format = splitext(path) format = format[1:] im.format = format.lower() im.save(filename=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 _log(self, priority, message, *args, **kwargs): """Generic log functions """
for arg in args: message = message + "\n" + self.pretty_printer.pformat(arg) self.logger.log(priority, 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 debug(self, message, *args, **kwargs): """Debug level to use and abuse when coding """
self._log(logging.DEBUG, message, *args, **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 warn(self, message, *args, **kwargs): """
self._log(logging.WARNING, message, *args, **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 warning(self, message, *args, **kwargs): """Alias to warn """
self._log(logging.WARNING, message, *args, **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 error(self, message, *args, **kwargs): """
self._log(logging.ERROR, message, *args, **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 init_logger(self): """Create configuration for the root logger."""
# All logs are comming to this logger self.logger.setLevel(logging.DEBUG) self.logger.propagate = False # Logging to console if self.min_log_level_to_print: level = self.min_log_level_to_print handler_class = logging.StreamHandler self._create_handler(handler_class, level) # Logging to file if self.min_log_level_to_save: level = self.min_log_level_to_save handler_class = logging.handlers.TimedRotatingFileHandler self._create_handler(handler_class, level) # Logging to syslog if self.min_log_level_to_syslog: level = self.min_log_level_to_syslog handler_class = logging.handlers.SysLogHandler self._create_handler(handler_class, level) # Logging to email if self.min_log_level_to_mail: level = self.min_log_level_to_mail handler_class = AlkiviEmailHandler self._create_handler(handler_class, level) 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 new_iteration(self, prefix): """When inside a loop logger, created a new iteration """
# Flush data for the current iteration self.flush() # Fix prefix self.prefix[-1] = prefix self.reset_formatter()
<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_formatter(self): """Rebuild formatter for all handlers."""
for handler in self.handlers: formatter = self.get_formatter(handler) handler.setFormatter(formatter)
<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_min_level(self, handler_class, level): """Generic method to setLevel for handlers."""
if self._exist_handler(handler_class): if not level: self._delete_handler(handler_class) else: self._update_handler(handler_class, level=level) elif level: self._create_handler(handler_class, 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 set_min_level_to_print(self, level): """Allow to change print level after creation """
self.min_log_level_to_print = level handler_class = logging.StreamHandler self._set_min_level(handler_class, 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 set_min_level_to_save(self, level): """Allow to change save level after creation """
self.min_log_level_to_save = level handler_class = logging.handlers.TimedRotatingFileHandler self._set_min_level(handler_class, 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 set_min_level_to_mail(self, level): """Allow to change mail level after creation """
self.min_log_level_to_mail = level handler_class = AlkiviEmailHandler self._set_min_level(handler_class, 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 set_min_level_to_syslog(self, level): """Allow to change syslog level after creation """
self.min_log_level_to_syslog = level handler_class = logging.handlers.SysLogHandler self._set_min_level(handler_class, 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_handler(self, handler_class): """Return an existing class of handler."""
element = None for handler in self.handlers: if isinstance(handler, handler_class): element = handler break return element
<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_handler(self, handler_class): """Delete a specific handler from our logger."""
to_remove = self._get_handler(handler_class) if not to_remove: logging.warning('Error we should have an element to remove') else: self.handlers.remove(to_remove) self.logger.removeHandler(to_remove)
<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_handler(self, handler_class, level): """Update the level of an handler."""
handler = self._get_handler(handler_class) handler.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 _create_handler(self, handler_class, level): """Create an handler for at specific level."""
if handler_class == logging.StreamHandler: handler = handler_class() handler.setLevel(level) elif handler_class == logging.handlers.SysLogHandler: handler = handler_class(address='/dev/log') handler.setLevel(level) elif handler_class == logging.handlers.TimedRotatingFileHandler: handler = handler_class(self.filename, when='midnight') handler.setLevel(level) elif handler_class == AlkiviEmailHandler: handler = handler_class(mailhost='127.0.0.1', fromaddr="%s@%s" % (USER, HOST), toaddrs=self.emails, level=self.min_log_level_to_mail) # Needed, we want all logs to go there handler.setLevel(0) formatter = self.get_formatter(handler) handler.setFormatter(formatter) self.handlers.append(handler) self.logger.addHandler(handler)
<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_formatter(self, handler): """ Return formatters according to handler. All handlers are the same format, except syslog. We omit time when syslogging. """
if isinstance(handler, logging.handlers.SysLogHandler): formatter = '[%(levelname)-9s]' else: formatter = '[%(asctime)s] [%(levelname)-9s]' for p in self.prefix: formatter += ' [%s]' % (p) formatter = formatter + ' %(message)s' return logging.Formatter(formatter)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def version_control(): """Return an object that provides the version control interface based on the detected version control system."""
curdir_contents = os.listdir('.') if '.hg' in curdir_contents: return hg.Hg() elif '.git' in curdir_contents: return git.Git() else: logger.critical('No version control system detected.') sys.exit(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 package_in_pypi(package): """Check whether the package is registered on pypi"""
url = 'http://pypi.python.org/simple/%s' % package try: urllib.request.urlopen(url) return True except urllib.error.HTTPError as e: logger.debug("Package not found on pypi: %s", e) return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _grab_version(self): """Set the version to a non-development version."""
original_version = self.vcs.version logger.debug("Extracted version: %s", original_version) if original_version is None: logger.critical('No version found.') sys.exit(1) suggestion = utils.cleanup_version(original_version) new_version = utils.ask_version("Enter version", default=suggestion) if not new_version: new_version = suggestion self.data['original_version'] = original_version self.data['new_version'] = new_version
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _write_history(self): """Write previously-calculated history lines back to the file"""
if self.data['history_file'] is None: return contents = '\n'.join(self.data['history_lines']) history = self.data['history_file'] open(history, 'w').write(contents) logger.info("History file %s updated.", history)
<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_if_tag_already_exists(self): """Check if tag already exists and show the difference if so"""
version = self.data['new_version'] if self.vcs.tag_exists(version): return True else: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _release(self): """Upload the release, when desired"""
pypiconfig = pypi.PypiConfig() # Does the user normally want a real release? We are # interested in getting a sane default answer here, so you can # override it in the exceptional case but just hit Enter in # the usual case. main_files = os.listdir(self.data['workingdir']) if 'setup.py' not in main_files and 'setup.cfg' not in main_files: # Neither setup.py nor setup.cfg, so this is no python # package, so at least a pypi release is not useful. # Expected case: this is a buildout directory. default_answer = False else: default_answer = pypiconfig.want_release() if not utils.ask("Check out the tag (for tweaks or pypi/distutils " "server upload)", default=default_answer): return package = self.vcs.name version = self.data['new_version'] logger.info("Doing a checkout...") self.vcs.checkout_from_tag(version) self.data['tagdir'] = os.path.realpath(os.getcwd()) logger.info("Tag checkout placed in %s", self.data['tagdir']) # Possibly fix setup.cfg. if self.setup_cfg.has_bad_commands(): logger.info("This is not advisable for a release.") if utils.ask("Fix %s (and commit to tag if possible)" % self.setup_cfg.config_filename, default=True): # Fix the setup.cfg in the current working directory # so the current release works well. self.setup_cfg.fix_config() sdist_options = self._sdist_options() if 'setup.py' in os.listdir(self.data['tagdir']): self._upload_distributions(package, sdist_options, pypiconfig) # Make sure we are in the expected directory again. os.chdir(self.vcs.workingdir)
<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_version(self): """Ask for and store a new dev version string."""
#current = self.vcs.version current = self.data['new_version'] # Clean it up to a non-development version. current = utils.cleanup_version(current) # Try to make sure that the suggestion for next version after # 1.1.19 is not 1.1.110, but 1.1.20. current_split = current.split('.') major = '.'.join(current_split[:-1]) minor = current_split[-1] try: minor = int(minor) + 1 suggestion = '.'.join([major, str(minor)]) except ValueError: # Fall back on simply updating the last character when it is # an integer. try: last = int(current[-1]) + 1 suggestion = current[:-1] + str(last) except ValueError: logger.warn("Version does not end with a number, so we can't " "calculate a suggestion for a next version.") suggestion = None print("Current version is %r" % current) q = "Enter new development version ('.dev0' will be appended)" version = utils.ask_version(q, default=suggestion) if not version: version = suggestion if not version: logger.error("No version entered.") sys.exit() self.data['new_version'] = version dev_version = self.data['dev_version_template'] % self.data self.data['dev_version'] = dev_version logger.info("New version string is %r", dev_version) self.vcs.version = self.data['dev_version']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_history(self): """Update the history file"""
version = self.data['new_version'] history = self.vcs.history_file() if not history: logger.warn("No history file found") return history_lines = open(history).read().split('\n') headings = utils.extract_headings_from_history(history_lines) if not len(headings): logger.warn("No detectable existing version headings in the " "history file.") inject_location = 0 underline_char = '-' else: first = headings[0] inject_location = first['line'] underline_line = first['line'] + 1 try: underline_char = history_lines[underline_line][0] except IndexError: logger.debug("No character on line below header.") underline_char = '-' header = '%s (unreleased)' % version inject = [header, underline_char * len(header), '', self.data['nothing_changed_yet'], '', ''] history_lines[inject_location:inject_location] = inject contents = '\n'.join(history_lines) open(history, 'w').write(contents) logger.info("Injected new section into the history: %r", header)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _push(self): """Offer to push changes, if needed."""
push_cmds = self.vcs.push_commands() if not push_cmds: return if utils.ask("OK to push commits to the server?"): for push_cmd in push_cmds: output = utils.system(push_cmd) logger.info(output)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_user(user, driver): # noqa: E501 """Retrieve a user Retrieve a user # noqa: E501 :param user: Get user with this name :type user: str :param driver: The driver to use for the request. ie. github :type driver: str :rtype: Response """
response = ApitaxResponse() driver: Driver = LoadedDrivers.getDriver(driver) user: User = driver.getApitaxUser(User(username=user)) response.body.add({'user': {'username': user.username, 'role': user.role}}) return Response(status=200, body=response.getResponseBody())
<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(path_dir, requirements_name): """Console script for imports."""
click.echo("\nWARNING: Uninstall libs it's at your own risk!") click.echo('\nREMINDER: After uninstall libs, update your requirements ' 'file.\nUse the `pip freeze > requirements.txt` command.') click.echo('\n\nList of installed libs and your dependencies added on ' 'project\nrequirements that are not being used:\n') check(path_dir, requirements_name)