anchor
stringlengths
16
95
positive
stringlengths
87
6.25k
negative
stringlengths
87
6.4k
python equivalent of matlab movmean function
def _propagate_mean(mean, linop, dist): """Propagate a mean through linear Gaussian transformation.""" return linop.matmul(mean) + dist.mean()[..., tf.newaxis]
def average_gradient(data, *kwargs): """ Compute average gradient norm of an image """ return np.average(np.array(np.gradient(data))**2)
python equivalent of matlab movmean function
def _propagate_mean(mean, linop, dist): """Propagate a mean through linear Gaussian transformation.""" return linop.matmul(mean) + dist.mean()[..., tf.newaxis]
def hmean_int(a, a_min=5778, a_max=1149851): """ Harmonic mean of an array, returns the closest int """ from scipy.stats import hmean return int(round(hmean(np.clip(a, a_min, a_max))))
python equivalent of matlab movmean function
def _propagate_mean(mean, linop, dist): """Propagate a mean through linear Gaussian transformation.""" return linop.matmul(mean) + dist.mean()[..., tf.newaxis]
def get_mi_vec(slab): """ Convenience function which returns the unit vector aligned with the miller index. """ mvec = np.cross(slab.lattice.matrix[0], slab.lattice.matrix[1]) return mvec / np.linalg.norm(mvec)
python equivalent of matlab movmean function
def _propagate_mean(mean, linop, dist): """Propagate a mean through linear Gaussian transformation.""" return linop.matmul(mean) + dist.mean()[..., tf.newaxis]
def _mean_absolute_error(y, y_pred, w): """Calculate the mean absolute error.""" return np.average(np.abs(y_pred - y), weights=w)
python equivalent of matlab movmean function
def _propagate_mean(mean, linop, dist): """Propagate a mean through linear Gaussian transformation.""" return linop.matmul(mean) + dist.mean()[..., tf.newaxis]
def mean(inlist): """ Returns the arithematic mean of the values in the passed list. Assumes a '1D' list, but will function on the 1st dim of an array(!). Usage: lmean(inlist) """ sum = 0 for item in inlist: sum = sum + item return sum / float(len(inlist))
python execute function with locals
def exec_function(ast, globals_map): """Execute a python code object in the given environment. Args: globals_map: Dictionary to use as the globals context. Returns: locals_map: Dictionary of locals from the environment after execution. """ locals_map = globals_map exec ast in global...
def __call__(self, args): """Execute the user function.""" window, ij = args return self.user_func(srcs, window, ij, global_args), window
python execute function with locals
def exec_function(ast, globals_map): """Execute a python code object in the given environment. Args: globals_map: Dictionary to use as the globals context. Returns: locals_map: Dictionary of locals from the environment after execution. """ locals_map = globals_map exec ast in global...
def ex(self, cmd): """Execute a normal python statement in user namespace.""" with self.builtin_trap: exec cmd in self.user_global_ns, self.user_ns
python execute function with locals
def exec_function(ast, globals_map): """Execute a python code object in the given environment. Args: globals_map: Dictionary to use as the globals context. Returns: locals_map: Dictionary of locals from the environment after execution. """ locals_map = globals_map exec ast in global...
def __call__(self, func, *args, **kwargs): """Shorcut for self.run.""" return self.run(func, *args, **kwargs)
python execute function with locals
def exec_function(ast, globals_map): """Execute a python code object in the given environment. Args: globals_map: Dictionary to use as the globals context. Returns: locals_map: Dictionary of locals from the environment after execution. """ locals_map = globals_map exec ast in global...
def execfile(fname, variables): """ This is builtin in python2, but we have to roll our own on py3. """ with open(fname) as f: code = compile(f.read(), fname, 'exec') exec(code, variables)
python execute function with locals
def exec_function(ast, globals_map): """Execute a python code object in the given environment. Args: globals_map: Dictionary to use as the globals context. Returns: locals_map: Dictionary of locals from the environment after execution. """ locals_map = globals_map exec ast in global...
def getFunction(self): """Called by remote workers. Useful to populate main module globals() for interactive shells. Retrieves the serialized function.""" return functionFactory( self.code, self.name, self.defaults, self.globals, self.i...
close connection python sqlalchemy
def cleanup(self, app): """Close all connections.""" if hasattr(self.database.obj, 'close_all'): self.database.close_all()
def close_database_session(session): """Close connection with the database""" try: session.close() except OperationalError as e: raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0])
close connection python sqlalchemy
def cleanup(self, app): """Close all connections.""" if hasattr(self.database.obj, 'close_all'): self.database.close_all()
def _close(self): """ Closes the client connection to the database. """ if self.connection: with self.wrap_database_errors: self.connection.client.close()
close connection python sqlalchemy
def cleanup(self, app): """Close all connections.""" if hasattr(self.database.obj, 'close_all'): self.database.close_all()
def destroy(self): """ Destroy the SQLStepQueue tables in the database """ with self._db_conn() as conn: for table_name in self._tables: conn.execute('DROP TABLE IF EXISTS %s' % table_name) return self
close connection python sqlalchemy
def cleanup(self, app): """Close all connections.""" if hasattr(self.database.obj, 'close_all'): self.database.close_all()
def unlock(self): """Closes the session to the database.""" if not hasattr(self, 'session'): raise RuntimeError('Error detected! The session that you want to close does not exist any more!') logger.debug("Closed database session of '%s'" % self._database) self.session.close() del self.session
close connection python sqlalchemy
def cleanup(self, app): """Close all connections.""" if hasattr(self.database.obj, 'close_all'): self.database.close_all()
def _executemany(self, cursor, query, parameters): """The function is mostly useful for commands that update the database: any result set returned by the query is discarded.""" try: self._log(query) cursor.executemany(query, parameters) except OperationalError ...
code that deletes any folder if empty python
def remove_examples_all(): """remove arduino/examples/all directory. :rtype: None """ d = examples_all_dir() if d.exists(): log.debug('remove %s', d) d.rmtree() else: log.debug('nothing to remove: %s', d)
def delete(build_folder): """Delete build directory and all its contents. """ if _meta_.del_build in ["on", "ON"] and os.path.exists(build_folder): shutil.rmtree(build_folder)
code that deletes any folder if empty python
def remove_examples_all(): """remove arduino/examples/all directory. :rtype: None """ d = examples_all_dir() if d.exists(): log.debug('remove %s', d) d.rmtree() else: log.debug('nothing to remove: %s', d)
def clean_out_dir(directory): """ Delete all the files and subdirectories in a directory. """ if not isinstance(directory, path): directory = path(directory) for file_path in directory.files(): file_path.remove() for dir_path in directory.dirs(): dir_path.rmtree()
code that deletes any folder if empty python
def remove_examples_all(): """remove arduino/examples/all directory. :rtype: None """ d = examples_all_dir() if d.exists(): log.debug('remove %s', d) d.rmtree() else: log.debug('nothing to remove: %s', d)
def _clear_dir(dirName): """ Remove a directory and it contents. Ignore any failures. """ # If we got here, clear dir for fname in os.listdir(dirName): try: os.remove( os.path.join(dirName, fname) ) except Exception: pass try: os.rmdir(dirName) e...
code that deletes any folder if empty python
def remove_examples_all(): """remove arduino/examples/all directory. :rtype: None """ d = examples_all_dir() if d.exists(): log.debug('remove %s', d) d.rmtree() else: log.debug('nothing to remove: %s', d)
def remover(file_path): """Delete a file or directory path only if it exists.""" if os.path.isfile(file_path): os.remove(file_path) return True elif os.path.isdir(file_path): shutil.rmtree(file_path) return True else: return False
code that deletes any folder if empty python
def remove_examples_all(): """remove arduino/examples/all directory. :rtype: None """ d = examples_all_dir() if d.exists(): log.debug('remove %s', d) d.rmtree() else: log.debug('nothing to remove: %s', d)
def safe_rmtree(directory): """Delete a directory if it's present. If it's not present, no-op.""" if os.path.exists(directory): shutil.rmtree(directory, True)
python file chooser restrict file types
def guess_file_type(kind, filepath=None, youtube_id=None, web_url=None, encoding=None): """ guess_file_class: determines what file the content is Args: filepath (str): filepath of file to check Returns: string indicating file's class """ if youtube_id: return FileTypes.YO...
def from_file(filename, mime=False): """" Accepts a filename and returns the detected filetype. Return value is the mimetype if mime=True, otherwise a human readable name. >>> magic.from_file("testdata/test.pdf", mime=True) 'application/pdf' """ m = _get_magic_type(mime) return m.f...
python file chooser restrict file types
def guess_file_type(kind, filepath=None, youtube_id=None, web_url=None, encoding=None): """ guess_file_class: determines what file the content is Args: filepath (str): filepath of file to check Returns: string indicating file's class """ if youtube_id: return FileTypes.YO...
def from_file(filename, mime=False): """ Opens file, attempts to identify content based off magic number and will return the file extension. If mime is True it will return the mime type instead. :param filename: path to file :param mime: Return mime, not extension :return: guessed extension or ...
python file chooser restrict file types
def guess_file_type(kind, filepath=None, youtube_id=None, web_url=None, encoding=None): """ guess_file_class: determines what file the content is Args: filepath (str): filepath of file to check Returns: string indicating file's class """ if youtube_id: return FileTypes.YO...
def glob_by_extensions(directory, extensions): """ Returns files matched by all extensions in the extensions list """ directorycheck(directory) files = [] xt = files.extend for ex in extensions: xt(glob.glob('{0}/*.{1}'.format(directory, ex))) return files
python file chooser restrict file types
def guess_file_type(kind, filepath=None, youtube_id=None, web_url=None, encoding=None): """ guess_file_class: determines what file the content is Args: filepath (str): filepath of file to check Returns: string indicating file's class """ if youtube_id: return FileTypes.YO...
def get_filetype_icon(fname): """Return file type icon""" ext = osp.splitext(fname)[1] if ext.startswith('.'): ext = ext[1:] return get_icon( "%s.png" % ext, ima.icon('FileIcon') )
python file chooser restrict file types
def guess_file_type(kind, filepath=None, youtube_id=None, web_url=None, encoding=None): """ guess_file_class: determines what file the content is Args: filepath (str): filepath of file to check Returns: string indicating file's class """ if youtube_id: return FileTypes.YO...
def _file_type(self, field): """ Returns file type for given file field. Args: field (str): File field Returns: string. File type """ type = mimetypes.guess_type(self._files[field])[0] return type.encode("utf-8") if isinstance(type, unico...
python file size determination
def get_file_size(filename): """ Get the file size of a given file :param filename: string: pathname of a file :return: human readable filesize """ if os.path.isfile(filename): return convert_size(os.path.getsize(filename)) return None
def get_file_size(fileobj): """ Returns the size of a file-like object. """ currpos = fileobj.tell() fileobj.seek(0, 2) total_size = fileobj.tell() fileobj.seek(currpos) return total_size
python file size determination
def get_file_size(filename): """ Get the file size of a given file :param filename: string: pathname of a file :return: human readable filesize """ if os.path.isfile(filename): return convert_size(os.path.getsize(filename)) return None
def get_size(path): """ Returns the size in bytes if `path` is a file, or the size of all files in `path` if it's a directory. Analogous to `du -s`. """ if os.path.isfile(path): return os.path.getsize(path) return sum(get_size(os.path.join(path, f)) for f in os.listdir(path))
python file size determination
def get_file_size(filename): """ Get the file size of a given file :param filename: string: pathname of a file :return: human readable filesize """ if os.path.isfile(filename): return convert_size(os.path.getsize(filename)) return None
def get_size_in_bytes(self, handle): """Return the size in bytes.""" fpath = self._fpath_from_handle(handle) return os.stat(fpath).st_size
python file size determination
def get_file_size(filename): """ Get the file size of a given file :param filename: string: pathname of a file :return: human readable filesize """ if os.path.isfile(filename): return convert_size(os.path.getsize(filename)) return None
def get_filesize(self, pdf): """Compute the filesize of the PDF """ try: filesize = float(pdf.get_size()) return filesize / 1024 except (POSKeyError, TypeError): return 0
python file size determination
def get_file_size(filename): """ Get the file size of a given file :param filename: string: pathname of a file :return: human readable filesize """ if os.path.isfile(filename): return convert_size(os.path.getsize(filename)) return None
def check_max_filesize(chosen_file, max_size): """ Checks file sizes for host """ if os.path.getsize(chosen_file) > max_size: return False else: return True
python fillna inplace not working
def _maybe_fill(arr, fill_value=np.nan): """ if we have a compatible fill_value and arr dtype, then fill """ if _isna_compat(arr, fill_value): arr.fill(fill_value) return arr
def fillna(series_or_arr, missing_value=0.0): """Fill missing values in pandas objects and numpy arrays. Arguments --------- series_or_arr : pandas.Series, numpy.ndarray The numpy array or pandas series for which the missing values need to be replaced. missing_value : float, int, st...
python fillna inplace not working
def _maybe_fill(arr, fill_value=np.nan): """ if we have a compatible fill_value and arr dtype, then fill """ if _isna_compat(arr, fill_value): arr.fill(fill_value) return arr
def _replace_nan(a, val): """ replace nan in a by val, and returns the replaced array and the nan position """ mask = isnull(a) return where_method(val, mask, a), mask
python fillna inplace not working
def _maybe_fill(arr, fill_value=np.nan): """ if we have a compatible fill_value and arr dtype, then fill """ if _isna_compat(arr, fill_value): arr.fill(fill_value) return arr
def clean_dataframe(df): """Fill NaNs with the previous value, the next value or if all are NaN then 1.0""" df = df.fillna(method='ffill') df = df.fillna(0.0) return df
python fillna inplace not working
def _maybe_fill(arr, fill_value=np.nan): """ if we have a compatible fill_value and arr dtype, then fill """ if _isna_compat(arr, fill_value): arr.fill(fill_value) return arr
def inpaint(self): """ Replace masked-out elements in an array using an iterative image inpainting algorithm. """ import inpaint filled = inpaint.replace_nans(np.ma.filled(self.raster_data, np.NAN).astype(np.float32), 3, 0.01, 2) self.raster_data = np.ma.masked_invalid(filled)
python fillna inplace not working
def _maybe_fill(arr, fill_value=np.nan): """ if we have a compatible fill_value and arr dtype, then fill """ if _isna_compat(arr, fill_value): arr.fill(fill_value) return arr
def fill_nulls(self, col: str): """ Fill all null values with NaN values in a column. Null values are ``None`` or en empty string :param col: column name :type col: str :example: ``ds.fill_nulls("mycol")`` """ n = [None, ""] try: self...
compute distance from longitude and latitude python
def _calculate_distance(latlon1, latlon2): """Calculates the distance between two points on earth. """ lat1, lon1 = latlon1 lat2, lon2 = latlon2 dlon = lon2 - lon1 dlat = lat2 - lat1 R = 6371 # radius of the earth in kilometers a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np...
def Distance(lat1, lon1, lat2, lon2): """Get distance between pairs of lat-lon points""" az12, az21, dist = wgs84_geod.inv(lon1, lat1, lon2, lat2) return az21, dist
compute distance from longitude and latitude python
def _calculate_distance(latlon1, latlon2): """Calculates the distance between two points on earth. """ lat1, lon1 = latlon1 lat2, lon2 = latlon2 dlon = lon2 - lon1 dlat = lat2 - lat1 R = 6371 # radius of the earth in kilometers a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np...
def _convert_latitude(self, latitude): """Convert from latitude to the y position in overall map.""" return int((180 - (180 / pi * log(tan( pi / 4 + latitude * pi / 360)))) * (2 ** self._zoom) * self._size / 360)
compute distance from longitude and latitude python
def _calculate_distance(latlon1, latlon2): """Calculates the distance between two points on earth. """ lat1, lon1 = latlon1 lat2, lon2 = latlon2 dlon = lon2 - lon1 dlat = lat2 - lat1 R = 6371 # radius of the earth in kilometers a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np...
def metres2latlon(mx, my, origin_shift= 2 * pi * 6378137 / 2.0): """Converts XY point from Spherical Mercator EPSG:900913 to lat/lon in WGS84 Datum""" lon = (mx / origin_shift) * 180.0 lat = (my / origin_shift) * 180.0 lat = 180 / pi * (2 * atan( exp( lat * pi / 180.0)) - pi / 2.0) return lat, ...
compute distance from longitude and latitude python
def _calculate_distance(latlon1, latlon2): """Calculates the distance between two points on earth. """ lat1, lon1 = latlon1 lat2, lon2 = latlon2 dlon = lon2 - lon1 dlat = lat2 - lat1 R = 6371 # radius of the earth in kilometers a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np...
def unproject(self, xy): """ Returns the coordinates from position in meters """ (x, y) = xy lng = x/EARTH_RADIUS * RAD_TO_DEG lat = 2 * atan(exp(y/EARTH_RADIUS)) - pi/2 * RAD_TO_DEG return (lng, lat)
compute distance from longitude and latitude python
def _calculate_distance(latlon1, latlon2): """Calculates the distance between two points on earth. """ lat1, lon1 = latlon1 lat2, lon2 = latlon2 dlon = lon2 - lon1 dlat = lat2 - lat1 R = 6371 # radius of the earth in kilometers a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np...
def xyz2lonlat(x, y, z): """Convert cartesian to lon lat.""" lon = xu.rad2deg(xu.arctan2(y, x)) lat = xu.rad2deg(xu.arctan2(z, xu.sqrt(x**2 + y**2))) return lon, lat
python finding the smallest and largetst valuse in a list
def find_lt(a, x): """Find rightmost value less than x.""" i = bs.bisect_left(a, x) if i: return i - 1 raise ValueError
def nlargest(self, n=None): """List the n most common elements and their counts. List is from the most common to the least. If n is None, the list all element counts. Run time should be O(m log m) where m is len(self) Args: n (int): The number of elements to return """ if n is None: return sorted...
python finding the smallest and largetst valuse in a list
def find_lt(a, x): """Find rightmost value less than x.""" i = bs.bisect_left(a, x) if i: return i - 1 raise ValueError
def closest_values(L): """Closest values :param L: list of values :returns: two values from L with minimal distance :modifies: the order of L :complexity: O(n log n), for n=len(L) """ assert len(L) >= 2 L.sort() valmin, argmin = min((L[i] - L[i - 1], i) for i in range(1, len(L))) ...
python finding the smallest and largetst valuse in a list
def find_lt(a, x): """Find rightmost value less than x.""" i = bs.bisect_left(a, x) if i: return i - 1 raise ValueError
def find_le(a, x): """Find rightmost value less than or equal to x.""" i = bs.bisect_right(a, x) if i: return i - 1 raise ValueError
python finding the smallest and largetst valuse in a list
def find_lt(a, x): """Find rightmost value less than x.""" i = bs.bisect_left(a, x) if i: return i - 1 raise ValueError
def mostCommonItem(lst): """Choose the most common item from the list, or the first item if all items are unique.""" # This elegant solution from: http://stackoverflow.com/a/1518632/1760218 lst = [l for l in lst if l] if lst: return max(set(lst), key=lst.count) else: return None
python finding the smallest and largetst valuse in a list
def find_lt(a, x): """Find rightmost value less than x.""" i = bs.bisect_left(a, x) if i: return i - 1 raise ValueError
def find_lt(a, x): """Find rightmost value less than x""" i = bisect.bisect_left(a, x) if i: return a[i-1] raise ValueError
python fit to exponential function
def exp_fit_fun(x, a, tau, c): """Function used to fit the exponential decay.""" # pylint: disable=invalid-name return a * np.exp(-x / tau) + c
def algo_exp(x, m, t, b): """mono-exponential curve.""" return m*np.exp(-t*x)+b
python fit to exponential function
def exp_fit_fun(x, a, tau, c): """Function used to fit the exponential decay.""" # pylint: disable=invalid-name return a * np.exp(-x / tau) + c
def fit_gaussian(x, y, yerr, p0): """ Fit a Gaussian to the data """ try: popt, pcov = curve_fit(gaussian, x, y, sigma=yerr, p0=p0, absolute_sigma=True) except RuntimeError: return [0],[0] return popt, pcov
python fit to exponential function
def exp_fit_fun(x, a, tau, c): """Function used to fit the exponential decay.""" # pylint: disable=invalid-name return a * np.exp(-x / tau) + c
def apply_fit(xy,coeffs): """ Apply the coefficients from a linear fit to an array of x,y positions. The coeffs come from the 'coeffs' member of the 'fit_arrays()' output. """ x_new = coeffs[0][2] + coeffs[0][0]*xy[:,0] + coeffs[0][1]*xy[:,1] y_new = coeffs[1][2] + coeffs[1][0]*...
python fit to exponential function
def exp_fit_fun(x, a, tau, c): """Function used to fit the exponential decay.""" # pylint: disable=invalid-name return a * np.exp(-x / tau) + c
def eval(e, amplitude, e_0, alpha, beta): """One dimenional log parabola model function""" ee = e / e_0 eeponent = -alpha - beta * np.log(ee) return amplitude * ee ** eeponent
python fit to exponential function
def exp_fit_fun(x, a, tau, c): """Function used to fit the exponential decay.""" # pylint: disable=invalid-name return a * np.exp(-x / tau) + c
def Exponential(x, a, tau, y0): """Exponential function Inputs: ------- ``x``: independent variable ``a``: scaling factor ``tau``: time constant ``y0``: additive constant Formula: -------- ``a*exp(x/tau)+y0`` """ return np.exp(x / tau) * a + y0
python flask template extend with context
def render_template_string(source, **context): """Renders a template from the given template source string with the given context. :param source: the sourcecode of the template to be rendered :param context: the variables that should be available in the context of...
def render_template(content, context): """ renders context aware template """ rendered = Template(content).render(Context(context)) return rendered
python flask template extend with context
def render_template_string(source, **context): """Renders a template from the given template source string with the given context. :param source: the sourcecode of the template to be rendered :param context: the variables that should be available in the context of...
def render_template(self, source, **kwargs_context): r"""Render a template string using sandboxed environment. :param source: A string containing the page source. :param \*\*kwargs_context: The context associated with the page. :returns: The rendered template. """ return...
python flask template extend with context
def render_template_string(source, **context): """Renders a template from the given template source string with the given context. :param source: the sourcecode of the template to be rendered :param context: the variables that should be available in the context of...
def tree_render(request, upy_context, vars_dictionary): """ It renders template defined in upy_context's page passed in arguments """ page = upy_context['PAGE'] return render_to_response(page.template.file_name, vars_dictionary, context_instance=RequestContext(request))
python flask template extend with context
def render_template_string(source, **context): """Renders a template from the given template source string with the given context. :param source: the sourcecode of the template to be rendered :param context: the variables that should be available in the context of...
def render_template(template_name, **context): """Render a template into a response.""" tmpl = jinja_env.get_template(template_name) context["url_for"] = url_for return Response(tmpl.render(context), mimetype="text/html")
python flask template extend with context
def render_template_string(source, **context): """Renders a template from the given template source string with the given context. :param source: the sourcecode of the template to be rendered :param context: the variables that should be available in the context of...
def render_template(env, filename, values=None): """ Render a jinja template """ if not values: values = {} tmpl = env.get_template(filename) return tmpl.render(values)
python float precision rounding
def round_to_float(number, precision): """Round a float to a precision""" rounded = Decimal(str(floor((number + precision / 2) // precision)) ) * Decimal(str(precision)) return float(rounded)
def _saferound(value, decimal_places): """ Rounds a float value off to the desired precision """ try: f = float(value) except ValueError: return '' format = '%%.%df' % decimal_places return format % f
python float precision rounding
def round_to_float(number, precision): """Round a float to a precision""" rounded = Decimal(str(floor((number + precision / 2) // precision)) ) * Decimal(str(precision)) return float(rounded)
def intround(value): """Given a float returns a rounded int. Should give the same result on both Py2/3 """ return int(decimal.Decimal.from_float( value).to_integral_value(decimal.ROUND_HALF_EVEN))
python float precision rounding
def round_to_float(number, precision): """Round a float to a precision""" rounded = Decimal(str(floor((number + precision / 2) // precision)) ) * Decimal(str(precision)) return float(rounded)
def round_float(f, digits, rounding=ROUND_HALF_UP): """ Accurate float rounding from http://stackoverflow.com/a/15398691. """ return Decimal(str(f)).quantize(Decimal(10) ** (-1 * digits), rounding=rounding)
python float precision rounding
def round_to_float(number, precision): """Round a float to a precision""" rounded = Decimal(str(floor((number + precision / 2) // precision)) ) * Decimal(str(precision)) return float(rounded)
def ceil_nearest(x, dx=1): """ ceil a number to within a given rounding accuracy """ precision = get_sig_digits(dx) return round(math.ceil(float(x) / dx) * dx, precision)
python float precision rounding
def round_to_float(number, precision): """Round a float to a precision""" rounded = Decimal(str(floor((number + precision / 2) // precision)) ) * Decimal(str(precision)) return float(rounded)
def py3round(number): """Unified rounding in all python versions.""" if abs(round(number) - number) == 0.5: return int(2.0 * round(number / 2.0)) return int(round(number))
count number of overlaps in two python lists
def _calc_overlap_count( markers1: dict, markers2: dict, ): """Calculate overlap count between the values of two dictionaries Note: dict values must be sets """ overlaps=np.zeros((len(markers1), len(markers2))) j=0 for marker_group in markers1: tmp = [len(markers2[i].intersecti...
def has_overlaps(self): """ :returns: True if one or more range in the list overlaps with another :rtype: bool """ sorted_list = sorted(self) for i in range(0, len(sorted_list) - 1): if sorted_list[i].overlaps(sorted_list[i + 1]): return True ...
count number of overlaps in two python lists
def _calc_overlap_count( markers1: dict, markers2: dict, ): """Calculate overlap count between the values of two dictionaries Note: dict values must be sets """ overlaps=np.zeros((len(markers1), len(markers2))) j=0 for marker_group in markers1: tmp = [len(markers2[i].intersecti...
def __matches(s1, s2, ngrams_fn, n=3): """ Returns the n-grams that match between two sequences See also: SequenceMatcher.get_matching_blocks Args: s1: a string s2: another string n: an int for the n in n-gram Returns: set: """ ...
count number of overlaps in two python lists
def _calc_overlap_count( markers1: dict, markers2: dict, ): """Calculate overlap count between the values of two dictionaries Note: dict values must be sets """ overlaps=np.zeros((len(markers1), len(markers2))) j=0 for marker_group in markers1: tmp = [len(markers2[i].intersecti...
def __similarity(s1, s2, ngrams_fn, n=3): """ The fraction of n-grams matching between two sequences Args: s1: a string s2: another string n: an int for the n in n-gram Returns: float: the fraction of n-grams matching """ ngrams1, ngr...
count number of overlaps in two python lists
def _calc_overlap_count( markers1: dict, markers2: dict, ): """Calculate overlap count between the values of two dictionaries Note: dict values must be sets """ overlaps=np.zeros((len(markers1), len(markers2))) j=0 for marker_group in markers1: tmp = [len(markers2[i].intersecti...
def search_overlap(self, point_list): """ Returns all intervals that overlap the point_list. """ result = set() for j in point_list: self.search_point(j, result) return result
count number of overlaps in two python lists
def _calc_overlap_count( markers1: dict, markers2: dict, ): """Calculate overlap count between the values of two dictionaries Note: dict values must be sets """ overlaps=np.zeros((len(markers1), len(markers2))) j=0 for marker_group in markers1: tmp = [len(markers2[i].intersecti...
def get_common_elements(list1, list2): """find the common elements in two lists. used to support auto align might be faster with sets Parameters ---------- list1 : list a list of objects list2 : list a list of objects Returns ------- list : list list of...
python foreign key to a foreign key
def __set__(self, instance, value): """ Set a related object for an instance. """ self.map[id(instance)] = (weakref.ref(instance), value)
def reverse_mapping(mapping): """ For every key, value pair, return the mapping for the equivalent value, key pair >>> reverse_mapping({'a': 'b'}) == {'b': 'a'} True """ keys, values = zip(*mapping.items()) return dict(zip(values, keys))
python foreign key to a foreign key
def __set__(self, instance, value): """ Set a related object for an instance. """ self.map[id(instance)] = (weakref.ref(instance), value)
def replace_keys(record: Mapping, key_map: Mapping) -> dict: """New record with renamed keys including keys only found in key_map.""" return {key_map[k]: v for k, v in record.items() if k in key_map}
python foreign key to a foreign key
def __set__(self, instance, value): """ Set a related object for an instance. """ self.map[id(instance)] = (weakref.ref(instance), value)
def set_pivot_keys(self, foreign_key, other_key): """ Set the key names for the pivot model instance """ self.__foreign_key = foreign_key self.__other_key = other_key return self
python foreign key to a foreign key
def __set__(self, instance, value): """ Set a related object for an instance. """ self.map[id(instance)] = (weakref.ref(instance), value)
def set_primary_key(self, table, column): """Create a Primary Key constraint on a specific column when the table is already created.""" self.execute('ALTER TABLE {0} ADD PRIMARY KEY ({1})'.format(wrap(table), column)) self._printer('\tAdded primary key to {0} on column {1}'.format(wrap(table), c...
python foreign key to a foreign key
def __set__(self, instance, value): """ Set a related object for an instance. """ self.map[id(instance)] = (weakref.ref(instance), value)
def get_from_human_key(self, key): """Return the key (aka database value) of a human key (aka Python identifier).""" if key in self._identifier_map: return self._identifier_map[key] raise KeyError(key)
create an array in python without numpy
def recarray(self): """Returns data as :class:`numpy.recarray`.""" return numpy.rec.fromrecords(self.records, names=self.names)
def A(*a): """convert iterable object into numpy array""" return np.array(a[0]) if len(a)==1 else [np.array(o) for o in a]
create an array in python without numpy
def recarray(self): """Returns data as :class:`numpy.recarray`.""" return numpy.rec.fromrecords(self.records, names=self.names)
def _create_empty_array(self, frames, always_2d, dtype): """Create an empty array with appropriate shape.""" import numpy as np if always_2d or self.channels > 1: shape = frames, self.channels else: shape = frames, return np.empty(shape, dtype, order='C')
create an array in python without numpy
def recarray(self): """Returns data as :class:`numpy.recarray`.""" return numpy.rec.fromrecords(self.records, names=self.names)
def to_0d_array(value: Any) -> np.ndarray: """Given a value, wrap it in a 0-D numpy.ndarray. """ if np.isscalar(value) or (isinstance(value, np.ndarray) and value.ndim == 0): return np.array(value) else: return to_0d_object_array(value)
create an array in python without numpy
def recarray(self): """Returns data as :class:`numpy.recarray`.""" return numpy.rec.fromrecords(self.records, names=self.names)
def _parse_array(self, tensor_proto): """Grab data in TensorProto and convert to numpy array.""" try: from onnx.numpy_helper import to_array except ImportError as e: raise ImportError("Unable to import onnx which is required {}".format(e)) np_array = to_array(tens...
create an array in python without numpy
def recarray(self): """Returns data as :class:`numpy.recarray`.""" return numpy.rec.fromrecords(self.records, names=self.names)
def torecarray(*args, **kwargs): """ Convenient shorthand for ``toarray(*args, **kwargs).view(np.recarray)``. """ import numpy as np return toarray(*args, **kwargs).view(np.recarray)
create polygon from lists of points python
def from_points(cls, list_of_lists): """ Creates a *Polygon* instance out of a list of lists, each sublist being populated with `pyowm.utils.geo.Point` instances :param list_of_lists: list :type: list_of_lists: iterable_of_polygons :returns: a *Polygon* instance ...
def polygon_from_points(points): """ Constructs a numpy-compatible polygon from a page representation. """ polygon = [] for pair in points.split(" "): x_y = pair.split(",") polygon.append([float(x_y[0]), float(x_y[1])]) return polygon
create polygon from lists of points python
def from_points(cls, list_of_lists): """ Creates a *Polygon* instance out of a list of lists, each sublist being populated with `pyowm.utils.geo.Point` instances :param list_of_lists: list :type: list_of_lists: iterable_of_polygons :returns: a *Polygon* instance ...
def polyline(*points): """Converts a list of points to a Path composed of lines connecting those points (i.e. a linear spline or polyline). See also `polygon()`.""" return Path(*[Line(points[i], points[i+1]) for i in range(len(points) - 1)])
create polygon from lists of points python
def from_points(cls, list_of_lists): """ Creates a *Polygon* instance out of a list of lists, each sublist being populated with `pyowm.utils.geo.Point` instances :param list_of_lists: list :type: list_of_lists: iterable_of_polygons :returns: a *Polygon* instance ...
def point_in_multipolygon(point, multipoly): """ valid whether the point is located in a mulitpolygon (donut polygon is not supported) Keyword arguments: point -- point geojson object multipoly -- multipolygon geojson object if(point inside multipoly) return true else false """ c...
create polygon from lists of points python
def from_points(cls, list_of_lists): """ Creates a *Polygon* instance out of a list of lists, each sublist being populated with `pyowm.utils.geo.Point` instances :param list_of_lists: list :type: list_of_lists: iterable_of_polygons :returns: a *Polygon* instance ...
def bounds_to_poly(bounds): """ Constructs a shapely Polygon from the provided bounds tuple. Parameters ---------- bounds: tuple Tuple representing the (left, bottom, right, top) coordinates Returns ------- polygon: shapely.geometry.Polygon Shapely Polygon geometry of t...
create polygon from lists of points python
def from_points(cls, list_of_lists): """ Creates a *Polygon* instance out of a list of lists, each sublist being populated with `pyowm.utils.geo.Point` instances :param list_of_lists: list :type: list_of_lists: iterable_of_polygons :returns: a *Polygon* instance ...
def is_in(self, point_x, point_y): """ Test if a point is within this polygonal region """ point_array = array(((point_x, point_y),)) vertices = array(self.points) winding = self.inside_rule == "winding" result = points_in_polygon(point_array, vertices, winding) return r...
cumulative sum of list python
def cumsum(inlist): """ Returns a list consisting of the cumulative sum of the items in the passed list. Usage: lcumsum(inlist) """ newlist = copy.deepcopy(inlist) for i in range(1, len(newlist)): newlist[i] = newlist[i] + newlist[i - 1] return newlist
def lcumsum (inlist): """ Returns a list consisting of the cumulative sum of the items in the passed list. Usage: lcumsum(inlist) """ newlist = copy.deepcopy(inlist) for i in range(1,len(newlist)): newlist[i] = newlist[i] + newlist[i-1] return newlist
cumulative sum of list python
def cumsum(inlist): """ Returns a list consisting of the cumulative sum of the items in the passed list. Usage: lcumsum(inlist) """ newlist = copy.deepcopy(inlist) for i in range(1, len(newlist)): newlist[i] = newlist[i] + newlist[i - 1] return newlist
def _cumprod(l): """Cumulative product of a list. Args: l: a list of integers Returns: a list with one more element (starting with 1) """ ret = [1] for item in l: ret.append(ret[-1] * item) return ret
cumulative sum of list python
def cumsum(inlist): """ Returns a list consisting of the cumulative sum of the items in the passed list. Usage: lcumsum(inlist) """ newlist = copy.deepcopy(inlist) for i in range(1, len(newlist)): newlist[i] = newlist[i] + newlist[i - 1] return newlist
def average(iterator): """Iterative mean.""" count = 0 total = 0 for num in iterator: count += 1 total += num return float(total)/count
cumulative sum of list python
def cumsum(inlist): """ Returns a list consisting of the cumulative sum of the items in the passed list. Usage: lcumsum(inlist) """ newlist = copy.deepcopy(inlist) for i in range(1, len(newlist)): newlist[i] = newlist[i] + newlist[i - 1] return newlist
def moving_average(iterable, n): """ From Python collections module documentation moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0 """ it = iter(iterable) d = collections.deque(itertools.islice(it, n - 1)) d.appendleft(0) s = sum(d) for elem in it: s += elem ...
cumulative sum of list python
def cumsum(inlist): """ Returns a list consisting of the cumulative sum of the items in the passed list. Usage: lcumsum(inlist) """ newlist = copy.deepcopy(inlist) for i in range(1, len(newlist)): newlist[i] = newlist[i] + newlist[i - 1] return newlist
def _accumulate(sequence, func): """ Python2 accumulate implementation taken from https://docs.python.org/3/library/itertools.html#itertools.accumulate """ iterator = iter(sequence) total = next(iterator) yield total for element in iterator: total = func(total, element) y...
cursor position graphics python
def ensure_hbounds(self): """Ensure the cursor is within horizontal screen bounds.""" self.cursor.x = min(max(0, self.cursor.x), self.columns - 1)
def set_cursor(self, x, y): """ Sets the cursor to the desired position. :param x: X position :param y: Y position """ curses.curs_set(1) self.screen.move(y, x)
cursor position graphics python
def ensure_hbounds(self): """Ensure the cursor is within horizontal screen bounds.""" self.cursor.x = min(max(0, self.cursor.x), self.columns - 1)
def get_cursor(self): """Return the virtual cursor position. The cursor can be moved with the :any:`move` method. Returns: Tuple[int, int]: The (x, y) coordinate of where :any:`print_str` will continue from. .. seealso:: :any:move` """ x, y ...
cursor position graphics python
def ensure_hbounds(self): """Ensure the cursor is within horizontal screen bounds.""" self.cursor.x = min(max(0, self.cursor.x), self.columns - 1)
def set_cursor_position(self, position): """Set cursor position""" position = self.get_position(position) cursor = self.textCursor() cursor.setPosition(position) self.setTextCursor(cursor) self.ensureCursorVisible()
cursor position graphics python
def ensure_hbounds(self): """Ensure the cursor is within horizontal screen bounds.""" self.cursor.x = min(max(0, self.cursor.x), self.columns - 1)
def home(self): """Set cursor to initial position and reset any shifting.""" self.command(c.LCD_RETURNHOME) self._cursor_pos = (0, 0) c.msleep(2)
cursor position graphics python
def ensure_hbounds(self): """Ensure the cursor is within horizontal screen bounds.""" self.cursor.x = min(max(0, self.cursor.x), self.columns - 1)
def move(self, x, y): """Move the virtual cursor. Args: x (int): x-coordinate to place the cursor. y (int): y-coordinate to place the cursor. .. seealso:: :any:`get_cursor`, :any:`print_str`, :any:`write` """ self._cursor = self._normalizePoint(x, y)
define an empty column in a data frame in python
def add_blank_row(self, label): """ Add a blank row with only an index value to self.df. This is done inplace. """ col_labels = self.df.columns blank_item = pd.Series({}, index=col_labels, name=label) # use .loc to add in place (append won't do that) self....
def fill_nulls(self, col: str): """ Fill all null values with NaN values in a column. Null values are ``None`` or en empty string :param col: column name :type col: str :example: ``ds.fill_nulls("mycol")`` """ n = [None, ""] try: self...
define an empty column in a data frame in python
def add_blank_row(self, label): """ Add a blank row with only an index value to self.df. This is done inplace. """ col_labels = self.df.columns blank_item = pd.Series({}, index=col_labels, name=label) # use .loc to add in place (append won't do that) self....
def stringify_col(df, col_name): """ Take a dataframe and string-i-fy a column of values. Turn nan/None into "" and all other values into strings. Parameters ---------- df : dataframe col_name : string """ df = df.copy() df[col_name] = df[col_name].fillna("") df[col_name] = ...
define an empty column in a data frame in python
def add_blank_row(self, label): """ Add a blank row with only an index value to self.df. This is done inplace. """ col_labels = self.df.columns blank_item = pd.Series({}, index=col_labels, name=label) # use .loc to add in place (append won't do that) self....
def fillna(series_or_arr, missing_value=0.0): """Fill missing values in pandas objects and numpy arrays. Arguments --------- series_or_arr : pandas.Series, numpy.ndarray The numpy array or pandas series for which the missing values need to be replaced. missing_value : float, int, st...
define an empty column in a data frame in python
def add_blank_row(self, label): """ Add a blank row with only an index value to self.df. This is done inplace. """ col_labels = self.df.columns blank_item = pd.Series({}, index=col_labels, name=label) # use .loc to add in place (append won't do that) self....
def clean_df(df, fill_nan=True, drop_empty_columns=True): """Clean a pandas dataframe by: 1. Filling empty values with Nan 2. Dropping columns with all empty values Args: df: Pandas DataFrame fill_nan (bool): If any empty values (strings, None, etc) should be replaced with NaN ...
define an empty column in a data frame in python
def add_blank_row(self, label): """ Add a blank row with only an index value to self.df. This is done inplace. """ col_labels = self.df.columns blank_item = pd.Series({}, index=col_labels, name=label) # use .loc to add in place (append won't do that) self....
def clean_dataframe(df): """Fill NaNs with the previous value, the next value or if all are NaN then 1.0""" df = df.fillna(method='ffill') df = df.fillna(0.0) return df
delete commas from a string python
def _split_comma_separated(string): """Return a set of strings.""" return set(text.strip() for text in string.split(',') if text.strip())
def unpunctuate(s, *, char_blacklist=string.punctuation): """ Remove punctuation from string s. """ # remove punctuation s = "".join(c for c in s if c not in char_blacklist) # remove consecutive spaces return " ".join(filter(None, s.split(" ")))
delete commas from a string python
def _split_comma_separated(string): """Return a set of strings.""" return set(text.strip() for text in string.split(',') if text.strip())
def unapostrophe(text): """Strip apostrophe and 's' from the end of a string.""" text = re.sub(r'[%s]s?$' % ''.join(APOSTROPHES), '', text) return text
delete commas from a string python
def _split_comma_separated(string): """Return a set of strings.""" return set(text.strip() for text in string.split(',') if text.strip())
def remove_punctuation(text, exceptions=[]): """ Return a string with punctuation removed. Parameters: text (str): The text to remove punctuation from. exceptions (list): List of symbols to keep in the given text. Return: str: The input text without the punctuation. """ ...
delete commas from a string python
def _split_comma_separated(string): """Return a set of strings.""" return set(text.strip() for text in string.split(',') if text.strip())
def strip_spaces(value, sep=None, join=True): """Cleans trailing whitespaces and replaces also multiple whitespaces with a single space.""" value = value.strip() value = [v.strip() for v in value.split(sep)] join_sep = sep or ' ' return join_sep.join(value) if join else value
delete commas from a string python
def _split_comma_separated(string): """Return a set of strings.""" return set(text.strip() for text in string.split(',') if text.strip())
def strip_accents(string): """ Strip all the accents from the string """ return u''.join( (character for character in unicodedata.normalize('NFD', string) if unicodedata.category(character) != 'Mn'))