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 should be abbreviations for the quantities, and its values should be a dictionary of the form {'name': string, 'units': string}. assumption_dict : dict A dictionary describing the assumptions used by the equations. Its keys should be short forms of the assumptions, and its values should be long forms of the assumptions, as you would insert into the sentence 'Calculates (quantity) assuming (assumption 1), (assumption 2), and (assumption 3).' equation : string, optional A string describing the equation the function uses. Should be wrapped to be no more than 80 characters in length. references : string, optional A string providing references for the function. Should be wrapped to be no more than 80 characters in length. Raises ------ ValueError: If the function name does not follow (varname)_from_(any text here), or if an argument of the function or the varname (as above) is not present in quantity_dict, or if an assumption in func.assumptions is not present in the assumption_dict. ''' # Now we have our utility functions, let's define the decorator itself def decorator(func): out_name_end_index = func.__name__.find('_from_') if out_name_end_index == -1: raise ValueError('equation_docstring decorator must be applied to ' 'function whose name contains "_from_"') out_quantity = func.__name__[:out_name_end_index] in_quantities = inspect.getargspec(func).args docstring = 'Calculates {0}'.format( quantity_string(out_quantity, quantity_dict)) try: if len(func.assumptions) > 0: docstring += ' assuming {0}'.format( assumption_list_string(func.assumptions, assumption_dict)) except AttributeError: pass docstring += '.' docstring = doc_paragraph(docstring) docstring += '\n\n' if equation is not None: func.equation = equation docstring += doc_paragraph(':math:`' + equation.strip() + '`') docstring += '\n\n' docstring += 'Parameters\n' docstring += '----------\n\n' docstring += '\n'.join([quantity_spec_string(q, quantity_dict) for q in in_quantities]) docstring += '\n\n' docstring += 'Returns\n' docstring += '-------\n\n' docstring += quantity_spec_string(out_quantity, quantity_dict) if notes is not None: docstring += '\n\n' docstring += 'Notes\n' docstring += '-----\n\n' docstring += notes.strip() if references is not None: if notes is None: # still need notes header for references docstring += '\n\n' docstring += 'Notes\n' docstring += '-----\n\n' func.references = references docstring += '\n\n' docstring += '**References**\n\n' docstring += references.strip() docstring += '\n' func.__doc__ = docstring 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 sma(array, window_size, axis=-1, mode='reflect', **kwargs): """ Computes a 1D simple moving average along the given axis. Parameters array : ndarray Array on which to perform the convolution. window_size: int Width of the simple moving average window in indices. axis : int, optional Axis along which to perform the moving average mode : {‘reflect’, ‘constant’, ‘nearest’, ‘mirror’, ‘wrap’}, optional The mode parameter determines how the array borders are handled, where cval is the value when mode is equal to ‘constant’. Default is ‘reflect’. kwargs : optional Other arguments to pass to `scipy.ndimage.filters.convolve1d` Returns ------- sma : ndarray Simple moving average of the given array with the specified window size along the requested axis. Raises ------ TypeError: If window_size or axis are not integers. """
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, **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 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(assumptions, six.string_types): raise TypeError('assumptions must be an iterable of strings, not a ' 'string itself') for a in assumptions: if a not in assumption_dict.keys(): raise ValueError('{} not present in assumption_dict'.format(a)) assumption_strings = [assumption_dict[a] for a in assumptions] return strings_to_list_string(assumption_strings)
<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_dict'.format(name)) s = '{0} : float or ndarray\n'.format(name) s += doc_paragraph('Data for {0}.'.format( quantity_string(name, quantity_dict)), indent=4) return 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 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. ''' return '\n'.join([' '*indent + l for l in wrap(s, width=80-indent)])
<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 closest value to x in L. Notes ----- Assumes x and the entries of L are of comparable types. Raises ------ ValueError: if L is empty ''' # Make sure the iterable is nonempty if len(L) == 0: raise ValueError('L must not be empty') if isinstance(L, np.ndarray): # use faster numpy methods if using a numpy array return (np.abs(L-x)).argmin() # for a general iterable (like a list) we need general Python # start by assuming the first item is closest min_index = 0 min_diff = abs(L[0] - x) i = 1 while i < len(L): # check if each other item is closer than our current closest diff = abs(L[i] - x) if diff < min_diff: # if it is, set it as the new closest min_index = i min_diff = diff i += 1 return min_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 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 locations of the polygon, in clockwise order. Returns ------- area : float The desired spherical area in the same units as r_sphere. Notes ----- This function assumes the vertices form a valid polygon (edges do not intersect each other). **References** Computing the Area of a Spherical Polygon of Arbitrary Shape Bevis and Cambareri (1987) Mathematical Geology, vol.19, Issue 4, pp 335-346 ''' dtr = np.pi/180. def _tranlon(plat, plon, qlat, qlon): t = np.sin((qlon-plon)*dtr)*np.cos(qlat*dtr) b = (np.sin(qlat*dtr)*np.cos(plat*dtr) - np.cos(qlat*dtr)*np.sin(plat*dtr)*np.cos((qlon-plon)*dtr)) return np.arctan2(t, b) if len(lat) < 3: raise ValueError('lat must have at least 3 vertices') if len(lat) != len(lon): raise ValueError('lat and lon must have the same length') total = 0. for i in range(-1, len(lat)-1): fang = _tranlon(lat[i], lon[i], lat[i+1], lon[i+1]) bang = _tranlon(lat[i], lon[i], lat[i-1], lon[i-1]) fvb = bang - fang if fvb < 0: fvb += 2.*np.pi total += fvb return (total - np.pi*float(len(lat)-2))*r_sphere**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 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, optional Boundary condition. If 'periodic', assume periodic boundary condition for centered difference. If 'forward-backward', take first-order forward or backward derivatives at boundary. Returns ------- derivative : ndarray Derivative of the data along the specified axis. Raises ------ ValueError: If an invalid boundary condition choice is given, if both dx and x are specified, if axis is out of the valid range for the shape of the data, or if x is specified and axis_x is out of the valid range for the shape of x. ''' if abs(axis) > len(data.shape): raise ValueError('axis is out of bounds for the shape of data') if boundary == 'periodic': diff = np.roll(data, -1, axis) - np.roll(data, 1, axis) elif boundary == 'forward-backward': # We will take forward-backward differencing at edges # need some fancy indexing to handle arbitrary derivative axis # Initialize our index lists front = [slice(s) for s in data.shape] back = [slice(s) for s in data.shape] target = [slice(s) for s in data.shape] # Set our index values for the derivative axis # front is the +1 index for derivative front[axis] = np.array([1, -1]) # back is the -1 index for derivative back[axis] = np.array([0, -2]) # target is the position where the derivative is being calculated target[axis] = np.array([0, -1]) diff = (np.roll(data, -1, axis) - np.roll(data, 1, axis))/(2.) diff[target] = (data[front]-data[back]) else: # invalid boundary condition was given raise ValueError('Invalid option {} for boundary ' 'condition.'.format(boundary)) return diff
<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_like temperature values, can also be used for things like dew point args Other positional arguments to pass to `semilogy` kwargs Other keyword arguments to pass to `semilogy` See Also -------- `matplotlib.Axes.semilogy` ''' # We need to replace the overridden plot with the original Axis plot # since it is called within Axes.semilogy no_plot = SkewTAxes.plot SkewTAxes.plot = Axes.plot Axes.semilogy(self, T, p, *args, **kwargs) # Be sure to put back the overridden plot method SkewTAxes.plot = no_plot self.yaxis.set_major_formatter(ScalarFormatter()) self.yaxis.set_major_locator(MultipleLocator(100)) labels = self.xaxis.get_ticklabels() for label in labels: label.set_rotation(45) label.set_horizontalalignment('right') label.set_fontsize(8) label.set_color('#B31515') self.grid(True) self.grid(axis='top', color='#B31515', linestyle='-', linewidth=1, alpha=0.5, zorder=1.1) self.grid(axis='x', color='#B31515', linestyle='-', linewidth=1, alpha=0.5, zorder=1.1) self.grid(axis='y', color='k', linestyle='-', linewidth=0.5, alpha=0.5, zorder=1.1) self.set_xlabel(r'Temperature ($^{\circ} C$)', color='#B31515') self.set_ylabel('Pressure ($hPa$)') if len(self._mixing_lines) == 0: self.plot_mixing_lines() if len(self._dry_adiabats) == 0: self.plot_dry_adiabats() if len(self._moist_adiabats) == 0: self.plot_moist_adiabats()
<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, located as a function of pressure. Parameters ---------- p : array_like pressure values u : array_like U (East-West) component of wind v : array_like V (North-South) component of wind xloc : float, optional Position for the barbs, in normalized axes coordinates, where 0.0 denotes far left and 1.0 denotes far right. Defaults to far right. x_clip_radius : float, optional Space, in normalized axes coordinates, to leave before clipping wind barbs in the x-direction. Defaults to 0.08. y_clip_radius : float, optional Space, in normalized axes coordinates, to leave above/below plot before clipping wind barbs in the y-direction. Defaults to 0.08. kwargs Other keyword arguments to pass to `barbs` See Also -------- `matplotlib.Axes.barbs` ''' #kwargs.setdefault('length', 7) # Assemble array of x-locations in axes space x = np.empty_like(p) x.fill(xloc) # Do barbs plot at this location b = self.barbs(x, p, u, v, transform=self.get_yaxis_transform(which='tick2'), clip_on=True, **kwargs) # Override the default clip box, which is the axes rectangle, so we can # have barbs that extend outside. ax_bbox = transforms.Bbox([[xloc-x_clip_radius, -y_clip_radius], [xloc+x_clip_radius, 1.0 + y_clip_radius]]) b.set_clip_box(transforms.TransformedBbox(ax_bbox, self.transAxes))
<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. Parameters ---------- p : array_like, optional 1-dimensional array of pressure values to be included in the dry adiabats. If not specified, they will be linearly distributed across the current plotted pressure range. theta : array_like, optional 1-dimensional array of potential temperature values for dry adiabats. By default these will be generated based on the current temperature limits. kwargs Other keyword arguments to pass to `matplotlib.collections.LineCollection` See Also#B85C00 -------- plot_moist_adiabats `matplotlib.collections.LineCollection` `metpy.calc.dry_lapse` ''' for artist in self._dry_adiabats: artist.remove() self._dry_adiabats = [] # Determine set of starting temps if necessary if theta is None: xmin, xmax = self.get_xlim() theta = np.arange(xmin, xmax + 201, 10) # Get pressure levels based on ylims if necessary if p is None: p = np.linspace(*self.get_ylim()) # Assemble into data for plotting t = calculate('T', theta=theta[:, None], p=p, p_units='hPa', T_units='degC', theta_units='degC') linedata = [np.vstack((ti, p)).T for ti in t] # Add to plot kwargs.setdefault('clip_on', True) kwargs.setdefault('colors', '#A65300') kwargs.setdefault('linestyles', '-') kwargs.setdefault('alpha', 1) kwargs.setdefault('linewidth', 0.5) kwargs.setdefault('zorder', 1.1) collection = LineCollection(linedata, **kwargs) self._dry_adiabats.append(collection) self.add_collection(collection) theta = theta.flatten() T_label = calculate('T', p=140, p_units='hPa', theta=theta, T_units='degC', theta_units='degC') for i in range(len(theta)): text = self.text( T_label[i], 140, '{:.0f}'.format(theta[i]), fontsize=8, ha='left', va='center', rotation=-60, color='#A65300', bbox={ 'facecolor': 'w', 'edgecolor': 'w', 'alpha': 0, }, zorder=1.2) text.set_clip_on(True) self._dry_adiabats.append(text)
<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. Parameters ---------- rv : array_like, optional 1-dimensional array of unitless mixing ratio values to plot. If none are given, default values are used. p : array_like, optional 1-dimensional array of pressure values to be included in the isohumes. If not specified, they will be linearly distributed across the current plotted pressure range. kwargs Other keyword arguments to pass to `matplotlib.collections.LineCollection` See Also -------- `matplotlib.collections.LineCollection` ''' for artist in self._mixing_lines: artist.remove() self._mixing_lines = [] # Default mixing level values if necessary if rv is None: rv = np.array([ 0.1e-3, 0.2e-3, 0.5e-3, 1e-3, 1.5e-3, 2e-3, 3e-3, 4e-3, 6e-3, 8e-3, 10e-3, 12e-3, 15e-3, 20e-3, 30e-3, 40e-3, 50e-3]).reshape(-1, 1) else: rv = np.asarray(rv).reshape(-1, 1) # Set pressure range if necessary if p is None: p = np.linspace(min(self.get_ylim()), max(self.get_ylim())) else: p = np.asarray(p) # Assemble data for plotting Td = calculate( 'Td', p=p, rv=rv, p_units='hPa', rv_units='kg/kg', Td_units='degC') Td_label = calculate('Td', p=550, p_units='hPa', rv=rv, Td_units='degC') linedata = [np.vstack((t, p)).T for t in Td] # Add to plot kwargs.setdefault('clip_on', True) kwargs.setdefault('colors', '#166916') kwargs.setdefault('linestyles', '--') kwargs.setdefault('alpha', 1) kwargs.setdefault('linewidth', 0.5) kwargs.setdefault('zorder', 1.1) collection = LineCollection(linedata, **kwargs) self._mixing_lines.append(collection) self.add_collection(collection) rv = rv.flatten() * 1000 for i in range(len(rv)): if rv[i] < 1: format_string = '{:.1f}' else: format_string = '{:.0f}' t = self.text(Td_label[i], 550, format_string.format(rv[i]), fontsize=8, ha='right', va='center', rotation=60, color='#166916', bbox={ 'facecolor': 'w', 'edgecolor': 'w', 'alpha': 0, }, zorder=1.2) t.set_clip_on(True) self._mixing_lines.append(t)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def 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 methods.keys(): if output in output_quantities or output in inputs: # we already know we can calculate this continue for args, func in methods[output].items(): if all([arg in inputs or arg in output_quantities for arg in args]): output_quantities.append(output) updated = True break return tuple(output_quantities) + tuple(inputs)
<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 equations that might help calculate the outputs from the inputs. ''' # Get a list of everything that we can possibly calculate # This is useful in figuring out whether we can calculate arguments intermediates = get_calculatable_quantities(inputs, methods) # Initialize our return dictionary return_methods = {} # list so that we can append arguments that need to be output for # some of the paths outputs = list(outputs) # keep track of when to exit the while loop keep_going = True while keep_going: # If there are no updates in a pass, the loop will exit keep_going = False for output in outputs: try: output_dict = return_methods[output] except: output_dict = {} for args, func in methods[output].items(): # only check the method if we're not already returning it if args not in output_dict.keys(): # Initialize a list of intermediates needed to use # this method, to add to outputs if we find we can # use it. needed = [] for arg in args: if arg in inputs: # we have this argument pass elif arg in outputs: # we may need to calculate one output using # another output pass elif arg in intermediates: if arg not in outputs: # don't need to add to needed if it's already # been put in outputs needed.append(arg) else: # Can't do this func break else: # did not break, can calculate this output_dict[args] = func if len(needed) > 0: # We added an output, so need another loop outputs.extend(needed) keep_going = True if len(output_dict) > 0: return_methods[output] = output_dict return return_methods
<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 given output variable, which is the one with the fewest possible arguments. ''' # Initialize a return dictionary calculatable_methods = {} # Iterate through each potential method output for var in methods.keys(): # See if we already have this output if var in inputs: continue # if we have it, we don't need to calculate it! else: # Initialize a dict for this output variable var_dict = {} for args, func in methods[var].items(): # See if we have what we need to solve this equation if all([arg in inputs for arg in args]): # If we do, add it to the var_dict var_dict[args] = func if len(var_dict) == 0: # No methods for this variable, keep going continue elif len(var_dict) == 1: # Exactly one method, perfect. calculatable_methods[var] = var_dict else: # More than one method, find the one with the least arguments min_args = min(var_dict.keys(), key=lambda x: len(x)) calculatable_methods[var] = {min_args: var_dict[min_args]} return calculatable_methods
<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 'overridden_by_assumptions' as keys, stating which assumptions are required to use the method, and which assumptions mean the method should not be used because it is overridden. ''' # Set up the methods dict we will eventually return methods = [] funcs = [] for item in inspect.getmembers(equations): if (item[0][0] != '_' and '_from_' in item[0]): func = item[1] output = item[0][:item[0].find('_from_')] # avoid returning duplicates if func in funcs: continue else: funcs.append(func) args = tuple(getfullargspec(func).args) try: assumptions = tuple(func.assumptions) except AttributeError: raise NotImplementedError('function {0} in equations module has no' ' assumption ' 'definition'.format(func.__name__)) try: overridden_by_assumptions = func.overridden_by_assumptions except AttributeError: overridden_by_assumptions = () methods.append({ 'func': func, 'args': args, 'output': output, 'assumptions': assumptions, 'overridden_by_assumptions': overridden_by_assumptions, }) return methods
<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 assumptions. See below for a list of default assumptions. add_assumptions : tuple, optional Strings specifying assumptions to use in addition to the default assumptions. May not be given in combination with the assumptions kwarg. remove_assumptions : tuple, optional Strings specifying assumptions not to use from the default assumptions. May not be given in combination with the assumptions kwarg. May not contain strings that are contained in add_assumptions, if given. \*\*kwargs : ndarray, optional Keyword arguments used to pass in arrays of data that correspond to quantities used for calculations, or unit specifications for quantities. For a complete list of kwargs that may be used, see the Quantity Parameters section below. Returns ------- quantity : ndarray Calculated quantity. Return type is the same as quantity parameter types. If multiple quantities are requested, returns a tuple containing the quantities. Notes ----- Calculating multiple quantities at once can avoid re-computing intermediate quantities, but requires more memory. **Quantity kwargs** <quantity parameter list goes here> In addition to the quantities above, kwargs of the form <quantity>_unit or <quantity>_units can be used with a string specifying a unit for the quantity. This will cause input data for that quantity to be assumed to be in that unit, and output data for that quantity to be given in that unit. Note this must be specified separately for *each* quantity. Acceptable units are the units available in the Pint package, with the exception that RH can be in units of "fraction" or "percent". **Assumptions** <default assumptions list goes here> **Assumption descriptions** <assumptions list goes here> Examples -------- Calculating pressure from virtual temperature and density: >>> calculate('p', Tv=273., rho=1.27) 99519.638400000011 Same calculation, but also returning a list of functions used: >>> p, funcs = calculate('p', Tv=273., rho=1.27, debug=True) >>> funcs (<function atmos.equations.p_from_rho_Tv_ideal_gas>,) Same calculation with temperature instead, ignoring virtual temperature correction: >>> calculate('p', T=273., rho=1.27, add_assumptions=('Tv equals T',)) 99519.638400000011 ''' if len(args) == 0: raise ValueError('must specify quantities to calculate') # initialize a solver to do the work solver = FluidSolver(**kwargs) # get the output return solver.calculate(*args)
<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('{ssid}:{password}'.format(ssid=ssid, password=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 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, restapi=self.schema.restApi, rscpath=self.schema.resourcePath, query=self.schema.query) return url.replace('/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 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): return zoomlevel(resources['ElevationData']['ZoomLevel']) except KeyError: try: if isinstance(resources['SeaLevelData'], dict): zoom = resources['SeaLevelData']['ZoomLevel'] return zoomlevel(zoom) except KeyError: print(KeyError)
<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 compaction options were modified in Cassandra, `False` otherwise. :rtype: bool """
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']) desired_options = get_compaction_options(model) desired_compact_strategy = desired_options.get('class', SizeTieredCompactionStrategy) desired_options.pop('class', None) do_update = False if desired_compact_strategy not in existing_compaction_strategy: do_update = True for k, v in desired_options.items(): val = existing_options.pop(k, None) if val != v: do_update = True # check compaction_strategy_options if do_update: options = get_compaction_options(model) # jsonify options = json.dumps(options).replace('"', "'") cf_name = model.column_family_name() query = "ALTER TABLE {} with compaction = {}".format(cf_name, options) logger.debug(query) execute(query) return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup( hosts, default_keyspace, consistency=ConsistencyLevel.ONE, lazy_connect=False, retry_connect=False, **kwargs): """ Records the hosts and connects to one of them :param hosts: list of hosts, see http://datastax.github.io/python-driver/api/cassandra/cluster.html :type hosts: list :param default_keyspace: The default keyspace to use :type default_keyspace: str :param consistency: The global consistency level :type consistency: int :param lazy_connect: True if should not connect until first use :type lazy_connect: bool :param retry_connect: bool :param retry_connect: True if we should retry to connect even if there was a connection failure initially """
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() from cqlengine import models models.DEFAULT_KEYSPACE = default_keyspace default_consistency_level = consistency if lazy_connect: kwargs['default_keyspace'] = default_keyspace kwargs['consistency'] = consistency kwargs['lazy_connect'] = False kwargs['retry_connect'] = retry_connect lazy_connect_args = (hosts, kwargs) return cluster = Cluster(hosts, **kwargs) try: session = cluster.connect() except NoHostAvailable: if retry_connect: kwargs['default_keyspace'] = default_keyspace kwargs['consistency'] = consistency kwargs['lazy_connect'] = False kwargs['retry_connect'] = retry_connect lazy_connect_args = (hosts, kwargs) raise session.row_factory = dict_factory
<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 * 1e9) timestamp = int(nanoseconds // 100) + 0x01b21dd213814000 if clock_seq is None: import random clock_seq = random.randrange(1 << 14) # instead of stable storage time_low = timestamp & 0xffffffff time_mid = (timestamp >> 32) & 0xffff time_hi_version = (timestamp >> 48) & 0x0fff clock_seq_low = clock_seq & 0xff clock_seq_hi_variant = (clock_seq >> 8) & 0x3f if node is None: node = getnode() return pyUUID(fields=(time_low, time_mid, time_hi_version, clock_seq_hi_variant, clock_seq_low, node), version=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 _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): raise QueryException('{} is not a valid query operator'.format(operator)) clone._where.append(operator) for arg, val in kwargs.items(): col_name, col_op = self._parse_filter_arg(arg) quote_field = True #resolve column and operator try: column = self.model._get_column(col_name) except KeyError: if col_name == 'pk__token': if not isinstance(val, Token): raise QueryException("Virtual column 'pk__token' may only be compared to Token() values") column = columns._PartitionKeysToken(self.model) quote_field = False else: raise QueryException("Can't resolve column name: '{}'".format(col_name)) if isinstance(val, Token): if col_name != 'pk__token': raise QueryException("Token() values may only be compared to the 'pk__token' virtual column") partition_columns = column.partition_columns if len(partition_columns) != len(val.value): raise QueryException( 'Token() received {} arguments but model has {} partition keys'.format( len(val.value), len(partition_columns))) val.set_columns(partition_columns) #get query operator, or use equals if not supplied operator_class = BaseWhereOperator.get_operator(col_op or 'EQ') operator = operator_class() if isinstance(operator, InOperator): if not isinstance(val, (list, tuple)): raise QueryException('IN queries must use a list/tuple value') query_val = [column.to_database(v) for v in val] elif isinstance(val, BaseQueryFunction): query_val = val else: query_val = column.to_database(val) clone._where.append(WhereClause(column.db_field_name, operator, query_val, quote_field=quote_field)) 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 order_by(self, *colnames): """ orders the result set. ordering can only use clustering columns. Default order is ascending, prepend a '-' to the column name for descending """
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) clone._order.extend(conditions) 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 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'] else: return len(self._result_cache)
<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 = self._parse_filter_arg(name) col = self.model._columns.get(col_name) # check for nonexistant columns if col is None: raise ValidationError("{}.{} has no column named: {}".format(self.__module__, self.model.__name__, col_name)) # check for primary key update attempts if col.is_primary_key: raise ValidationError("Cannot apply update to primary key '{}' for {}.{}".format(col_name, self.__module__, self.model.__name__)) # we should not provide default values in this use case. val = col.validate(val) if val is None: nulled_columns.add(col_name) continue # add the update statements if isinstance(col, Counter): # TODO: implement counter updates raise NotImplementedError elif isinstance(col, (List, Set, Map)): if isinstance(col, List): klass = ListUpdateClause elif isinstance(col, Set): klass = SetUpdateClause elif isinstance(col, Map): klass = MapUpdateClause else: raise RuntimeError us.add_assignment_clause(klass(col_name, col.to_database(val), operation=col_op)) else: us.add_assignment_clause(AssignmentClause( col_name, col.to_database(val))) if us.assignments: self._execute(us) if nulled_columns: ds = DeleteStatement(self.column_family_name, fields=nulled_columns, where=self._where) self._execute(ds)
<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': {} # None or dict }, ] } if no formaters, use autopep8 formater and it's default config """
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_length = None for formater in formaters: max_line_length = formater.get('config', {}).get('max_line_length') if max_line_length: break for formater in formaters: name = formater.get('name', None) config = formater.get('config', {}) if name not in FORMATERS: return send(client, 'formater {} not support'.format(name), None) formater = FORMATERS[name] if formater is None: return send(client, 'formater {} not installed'.format(name), None) if name == 'isort' and max_line_length: config.setdefault('line_length', max_line_length) data = formater(data, **config) return send(client, None, 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 easeInOutQuad(n): """A quadratic tween function that accelerates, reaches the midpoint, and then decelerates. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine(). """
_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.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine(). """
_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 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine(). """
_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 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine(). """
_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, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine(). """
_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 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine(). """
_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 (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine(). """
_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: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine(). """
_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 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine(). """
_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, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine(). """
_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 progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine(). """
_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.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine(). """
_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 ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine(). """
_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)) return super(AccessControlMixin, self).formfield_for_manytomany(db_field, request, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def delete_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 objects that # will also be deleted. deletable_objects, model_count, perms_needed, protected = self.get_deleted_objects(request, queryset) # The user has already confirmed the deletion. # Do the deletion and return a None to display the change list view again. if request.POST.get('post') and not protected: if perms_needed or protected: raise PermissionDenied n = queryset.count() if n: for obj in queryset: obj_display = force_text(obj) self.log_deletion(request, obj, obj_display) queryset.delete() self.message_user(request, _("Successfully deleted %(count)d %(items)s.") % { "count": n, "items": model_ngettext(self.opts, n) }, messages.SUCCESS) # Return None to display the change list page again. return None sz = queryset.count() if sz == 1: objects_name = _('%(verbose_name)s "%(object)s"') % { 'verbose_name': force_text(opts.verbose_name), 'object': queryset[0] } else: objects_name = _('%(count)s %(verbose_name_plural)s') % { 'verbose_name_plural': force_text(opts.verbose_name_plural), 'count': sz } if perms_needed or protected: title = _("Cannot delete %(name)s") % {"name": objects_name} else: title = _("Are you sure?") context = dict( self.admin_site.each_context(request), title=title, objects_name=objects_name, deletable_objects=[deletable_objects], model_count=dict(model_count).items(), queryset=queryset, perms_lacking=perms_needed, protected=protected, opts=opts, action_checkbox_name=helpers.ACTION_CHECKBOX_NAME, media=self.media, ) request.current_app = self.admin_site.name # Display the confirmation page return TemplateResponse(request, self.delete_selected_confirmation_template or [ "admin/%s/%s/delete_selected_confirmation.html" % (app_label, opts.model_name), "admin/%s/delete_selected_confirmation.html" % app_label, "admin/delete_selected_confirmation.html" ], context)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_deleted_objects(self, request, queryset): """ Find all objects related to instances of ``queryset`` that should also be deleted. Returns - to_delete - a nested list of strings suitable for display in the template with the ``unordered_list`` filter. - model_count - statistics for models of all deleted instances - perms_needed - list of names for all instances which can not be deleted because of not enough rights - protected - list of names for all objects protected for deletion because of reference type """
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.__class__ in self.admin_site._registry opts = obj._meta no_edit_link = '%s: %s' % (capfirst(opts.verbose_name), force_text(obj)) # Trying to get admin change URL admin_url = None try: admin_url = reverse('%s:%s_%s_change' % (self.admin_site.name, opts.app_label, opts.model_name), None, (quote(obj._get_pk_val()),)) except NoReverseMatch: # Change url doesn't exist -- don't display link to edit pass # Collecting forbidden subobjects, compatible with Django or forced by the option if STRONG_DELETION_CONTROL or has_admin: if not obj.__class__._meta.auto_created: manager = AccessManager(obj.__class__) # filter out forbidden items if manager.check_deleteable(obj.__class__, request) is False: model_perms_needed.add(opts.verbose_name) if not manager.apply_deleteable(obj.__class__._default_manager.filter(pk=obj.pk), request): object_perms_needed.add(obj) if admin_url: # Display a link to the admin page. return format_html('{}: <a href="{}">{}</a>', capfirst(opts.verbose_name), admin_url, obj) else: # Don't display link to edit, because it either has no # admin or is edited inline. return no_edit_link to_delete = collector.nested(format_callback) protected = [format_callback(obj) for obj in collector.protected] protected = set([format_callback(obj) for obj in object_perms_needed]).union(protected) model_count = {model._meta.verbose_name_plural: len(objs) for model, objs in collector.model_objs.items()} return to_delete, model_count, model_perms_needed, protected
<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_plugins: logger.info("Creating a default plugin: %s", default_plugin) path = default_plugin.split('.') plugin_path = '.'.join(path[:-1]) plugin_name = path[-1] DefaultPlugin = getattr(import_module(plugin_path), plugin_name) cls.default_plugins[default_plugin] = DefaultPlugin() return cls.default_plugins[default_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 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: return cls.plugins[model] for b in model.__bases__: p = cls.plugin_for(b) if p: return p
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def 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.MyPlugin' """
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 else dist.ppf(0.99, loc=loc, scale=scale) # Build PDF and turn into pandas Series x = np.linspace(start, end, size) y = dist.pdf(x, loc=loc, scale=scale, *arg) pdf = pd.Series(y, x) return pdf
<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:: plugin_model_instance = MyPlugin.get_model() plugin_model_instance = MyPluginPoint.get_model('plugin-name') plugin_point_model_instance = MyPluginPoint.get_model() """
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, name=name, **kwargs) else: return PluginPointModel.objects.get(pythonpath=ppath) else: return Plugin.objects.get(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 there should be # another way but this appears to work fine. if django_version >= (1, 9) and \ not db_table_exists(Plugin._meta.db_table): raise StopIteration if is_plugin_point(cls): for plugin_model in cls.get_plugins_qs(): yield plugin_model.get_plugin() else: raise Exception(_('This method is only available to plugin point ' 'classes.'))
<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(plugin_instance.get_plugin().name) """
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 available to plugin point ' 'classes.'))
<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.loads(r)) for r in data] return _Auxiliary._byteify(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 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.status == REMOVED: self.print_(1, "Updating %s for %s" % (model.__name__, name)) # re-enable a previously removed plugin point and its plugins inst.status = ENABLED yield point, 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 there should be # another way but this appears to work fine. if django_version >= (1, 9) and ( not db_table_exists(Plugin._meta.db_table) or not db_table_exists(PluginPoint._meta.db_table)): return self.points()
<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(data) else: rows = _Constants._DATABASE.execute("SELECT data FROM weather".format( hardware=_Constants._HARDWARE)) data = [r[0] for r in rows] data = [_Auxiliary._byteify(_json.loads(r)) for r in data] return _Auxiliary._byteify(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(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('Authorization', self.AUTHORIZATION_HEADER) kw['headers'] = headers resp = self.session.get(url, **kw) self._raise_for_status(resp) return resp
<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) self._raise_for_status(resp) return resp
<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('Accept', 'application/json') kw['headers'] = headers kw['data'] = data return self._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 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 :param password: Matching password :raises: :class:`~xbox.exceptions.AuthenticationException` :returns: Instance of :class:`~xbox.Client` ''' if login is None: login = os.environ.get('MS_LOGIN') if password is None: password = os.environ.get('MS_PASSWD') if not login or not password: msg = ( 'Authentication credentials required. Please refer to ' 'http://xbox.readthedocs.org/en/latest/authentication.html' ) raise AuthenticationException(msg) self.login = login # firstly we have to GET the login page and extract # certain data we need to include in our POST request. # sadly the data is locked away in some javascript code base_url = 'https://login.live.com/oauth20_authorize.srf?' # if the query string is percent-encoded the server # complains that client_id is missing qs = unquote(urlencode({ 'client_id': '0000000048093EE3', 'redirect_uri': 'https://login.live.com/oauth20_desktop.srf', 'response_type': 'token', 'display': 'touch', 'scope': 'service::user.auth.xboxlive.com::MBI_SSL', 'locale': 'en', })) resp = self.session.get(base_url + qs) # python 3.x will error if this string is not a # bytes-like object url_re = b'urlPost:\\\'([A-Za-z0-9:\?_\-\.&/=]+)' ppft_re = b'sFTTag:\\\'.*value="(.*)"/>' login_post_url = re.search(url_re, resp.content).group(1) post_data = { 'login': login, 'passwd': password, 'PPFT': re.search(ppft_re, resp.content).groups(1)[0], 'PPSX': 'Passpor', 'SI': 'Sign in', 'type': '11', 'NewUser': '1', 'LoginOptions': '1', 'i3': '36728', 'm1': '768', 'm2': '1184', 'm3': '0', 'i12': '1', 'i17': '0', 'i18': '__Login_Host|1', } resp = self.session.post( login_post_url, data=post_data, allow_redirects=False, ) if 'Location' not in resp.headers: # we can only assume the login failed msg = 'Could not log in with supplied credentials' raise AuthenticationException(msg) # the access token is included in fragment of the location header location = resp.headers['Location'] parsed = urlparse(location) fragment = parse_qs(parsed.fragment) access_token = fragment['access_token'][0] url = 'https://user.auth.xboxlive.com/user/authenticate' resp = self.session.post(url, data=json.dumps({ "RelyingParty": "http://auth.xboxlive.com", "TokenType": "JWT", "Properties": { "AuthMethod": "RPS", "SiteName": "user.auth.xboxlive.com", "RpsTicket": access_token, } }), headers={'Content-Type': 'application/json'}) json_data = resp.json() user_token = json_data['Token'] uhs = json_data['DisplayClaims']['xui'][0]['uhs'] url = 'https://xsts.auth.xboxlive.com/xsts/authorize' resp = self.session.post(url, data=json.dumps({ "RelyingParty": "http://xboxlive.com", "TokenType": "JWT", "Properties": { "UserTokens": [user_token], "SandboxId": "RETAIL", } }), headers={'Content-Type': 'application/json'}) response = resp.json() self.AUTHORIZATION_HEADER = 'XBL3.0 x=%s;%s' % (uhs, response['Token']) self.user_xid = response['DisplayClaims']['xui'][0]['xid'] self.authenticated = True return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def 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.com/users/xuid(%s)/profile/settings' % xuid try: return cls._fetch(url) except (GamertagNotFound, InvalidRequest): # this endpoint seems to return 400 when the resource # does not exist raise GamertagNotFound('No such user: %s' % xuid)
<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://profile.xboxlive.com/users/gt(%s)/profile/settings' % gamertag try: return cls._fetch(url) except GamertagNotFound: raise GamertagNotFound('No such user: %s' % gamertag)
<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)/scids/%(scid)s/clips/%(clip_id)s' % { 'xuid': xuid, 'scid': scid, 'clip_id': clip_id, } ) resp = xbox.client._get(url) # scid does not seem to matter when fetching clips, # as long as it looks like a uuid it should be fine. # perhaps we'll raise an exception in future if resp.status_code == 404: msg = 'Could not find clip: xuid=%s, scid=%s, clip_id=%s' % ( xuid, scid, clip_id, ) raise ClipNotFound(msg) data = resp.json() # as we don't have the user object let's # create a lazily evaluated proxy object # that will fetch it only when required user = UserProxy(xuid) return cls(user, data['gameClip'])
<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 set to ``None`` :returns: Iterator of :class:`~xbox.Clip` instances ''' url = 'https://gameclipsmetadata.xboxlive.com/users/xuid(%s)/clips/saved' resp = xbox.client._get(url % user.xuid) data = resp.json() for clip in data['gameClips']: if clip['state'] != 'PendingUpload' or include_pending: yield cls(user, clip)
<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 return # Support for unicode domain names and paths. scheme, auth, host, port, path, query, fragment = parse_url(url) if not scheme: raise MissingSchema("Invalid URL {0!r}: No schema supplied. " "Perhaps you meant http://{0}?".format(url)) if not host: raise InvalidURL("Invalid URL %r: No host supplied" % url) # Only want to apply IDNA to the hostname try: host = host.encode('idna').decode('utf-8') except UnicodeError: raise InvalidURL('URL has an invalid label.') # Carefully reconstruct the network location netloc = auth or '' if netloc: netloc += '@' netloc += host if port: netloc += ':' + str(port) # Bare domains aren't valid URLs. if not path: path = '/' if is_py2: if isinstance(scheme, str): scheme = scheme.encode('utf-8') if isinstance(netloc, str): netloc = netloc.encode('utf-8') if isinstance(path, str): path = path.encode('utf-8') if isinstance(query, str): query = query.encode('utf-8') if isinstance(fragment, str): fragment = fragment.encode('utf-8') enc_params = self._encode_params(params) if enc_params: if query: query = '%s&%s' % (query, enc_params) else: query = enc_params url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment])) self.url = 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 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']) else: return '%s: no result' % 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(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_url()) #Callback self._debug('Provider', 'run', 'Running in-download callback.') self._in_download(url) #Invalid filename character fix if IS_WINDOWS: self.filename = re.sub(ur'[?\/\\<>:"*|]+', '_', self.filename, re.UNICODE) self.full_filename = '%s.%s' % (self.filename, self.fileext) self._debug('Provider', 'run', 'full_filename', self.full_filename) if not os.path.isfile(self.full_filename): #Save the stream to the output file out = open(self.full_filename, 'wb') out.write(url.read()) else: #Skipping #TODO: warn pass #We are done therefore success! success = True finally: if out is not None: out.close() if url is not None: url.close() #Callback self._debug('Provider', 'run', 'Running post-download callback.') self._debug('Provider', 'run', 'success', success) self._post_download(success)
<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>`_ accepts. :raises: commentjson.JSONLibraryException :returns str: serialized string. ''' try: return json.dumps(obj, **kwargs) except Exception as e: raise JSONLibraryException(e)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepend_name_prefix(func): """ Decorator that wraps instance methods to prepend the instance's filename prefix to the beginning of the referenced filename. Must only be used on instance methods where the first parameter after `self` is `name` or a comparable parameter of a different name. """
@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 member of: {} or a positive ' 'integer below 8'.format(', '.join(COLOR_NAMES)) ) return '{}{}'.format(self.PREFIX, 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 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 multiple files and store result in dict. Untested since does the same thing as count reads."""
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_in_windows(bed_file, args) bed_windows[bed_file] = chromosome_dfs return bed_windows
<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 OrderedDict where the keys are files, the values are lists of dfs, one per chromosome. Returns a list of dataframes, one per chromosome, with the collective count per bin for all files. TODO: is it faster to merge all in one command? """
# 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 chromosome files in parallel merged = merge_same_files(merged, chromosome_dfs, nb_cpu) return merged
<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 avoid bias: when x is even, rounding is towards zero, when x is odd, rounding is away from zero. Thus, in Python 3, round(2.5) results in 2, round(3.5) is 4. Python 3 also returns an int; Python 2 returns a float. """
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__( [lower, upper], lower_inc=lower_inc, upper_inc=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 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 enriched. """
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_threshold = current_threshold + 1 return island_enriched_threshold
<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