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 assumes(*args): '''Stores a function's assumptions as an attribute.''' args = tuple(args) def decorator(func): func.assumptions = args return func return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def overridden_by_assumptions(*args): '''Stores what assumptions a function is overridden by as an attribute.''' args = tuple(args) def decorator(func): func.overridden_by_assumptions = args return func return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def equation_docstring(quantity_dict, assumption_dict, equation=None, references=None, notes=None): ''' Creates a decorator that adds a docstring to an equation function. Parameters ---------- quantity_dict : dict A dictionary describing the quantities used in the equations. Its keys ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sma(array, window_size, axis=-1, mode='reflect', **kwargs): """ Computes a 1D simple moving average along the given axis. Parameters array : ndarray Array on...
kwargs['axis'] = axis kwargs['mode'] = mode if not isinstance(window_size, int): raise TypeError('window_size must be an integer') if not isinstance(kwargs['axis'], int): raise TypeError('axis must be an integer') return convolve1d(array, np.repeat(1.0, window_size)/window_size, **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 assumption_list_string(assumptions, assumption_dict): ''' Takes in a list of short forms of assumptions and an assumption dictionary, and returns a "list" form of the long form of the assumptions. Raises ------ ValueError if one of the assumptions is not in assumption_dict. ''' if isinstance(assump...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def quantity_spec_string(name, quantity_dict): ''' Returns a quantity specification for docstrings. Example ------- >>> quantity_spec_string('Tv') >>> 'Tv : float or ndarray\n Data for virtual temperature.' ''' if name not in quantity_dict.keys(): raise ValueError('{0} not present in quantity_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 doc_paragraph(s, indent=0): '''Takes in a string without wrapping corresponding to a paragraph, and returns a version of that string wrapped to be at most 80 characters in length on each line. If indent is given, ensures each line is indented to that number of spaces. ''' 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 closest_val(x, L): ''' Finds the index value in an iterable closest to a desired value. Parameters ---------- x : object The desired value. L : iterable The iterable in which to search for the desired value. Returns ------- index : int The index of the c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def area_poly_sphere(lat, lon, r_sphere): ''' Calculates the area enclosed by an arbitrary polygon on the sphere. Parameters ---------- lat : iterable The latitudes, in degrees, of the vertex locations of the polygon, in clockwise order. lon : iterable The longitudes, in degrees, of the vertex locatio...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def d_x(data, axis, boundary='forward-backward'): ''' Calculates a second-order centered finite difference of data along the specified axis. Parameters ---------- data : ndarray Data on which we are taking a derivative. axis : int Index of the data array on which to take the difference. boundary : string,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def semilogy(self, p, T, *args, **kwargs): r'''Plot data. Simple wrapper around plot so that pressure is the first (independent) input. This is essentially a wrapper around `semilogy`. Parameters ---------- p : array_like pressure values T : array_li...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def plot_barbs(self, p, u, v, xloc=1.0, x_clip_radius=0.08, y_clip_radius=0.08, **kwargs): r'''Plot wind barbs. Adds wind barbs to the skew-T plot. This is a wrapper around the `barbs` command that adds to appropriate transform to place the barbs in a vertical line, 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 plot_dry_adiabats(self, p=None, theta=None, **kwargs): r'''Plot dry adiabats. Adds dry adiabats (lines of constant potential temperature) to the plot. The default style of these lines is dashed red lines with an alpha value of 0.5. These can be overridden using keyword arguments. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def plot_mixing_lines(self, p=None, rv=None, **kwargs): r'''Plot lines of constant mixing ratio. Adds lines of constant mixing ratio (isohumes) to the plot. The default style of these lines is dashed green lines with an alpha value of 0.8. These can be overridden using keyword arguments...
<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_calculatable_quantities(inputs, methods): ''' Given an interable of input quantity names and a methods dictionary, returns a list of output quantities that can be calculated. ''' output_quantities = [] updated = True while updated: updated = False for output in method...
<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_methods_that_calculate_outputs(inputs, outputs, methods): ''' Given iterables of input variable names, output variable names, and a methods dictionary, returns the subset of the methods dictionary that can be calculated, doesn't calculate something we already have, and only contains equatio...
<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_calculatable_methods_dict(inputs, methods): ''' Given an iterable of input variable names and a methods dictionary, returns the subset of that methods dictionary that can be calculated and which doesn't calculate something we already have. Additionally it may only contain one method for any...
<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_methods(module): ''' Returns a methods list corresponding to the equations in the given module. Each entry is a dictionary with keys 'output', 'args', and 'func' corresponding to the output, arguments, and function of the method. The entries may optionally include 'assumptions' and ...
<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_scalar(value): '''If value is a 0-dimensional array, returns the contents of value. Otherwise, returns value. ''' if isinstance(value, np.ndarray): if value.ndim == 0: # We have a 0-dimensional array return value[None][0] return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def calculate(*args, **kwargs): ''' Calculates and returns a requested quantity from quantities passed in as keyword arguments. Parameters ---------- \*args : string Names of quantities to be calculated. assumptions : tuple, optional Strings specifying which assumptions to enable. Overrides the default ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ip(): """Show ip address."""
ok, err = _hack_ip() if not ok: click.secho(click.style(err, fg='red')) sys.exit(1) click.secho(click.style(err, fg='green'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wp(ssid): """Show wifi password."""
if not ssid: ok, err = _detect_wifi_ssid() if not ok: click.secho(click.style(err, fg='red')) sys.exit(1) ssid = err ok, err = _hack_wifi_password(ssid) if not ok: click.secho(click.style(err, fg='red')) sys.exit(1) click.secho(click.style...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_url(self): """Builds the URL for elevations API services based on the data given by the user. Returns: url (str): URL for the elevations API services ...
url = '{protocol}/{url}/{rest}/{version}/{restapi}/{rscpath}/' \ '{query}'.format(protocol=self.schema.protocol, url=self.schema.main_url, rest=self.schema.rest, version=self.schema.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 zoomlevel(self): """Retrieves zoomlevel from the output response Returns: zoomlevel (namedtuple): A namedtuple of zoomlevel from the output response """
resources = self.get_resource() zoomlevel = namedtuple('zoomlevel', 'zoomLevel') try: return [zoomlevel(resource['zoomLevel']) for resource in resources] except TypeError: try: if isinstance(resources['ElevationData'], 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 to_json_file(self, path, file_name=None): """Writes output to a JSON file with the given file name"""
if bool(path) and os.path.isdir(path): self.write_to_json(path, file_name) else: self.write_to_json(os.getcwd(), file_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 get_data(self): """Gets data from the built url"""
url = self.build_url() self.locationApiData = requests.get(url) if not self.locationApiData.status_code == 200: raise self.locationApiData.raise_for_status()
<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_compaction(model): """Updates the compaction options for the given model if necessary. :param model: The model to update. :return: `True`, if the comp...
logger.debug("Checking %s for compaction differences", model) table = get_table_settings(model) existing_options = table.options.copy() existing_compaction_strategy = existing_options['compaction_strategy_class'] existing_options = json.loads(existing_options['compaction_strategy_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 setup( hosts, default_keyspace, consistency=ConsistencyLevel.ONE, lazy_connect=False, retry_connect=False, **kwargs): """ Records the hosts and connects to o...
global cluster, session, default_consistency_level, lazy_connect_args if 'username' in kwargs or 'password' in kwargs: raise CQLEngineException("Username & Password are now handled by using the native driver's auth_provider") if not default_keyspace: raise UndefinedKeyspaceException() ...
<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(self, value): """ Returns a cleaned and validated value. Raises a ValidationError if there's a problem """
if value is None: if self.required: raise ValidationError('{} - None values are not allowed'.format(self.column_name or self.db_field)) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_datetime(self, dt): """ generates a UUID for a given datetime :param dt: datetime :type dt: datetime :return: """
global _last_timestamp epoch = datetime(1970, 1, 1, tzinfo=dt.tzinfo) offset = epoch.tzinfo.utcoffset(epoch).total_seconds() if epoch.tzinfo else 0 timestamp = (dt - epoch).total_seconds() - offset node = None clock_seq = None nanoseconds = int(timestamp * 1e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _can_update(self): """ Called by the save function to check if this should be persisted with update or insert :return: """
if not self._is_persisted: return False pks = self._primary_keys.keys() return all([not self._values[k].changed for k in self._primary_keys])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self): """ Deletes this instance """
self.__dmlquery__(self.__class__, self, batch=self._batch, timestamp=self._timestamp, consistency=self.__consistency__, timeout=self._timeout).delete()
<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, *args, **kwargs): """ Adds WHERE arguments to the queryset, returning a new queryset #TODO: show examples :rtype: AbstractQuerySet """
#add arguments to the where clause filters if len([x for x in kwargs.values() if x is None]): raise CQLEngineException("None values on filter are not allowed") clone = copy.deepcopy(self) for operator in args: if not isinstance(operator, WhereClause): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def order_by(self, *colnames): """ orders the result set. ordering can only use clustering columns. Default order is ascending, prepend a '-' to the column name ...
if len(colnames) == 0: clone = copy.deepcopy(self) clone._order = [] return clone conditions = [] for colname in colnames: conditions.append('"{}" {}'.format(*self._get_ordering_condition(colname))) clone = copy.deepcopy(self) cl...
<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(self): """ Returns the number of rows matched by this query """
if self._batch: raise CQLEngineException("Only inserts, updates, and deletes are available in batch mode") if self._result_cache is None: query = self._select_query() query.count = True result = self._execute(query) return result[0]['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 limit(self, v): """ Sets the limit on the number of results returned CQL has a default limit of 10,000 """
if not (v is None or isinstance(v, six.integer_types)): raise TypeError if v == self._limit: return self if v < 0: raise QueryException("Negative limit is not allowed") clone = copy.deepcopy(self) clone._limit = v return clone
<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(self, **values): """ Updates the rows in this queryset """
if not values: return nulled_columns = set() us = UpdateStatement(self.column_family_name, where=self._where, ttl=self._ttl, timestamp=self._timestamp, transactions=self._transaction) for name, val in values.items(): col_name, col_op...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle(client, request): """ Handle format request request struct: { 'data': 'data_need_format', 'formaters': [ { 'name': 'formater_name', 'config': {} # Non...
formaters = request.get('formaters', None) if not formaters: formaters = [{'name': 'autopep8'}] logging.debug('formaters: ' + json.dumps(formaters, indent=4)) data = request.get('data', None) if not isinstance(data, str): return send(client, 'invalid data', None) max_line_lengt...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def easeInOutQuad(n): """A quadratic tween function that accelerates, reaches the midpoint, and then decelerates. Args: n (float): The time progress, starting a...
_checkRange(n) if n < 0.5: return 2 * n**2 else: n = n * 2 - 1 return -0.5 * (n*(n-2) - 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 easeInOutCubic(n): """A cubic tween function that accelerates, reaches the midpoint, and then decelerates. Args: n (float): The time progress, starting at 0...
_checkRange(n) n = 2 * n if n < 1: return 0.5 * n**3 else: n = n - 2 return 0.5 * (n**3 + 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 easeInOutQuart(n): """A quartic tween function that accelerates, reaches the midpoint, and then decelerates. Args: n (float): The time progress, starting at...
_checkRange(n) n = 2 * n if n < 1: return 0.5 * n**4 else: n = n - 2 return -0.5 * (n**4 - 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 easeInOutQuint(n): """A quintic tween function that accelerates, reaches the midpoint, and then decelerates. Args: n (float): The time progress, starting at...
_checkRange(n) n = 2 * n if n < 1: return 0.5 * n**5 else: n = n - 2 return 0.5 * (n**5 + 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 easeInOutExpo(n): """An exponential tween function that accelerates, reaches the midpoint, and then decelerates. Args: n (float): The time progress, startin...
_checkRange(n) if n == 0: return 0 elif n == 1: return 1 else: n = n * 2 if n < 1: return 0.5 * 2**(10 * (n - 1)) else: n -= 1 # 0.5 * (-() + 2) return 0.5 * (-1 * (2 ** (-10 * n)) + 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 easeInOutCirc(n): """A circular tween function that accelerates, reaches the midpoint, and then decelerates. Args: n (float): The time progress, starting at...
_checkRange(n) n = n * 2 if n < 1: return -0.5 * (math.sqrt(1 - n**2) - 1) else: n = n - 2 return 0.5 * (math.sqrt(1 - n**2) + 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 easeInElastic(n, amplitude=1, period=0.3): """An elastic tween function that begins with an increasing wobble and then snaps into the destination. Args: n (f...
_checkRange(n) return 1 - easeOutElastic(1-n, amplitude=amplitude, period=period)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def easeOutElastic(n, amplitude=1, period=0.3): """An elastic tween function that overshoots the destination and then "rubber bands" into the destination. Args: ...
_checkRange(n) if amplitude < 1: amplitude = 1 s = period / 4 else: s = period / (2 * math.pi) * math.asin(1 / amplitude) return amplitude * 2**(-10*n) * math.sin((n-s)*(2*math.pi / period)) + 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 easeInOutElastic(n, amplitude=1, period=0.5): """An elastic tween function wobbles towards the midpoint. Args: n (float): The time progress, starting at 0.0...
_checkRange(n) n *= 2 if n < 1: return easeInElastic(n, amplitude=amplitude, period=period) / 2 else: return easeOutElastic(n-1, amplitude=amplitude, period=period) / 2 + 0.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 easeInBack(n, s=1.70158): """A tween function that backs up first at the start and then goes to the destination. Args: n (float): The time progress, startin...
_checkRange(n) return n * n * ((s + 1) * n - s)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def easeOutBack(n, s=1.70158): """A tween function that overshoots the destination a little and then backs into the destination. Args: n (float): The time progr...
_checkRange(n) n = n - 1 return n * n * ((s + 1) * n + s) + 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 easeInOutBack(n, s=1.70158): """A "back-in" tween function that overshoots both the start and destination. Args: n (float): The time progress, starting at 0...
_checkRange(n) n = n * 2 if n < 1: s *= 1.525 return 0.5 * (n * n * ((s + 1) * n - s)) else: n -= 2 s *= 1.525 return 0.5 * (n * n * ((s + 1) * n + s) + 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 easeOutBounce(n): """A bouncing tween function that hits the destination and then bounces to rest. Args: n (float): The time progress, starting at 0.0 and e...
_checkRange(n) if n < (1/2.75): return 7.5625 * n * n elif n < (2/2.75): n -= (1.5/2.75) return 7.5625 * n * n + 0.75 elif n < (2.5/2.75): n -= (2.25/2.75) return 7.5625 * n * n + 0.9375 else: n -= (2.65/2.75) return 7.5625 * n * n + 0.984375
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def formfield_for_manytomany(self, db_field, request, **kwargs): ''' Not all Admin subclasses use get_field_queryset here, so we will use it explicitly ''' db = kwargs.get('using') kwargs['queryset'] = kwargs.get('queryset', self.get_field_queryset(db, db_field, request)) ...
<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_selected(self, request, queryset): ''' The real delete function always evaluated either from the action, or from the instance delete link ''' opts = self.model._meta app_label = opts.app_label # Populate deletable_objects, a data structure of all related objec...
<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_deleted_objects(self, request, queryset): """ Find all objects related to instances of ``queryset`` that should also be deleted. Returns - to_delete - a ...
collector = NestedObjects(using=queryset.db) collector.collect(queryset) model_perms_needed = set() object_perms_needed = set() STRONG_DELETION_CONTROL = getattr(settings, 'ACCESS_STRONG_DELETION_CONTROL', False) def format_callback(obj): has_admin = 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 register_plugins(cls, plugins): ''' Reguster plugins. The plugins parameter should be dict mapping model to plugin. Just calls a register_plugin for every such a pair. ''' for model in plugins: cls.register_plugin(model, plugins[model])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def register_plugin(cls, model, plugin): ''' Reguster a plugin for the model. The only one plugin can be registered. If you want to combine plugins, use CompoundPlugin. ''' logger.info("Plugin registered for %s: %s", model, plugin) cls.plugins[model] = plugin
<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_default_plugin(cls): ''' Return a default plugin. ''' from importlib import import_module from django.conf import settings default_plugin = getattr(settings, 'ACCESS_DEFAULT_PLUGIN', "access.plugins.DjangoAccessPlugin") if default_plugin not in cls.default...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def plugin_for(cls, model): ''' Find and return a plugin for this model. Uses inheritance to find a model where the plugin is registered. ''' logger.debug("Getting a plugin for: %s", model) if not issubclass(model, Model): return if model in cls.plugins: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def visible(self, request): ''' Checks the both, check_visible and apply_visible, against the owned model and it's instance set ''' return self.apply_visible(self.get_queryset(), request) if self.check_visible(self.model, request) is not False else self.get_queryset().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 changeable(self, request): ''' Checks the both, check_changeable and apply_changeable, against the owned model and it's instance set ''' return self.apply_changeable(self.get_queryset(), request) if self.check_changeable(self.model, request) is not False else self.get_queryset().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 deleteable(self, request): ''' Checks the both, check_deleteable and apply_deleteable, against the owned model and it's instance set ''' return self.apply_deleteable(self.get_queryset(), request) if self.check_deleteable(self.model, request) is not False else self.get_queryset().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 get_plugin_from_string(plugin_name): """ Returns plugin or plugin point class from given ``plugin_name`` string. Example of ``plugin_name``:: 'my_app.MyPlugi...
modulename, classname = plugin_name.rsplit('.', 1) module = import_module(modulename) return getattr(module, classname)
<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_pdf(dist, params, size=10000): """Generate distributions's Propbability Distribution Function """
# Separate parts of parameters arg = params[:-2] loc = params[-2] scale = params[-1] # Get sane start and end points of distribution start = dist.ppf(0.01, *arg, loc=loc, scale=scale) if arg else dist.ppf(0.01, loc=loc, scale=scale) end = dist.ppf(0.99, *arg, loc=loc, scale=scale) if arg ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def urlencode(query, params): """ Correctly convert the given query and parameters into a full query+query string, ensuring the order of the params. """
return query + '?' + "&".join(key+'='+quote_plus(str(value)) for key, value in params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _load_from_string(data): '''Loads the cache from the string''' global _CACHE if PYTHON_3: data = json.loads(data.decode("utf-8")) else: data = json.loads(data) _CACHE = _recursively_convert_unicode_to_str(data)['data']
<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_model(cls, name=None, status=ENABLED): """ Returns model instance of plugin point or plugin, depending from which class this methos is called. Example:: ...
ppath = cls.get_pythonpath() if is_plugin_point(cls): if name is not None: kwargs = {} if status is not None: kwargs['status'] = status return Plugin.objects.get(point__pythonpath=ppath, ...
<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_point_model(cls): """ Returns plugin point model instance. Only used from plugin classes. """
if is_plugin_point(cls): raise Exception(_('This method is only available to plugin ' 'classes.')) else: return PluginPointModel.objects.\ get(plugin__pythonpath=cls.get_pythonpath())
<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_plugins(cls): """ Returns all plugin instances of plugin point, passing all args and kwargs to plugin constructor. """
# Django >= 1.9 changed something with the migration logic causing # plugins to be executed before the corresponding database tables # exist. This method will only return something if the database # tables have already been created. # XXX: I don't fully understand the issue and ...
<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_plugins_qs(cls): """ Returns query set of all plugins belonging to plugin point. Example:: for plugin_instance in MyPluginPoint.get_plugins_qs(): print(...
if is_plugin_point(cls): point_pythonpath = cls.get_pythonpath() return Plugin.objects.filter(point__pythonpath=point_pythonpath, status=ENABLED).\ order_by('index') else: raise Exception(_('This method is only...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def safeunicode(arg, *args, **kwargs): """Coerce argument to unicode, if it's not already."""
return arg if isinstance(arg, unicode) else unicode(arg, *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 get_reports(): """ Returns energy data from 1960 to 2014 across various factors. """
if False: # If there was a Test version of this method, it would go here. But alas. pass else: rows = _Constants._DATABASE.execute("SELECT data FROM energy".format( hardware=_Constants._HARDWARE)) data = [r[0] for r in rows] data = [_Auxiliary._byteify(_json....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def available(self, src, dst, model): """ Iterate over all registered plugins or plugin points and prepare to add them to database. """
for name, point in six.iteritems(src): inst = dst.pop(name, None) if inst is None: self.print_(1, "Registering %s for %s" % (model.__name__, name)) inst = model(pythonpath=name) if inst...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def missing(self, dst): """ Mark all missing plugins, that exists in database, but are not registered. """
for inst in six.itervalues(dst): if inst.status != REMOVED: inst.status = REMOVED inst.save()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def all(self): """ Synchronize all registered plugins and plugin points to database. """
# Django >= 1.9 changed something with the migration logic causing # plugins to be executed before the corresponding database tables # exist. This method will only return something if the database # tables have already been created. # XXX: I don't fully understand the issue and ...
<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_weather(test=False): """ Returns weather reports from the dataset. """
if _Constants._TEST or test: rows = _Constants._DATABASE.execute("SELECT data FROM weather LIMIT {hardware}".format( hardware=_Constants._HARDWARE)) data = [r[0] for r in rows] data = [_Auxiliary._byteify(_json.loads(r)) for r in data] return _Auxiliary._byteify...
<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, url, **kw): ''' Makes a GET request, setting Authorization header by default ''' headers = kw.pop('headers', {}) headers.setdefault('Content-Type', 'application/json') headers.setdefault('Accept', 'application/json') headers.setdefault('Auth...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _post(self, url, **kw): ''' Makes a POST request, setting Authorization header by default ''' headers = kw.pop('headers', {}) headers.setdefault('Authorization', self.AUTHORIZATION_HEADER) kw['headers'] = headers resp = self.session.post(url, **kw) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _post_json(self, url, data, **kw): ''' Makes a POST request, setting Authorization and Content-Type headers by default ''' data = json.dumps(data) headers = kw.pop('headers', {}) headers.setdefault('Content-Type', 'application/json') headers.setdefault...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def authenticate(self, login=None, password=None): ''' Authenticated this client instance. ``login`` and ``password`` default to the environment variables ``MS_LOGIN`` and ``MS_PASSWD`` respectively. :param login: Email address associated with a microsoft account :para...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def from_xuid(cls, xuid): ''' Instantiates an instance of ``GamerProfile`` from an xuid :param xuid: Xuid to look up :raises: :class:`~xbox.exceptions.GamertagNotFound` :returns: :class:`~xbox.GamerProfile` instance ''' url = 'https://profile.xboxlive....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def from_gamertag(cls, gamertag): ''' Instantiates an instance of ``GamerProfile`` from a gamertag :param gamertag: Gamertag to look up :raises: :class:`~xbox.exceptions.GamertagNotFound` :returns: :class:`~xbox.GamerProfile` instance ''' url = 'https:/...
<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(cls, xuid, scid, clip_id): ''' Gets a specific game clip :param xuid: xuid of an xbox live user :param scid: scid of a clip :param clip_id: id of a clip ''' url = ( 'https://gameclipsmetadata.xboxlive.com/users' '/xuid(%(xuid)s)/sc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def saved_from_user(cls, user, include_pending=False): ''' Gets all clips 'saved' by a user. :param user: :class:`~xbox.GamerProfile` instance :param bool include_pending: whether to ignore clips that are not yet uploaded. These clips will have thumbnails and 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 prepare_url(self, url, params): """Prepares the given HTTP URL."""
url = to_native_string(url) # Don't do any URL preparation for non-HTTP schemes like `mailto`, # `data` etc to work around exceptions from `url_parse`, which # handles RFC 3986 only. if ':' in url and not url.lower().startswith('http'): self.url = url 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 description_of(file, name='stdin'): """Return a string describing the probable encoding of a file."""
u = UniversalDetector() for line in file: u.feed(line) u.close() result = u.result if result['encoding']: return '%s: %s with confidence %s' % (name, result['encoding'], result['confidence'])...
<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): ''' Download the video. ''' #Callback self._debug('Provider', 'run', 'Running pre-download callback.') self._pre_download() url = None out = None success = False try: url = Provider._download(self.get_download_u...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dumps(obj, **kwargs): ''' Serialize `obj` to a JSON formatted `str`. Accepts the same arguments as `json` module in stdlib. :param obj: a JSON serializable Python object. :param kwargs: all the arguments that `json.dumps <http://docs.python.org/ 2/library/json.html#json.dumps>`_ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepend_name_prefix(func): """ Decorator that wraps instance methods to prepend the instance's filename prefix to the beginning of the referenced filename. M...
@wraps(func) def prepend_prefix(self, name, *args, **kwargs): name = self.name_prefix + name return func(self, name, *args, **kwargs) return prepend_prefix
<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_chalk(level): """Gets the appropriate piece of chalk for the logging level """
if level >= logging.ERROR: _chalk = chalk.red elif level >= logging.WARNING: _chalk = chalk.yellow elif level >= logging.INFO: _chalk = chalk.blue elif level >= logging.DEBUG: _chalk = chalk.green else: _chalk = chalk.white return _chalk
<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_str(obj): """Attempts to convert given object to a string object """
if not isinstance(obj, str) and PY3 and isinstance(obj, bytes): obj = obj.decode('utf-8') return obj if isinstance(obj, string_types) else str(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 get_color(self, value): """Helper method to validate and map values used in the instantiation of of the Color object to the correct unicode value. """
if value in COLOR_SET: value = COLOR_MAP[value] else: try: value = int(value) if value >= 8: raise ValueError() except ValueError as exc: raise ValueError( 'Colors should either a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shuffle(self, overwrite=False): """ This method creates new shuffled file. """
if overwrite: shuffled = self.path else: shuffled = FileAPI.add_ext_name(self.path, "_shuffled") lines = open(self.path).readlines() random.shuffle(lines) open(shuffled, "w").writelines(lines) self.path = shuffled
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def multiple_files_count_reads_in_windows(bed_files, args): # type: (Iterable[str], Namespace) -> OrderedDict[str, List[pd.DataFrame]] """Use count_reads on mult...
bed_windows = OrderedDict() # type: OrderedDict[str, List[pd.DataFrame]] for bed_file in bed_files: logging.info("Binning " + bed_file) if ".bedpe" in bed_file: chromosome_dfs = count_reads_in_windows_paired_end(bed_file, args) else: chromosome_dfs = count_reads...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _merge_files(windows, nb_cpu): # type: (Iterable[pd.DataFrame], int) -> pd.DataFrame """Merge lists of chromosome bin df chromosome-wise. windows is an Order...
# windows is a list of chromosome dfs per file windows = iter(windows) # can iterate over because it is odict_values merged = next(windows) # if there is only one file, the merging is skipped since the windows is used up for chromosome_dfs in windows: # merge_same_files merges the chromo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def py2round(value): """Round values as in Python 2, for Python 3 compatibility. All x.5 values are rounded away from zero. In Python 3, this has changed to avoi...
if value > 0: return float(floor(float(value)+0.5)) else: return float(ceil(float(value)-0.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 canonicalize(interval, lower_inc=True, upper_inc=False): """ Convert equivalent discrete intervals to different representations. """
if not interval.discrete: raise TypeError('Only discrete ranges can be canonicalized') if interval.empty: return interval lower, lower_inc = canonicalize_lower(interval, lower_inc) upper, upper_inc = canonicalize_upper(interval, upper_inc) return interval.__class__( [lowe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def glb(self, other): """ Return the greatest lower bound for given intervals. :param other: AbstractInterval instance """
return self.__class__( [ min(self.lower, other.lower), min(self.upper, other.upper) ], lower_inc=self.lower_inc if self < other else other.lower_inc, upper_inc=self.upper_inc if self > other else other.upper_inc, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lub(self, other): """ Return the least upper bound for given intervals. :param other: AbstractInterval instance """
return self.__class__( [ max(self.lower, other.lower), max(self.upper, other.upper), ], lower_inc=self.lower_inc if self < other else other.lower_inc, upper_inc=self.upper_inc if self > other else other.upper_inc, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compute_enriched_threshold(average_window_readcount): # type: (float) -> int """ Computes the minimum number of tags required in window for an island to be e...
current_threshold, survival_function = 0, 1 for current_threshold in count(start=0, step=1): survival_function -= poisson.pmf(current_threshold, average_window_readcount) if survival_function <= WINDOW_P_VALUE: break island_enriched_thr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _factln(num): # type: (int) -> float """ Computes logfactorial regularly for tractable numbers, uses Ramanujans approximation otherwise. """
if num < 20: log_factorial = log(factorial(num)) else: log_factorial = num * log(num) - num + log(num * (1 + 4 * num * ( 1 + 2 * num))) / 6.0 + log(pi) / 2 return log_factorial