repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
idlesign/torrentool
torrentool/utils.py
get_open_trackers_from_remote
python
def get_open_trackers_from_remote(): url_base = 'https://raw.githubusercontent.com/idlesign/torrentool/master/torrentool/repo' url = '%s/%s' % (url_base, OPEN_TRACKERS_FILENAME) try: import requests response = requests.get(url, timeout=REMOTE_TIMEOUT) response.raise_for_status() ...
Returns open trackers announce URLs list from remote repo.
train
https://github.com/idlesign/torrentool/blob/78c474c2ecddbad2e3287b390ac8a043957f3563/torrentool/utils.py#L64-L83
null
import math from os import path from .exceptions import RemoteUploadError, RemoteDownloadError OPEN_TRACKERS_FILENAME = 'open_trackers.ini' REMOTE_TIMEOUT = 4 def get_app_version(): """Returns full version string including application name suitable for putting into Torrent.created_by. """ from tor...
idlesign/torrentool
torrentool/utils.py
get_open_trackers_from_local
python
def get_open_trackers_from_local(): with open(path.join(path.dirname(__file__), 'repo', OPEN_TRACKERS_FILENAME)) as f: open_trackers = map(str.strip, f.readlines()) return list(open_trackers)
Returns open trackers announce URLs list from local backup.
train
https://github.com/idlesign/torrentool/blob/78c474c2ecddbad2e3287b390ac8a043957f3563/torrentool/utils.py#L86-L91
null
import math from os import path from .exceptions import RemoteUploadError, RemoteDownloadError OPEN_TRACKERS_FILENAME = 'open_trackers.ini' REMOTE_TIMEOUT = 4 def get_app_version(): """Returns full version string including application name suitable for putting into Torrent.created_by. """ from tor...
idlesign/torrentool
torrentool/bencode.py
Bencode.encode
python
def encode(cls, value): val_encoding = 'utf-8' def encode_str(v): try: v_enc = encode(v, val_encoding) except UnicodeDecodeError: if PY3: raise else: # Suppose bytestring ...
Encodes a value into bencoded bytes. :param value: Python object to be encoded (str, int, list, dict). :param str val_encoding: Encoding used by strings in a given object. :rtype: bytes
train
https://github.com/idlesign/torrentool/blob/78c474c2ecddbad2e3287b390ac8a043957f3563/torrentool/bencode.py#L27-L81
[ "def encode_(val):\n if isinstance(val, str_type):\n result = encode_str(val)\n\n elif isinstance(val, int_types):\n result = encode(('i%se' % val), val_encoding)\n\n elif isinstance(val, (list, set, tuple)):\n result = encode('l', val_encoding)\n for item in val:\n r...
class Bencode(object): """Exposes utilities for bencoding.""" @classmethod @classmethod def decode(cls, encoded): """Decodes bencoded data introduced as bytes. Returns decoded structure(s). :param bytes encoded: """ def create_dict(items): # Let's...
idlesign/torrentool
torrentool/bencode.py
Bencode.decode
python
def decode(cls, encoded): def create_dict(items): # Let's guarantee that dictionaries are sorted. k_v_pair = zip(*[iter(items)] * 2) return OrderedDict(sorted(k_v_pair, key=itemgetter(0))) def create_list(items): return list(items) stack_items = ...
Decodes bencoded data introduced as bytes. Returns decoded structure(s). :param bytes encoded:
train
https://github.com/idlesign/torrentool/blob/78c474c2ecddbad2e3287b390ac8a043957f3563/torrentool/bencode.py#L84-L177
[ "def parse_forward(till_char, sequence):\n number = ''\n char_sub_idx = 0\n\n for char_sub_idx, char_sub in enumerate(sequence):\n char_sub = chr_(char_sub)\n if char_sub == till_char:\n break\n\n number += char_sub\n\n number = int(number or 0)\n char_sub_idx += 1\n\n...
class Bencode(object): """Exposes utilities for bencoding.""" @classmethod def encode(cls, value): """Encodes a value into bencoded bytes. :param value: Python object to be encoded (str, int, list, dict). :param str val_encoding: Encoding used by strings in a given object. ...
idlesign/torrentool
torrentool/bencode.py
Bencode.read_string
python
def read_string(cls, string): if PY3 and not isinstance(string, byte_types): string = string.encode() return cls.decode(string)
Decodes a given bencoded string or bytestring. Returns decoded structure(s). :param str string: :rtype: list
train
https://github.com/idlesign/torrentool/blob/78c474c2ecddbad2e3287b390ac8a043957f3563/torrentool/bencode.py#L180-L191
[ "def decode(cls, encoded):\n \"\"\"Decodes bencoded data introduced as bytes.\n\n Returns decoded structure(s).\n\n :param bytes encoded:\n \"\"\"\n def create_dict(items):\n # Let's guarantee that dictionaries are sorted.\n k_v_pair = zip(*[iter(items)] * 2)\n return OrderedDict...
class Bencode(object): """Exposes utilities for bencoding.""" @classmethod def encode(cls, value): """Encodes a value into bencoded bytes. :param value: Python object to be encoded (str, int, list, dict). :param str val_encoding: Encoding used by strings in a given object. ...
idlesign/torrentool
torrentool/bencode.py
Bencode.read_file
python
def read_file(cls, filepath): with open(filepath, mode='rb') as f: contents = f.read() return cls.decode(contents)
Decodes bencoded data of a given file. Returns decoded structure(s). :param str filepath: :rtype: list
train
https://github.com/idlesign/torrentool/blob/78c474c2ecddbad2e3287b390ac8a043957f3563/torrentool/bencode.py#L194-L204
[ "def decode(cls, encoded):\n \"\"\"Decodes bencoded data introduced as bytes.\n\n Returns decoded structure(s).\n\n :param bytes encoded:\n \"\"\"\n def create_dict(items):\n # Let's guarantee that dictionaries are sorted.\n k_v_pair = zip(*[iter(items)] * 2)\n return OrderedDict...
class Bencode(object): """Exposes utilities for bencoding.""" @classmethod def encode(cls, value): """Encodes a value into bencoded bytes. :param value: Python object to be encoded (str, int, list, dict). :param str val_encoding: Encoding used by strings in a given object. ...
perrygeo/python-rasterstats
src/rasterstats/cli.py
zonalstats
python
def zonalstats(features, raster, all_touched, band, categorical, indent, info, nodata, prefix, stats, sequence, use_rs): '''zonalstats generates summary statistics of geospatial raster datasets based on vector features. The input arguments to zonalstats should be valid GeoJSON Features. (see...
zonalstats generates summary statistics of geospatial raster datasets based on vector features. The input arguments to zonalstats should be valid GeoJSON Features. (see cligj) The output GeoJSON will be mostly unchanged but have additional properties per feature describing the summary statistics (min,...
train
https://github.com/perrygeo/python-rasterstats/blob/910455cd7c9c21eadf464927db72b38ef62b7dfb/src/rasterstats/cli.py#L29-L74
[ "def gen_zonal_stats(\n vectors, raster,\n layer=0,\n band=1,\n nodata=None,\n affine=None,\n stats=None,\n all_touched=False,\n categorical=False,\n category_map=None,\n add_stats=None,\n zone_func=None,\n raster_out=False,\n ...
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division import logging import click import cligj import simplejson as json from rasterstats import gen_zonal_stats, gen_point_query from rasterstats._version import __version__ as version SETTINGS = dict(help_option_names=['-h', '...
perrygeo/python-rasterstats
src/rasterstats/cli.py
pointquery
python
def pointquery(features, raster, band, indent, nodata, interpolate, property_name, sequence, use_rs): results = gen_point_query( features, raster, band=band, nodata=nodata, interpolate=interpolate, property_name=property_name, geojson_out=True)...
Queries the raster values at the points of the input GeoJSON Features. The raster values are added to the features properties and output as GeoJSON Feature Collection. If the Features are Points, the point geometery is used. For other Feauture types, all of the verticies of the geometry will be queried...
train
https://github.com/perrygeo/python-rasterstats/blob/910455cd7c9c21eadf464927db72b38ef62b7dfb/src/rasterstats/cli.py#L88-L120
[ "def gen_point_query(\n vectors,\n raster,\n band=1,\n layer=0,\n nodata=None,\n affine=None,\n interpolate='bilinear',\n property_name='value',\n geojson_out=False):\n \"\"\"\n Given a set of vector features and a raster,\n generate raster values at each vertex of the geometry\n...
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division import logging import click import cligj import simplejson as json from rasterstats import gen_zonal_stats, gen_point_query from rasterstats._version import __version__ as version SETTINGS = dict(help_option_names=['-h', '...
perrygeo/python-rasterstats
src/rasterstats/point.py
point_window_unitxy
python
def point_window_unitxy(x, y, affine): fcol, frow = ~affine * (x, y) r, c = int(round(frow)), int(round(fcol)) # The new source window for our 2x2 array new_win = ((r - 1, r + 1), (c - 1, c + 1)) # the new x, y coords on the unit square unitxy = (0.5 - (c - fcol), 0.5 + (r - frow...
Given an x, y and a geotransform Returns - rasterio window representing 2x2 window whose center points encompass point - the cartesian x, y coordinates of the point on the unit square defined by the array center points. ((row1, row2), (col1, col2)), (unitx, unity)
train
https://github.com/perrygeo/python-rasterstats/blob/910455cd7c9c21eadf464927db72b38ef62b7dfb/src/rasterstats/point.py#L10-L29
null
from __future__ import absolute_import from __future__ import division from shapely.geometry import shape from shapely import wkt from numpy.ma import masked from numpy import asscalar from .io import read_features, Raster def bilinear(arr, x, y): """ Given a 2x2 array, an x, and y, treat center points as a unit...
perrygeo/python-rasterstats
src/rasterstats/point.py
bilinear
python
def bilinear(arr, x, y): # for now, only 2x2 arrays assert arr.shape == (2, 2) ulv, urv, llv, lrv = arr[0:2, 0:2].flatten().tolist() # not valid if not on unit square assert 0.0 <= x <= 1.0 assert 0.0 <= y <= 1.0 if hasattr(arr, 'count') and arr.count() != 4: # a masked array with ...
Given a 2x2 array, an x, and y, treat center points as a unit square return the value for the fractional row/col using bilinear interpolation between the cells +---+---+ | A | B | +----+ +---+---+ => | | | C | D | +----+ +---+---+ e.g.: Center of ...
train
https://github.com/perrygeo/python-rasterstats/blob/910455cd7c9c21eadf464927db72b38ef62b7dfb/src/rasterstats/point.py#L32-L66
null
from __future__ import absolute_import from __future__ import division from shapely.geometry import shape from shapely import wkt from numpy.ma import masked from numpy import asscalar from .io import read_features, Raster def point_window_unitxy(x, y, affine): """ Given an x, y and a geotransform Returns ...
perrygeo/python-rasterstats
src/rasterstats/point.py
geom_xys
python
def geom_xys(geom): if geom.has_z: # hack to convert to 2D, https://gist.github.com/ThomasG77/cad711667942826edc70 geom = wkt.loads(geom.to_wkt()) assert not geom.has_z if hasattr(geom, "geoms"): geoms = geom.geoms else: geoms = [geom] for g in geoms: ar...
Given a shapely geometry, generate a flattened series of 2D points as x,y tuples
train
https://github.com/perrygeo/python-rasterstats/blob/910455cd7c9c21eadf464927db72b38ef62b7dfb/src/rasterstats/point.py#L69-L86
null
from __future__ import absolute_import from __future__ import division from shapely.geometry import shape from shapely import wkt from numpy.ma import masked from numpy import asscalar from .io import read_features, Raster def point_window_unitxy(x, y, affine): """ Given an x, y and a geotransform Returns ...
perrygeo/python-rasterstats
src/rasterstats/point.py
gen_point_query
python
def gen_point_query( vectors, raster, band=1, layer=0, nodata=None, affine=None, interpolate='bilinear', property_name='value', geojson_out=False): if interpolate not in ['nearest', 'bilinear']: raise ValueError("interpolate must be nearest or bilinear") features_ite...
Given a set of vector features and a raster, generate raster values at each vertex of the geometry For features with point geometry, the values will be a 1D with the index refering to the feature For features with other geometry types, it effectively creates a 2D list, such that the first inde...
train
https://github.com/perrygeo/python-rasterstats/blob/910455cd7c9c21eadf464927db72b38ef62b7dfb/src/rasterstats/point.py#L100-L197
[ "def bilinear(arr, x, y):\n \"\"\" Given a 2x2 array, an x, and y, treat center points as a unit square\n return the value for the fractional row/col\n using bilinear interpolation between the cells\n\n +---+---+\n | A | B | +----+\n +---+---+ => | |\n | C | D | +...
from __future__ import absolute_import from __future__ import division from shapely.geometry import shape from shapely import wkt from numpy.ma import masked from numpy import asscalar from .io import read_features, Raster def point_window_unitxy(x, y, affine): """ Given an x, y and a geotransform Returns ...
perrygeo/python-rasterstats
src/rasterstats/utils.py
rasterize_geom
python
def rasterize_geom(geom, like, all_touched=False): geoms = [(geom, 1)] rv_array = features.rasterize( geoms, out_shape=like.shape, transform=like.affine, fill=0, dtype='uint8', all_touched=all_touched) return rv_array.astype(bool)
Parameters ---------- geom: GeoJSON geometry like: raster object with desired shape and transform all_touched: rasterization strategy Returns ------- ndarray: boolean
train
https://github.com/perrygeo/python-rasterstats/blob/910455cd7c9c21eadf464927db72b38ef62b7dfb/src/rasterstats/utils.py#L28-L49
null
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division import sys from rasterio import features from shapely.geometry import box, MultiPolygon from .io import window_bounds DEFAULT_STATS = ['count', 'min', 'max', 'mean'] VALID_STATS = DEFAULT_STATS + \ ['sum', 'std', 'media...
perrygeo/python-rasterstats
src/rasterstats/utils.py
key_assoc_val
python
def key_assoc_val(d, func, exclude=None): vs = list(d.values()) ks = list(d.keys()) key = ks[vs.index(func(vs))] return key
return the key associated with the value returned by func
train
https://github.com/perrygeo/python-rasterstats/blob/910455cd7c9c21eadf464927db72b38ef62b7dfb/src/rasterstats/utils.py#L119-L125
null
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division import sys from rasterio import features from shapely.geometry import box, MultiPolygon from .io import window_bounds DEFAULT_STATS = ['count', 'min', 'max', 'mean'] VALID_STATS = DEFAULT_STATS + \ ['sum', 'std', 'media...
perrygeo/python-rasterstats
src/rasterstats/utils.py
boxify_points
python
def boxify_points(geom, rast): if 'Point' not in geom.type: raise ValueError("Points or multipoints only") buff = -0.01 * abs(min(rast.affine.a, rast.affine.e)) if geom.type == 'Point': pts = [geom] elif geom.type == "MultiPoint": pts = geom.geoms geoms = [] for pt in p...
Point and MultiPoint don't play well with GDALRasterize convert them into box polygons 99% cellsize, centered on the raster cell
train
https://github.com/perrygeo/python-rasterstats/blob/910455cd7c9c21eadf464927db72b38ef62b7dfb/src/rasterstats/utils.py#L128-L148
[ "def window_bounds(window, affine):\n (row_start, row_stop), (col_start, col_stop) = window\n w, s = (col_start, row_stop) * affine\n e, n = (col_stop, row_start) * affine\n return w, s, e, n\n" ]
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division import sys from rasterio import features from shapely.geometry import box, MultiPolygon from .io import window_bounds DEFAULT_STATS = ['count', 'min', 'max', 'mean'] VALID_STATS = DEFAULT_STATS + \ ['sum', 'std', 'media...
perrygeo/python-rasterstats
src/rasterstats/io.py
parse_feature
python
def parse_feature(obj): # object implementing geo_interface if hasattr(obj, '__geo_interface__'): gi = obj.__geo_interface__ if gi['type'] in geom_types: return wrap_geom(gi) elif gi['type'] == 'Feature': return gi # wkt try: shape = wkt.loads(ob...
Given a python object attemp to a GeoJSON-like Feature from it
train
https://github.com/perrygeo/python-rasterstats/blob/910455cd7c9c21eadf464927db72b38ef62b7dfb/src/rasterstats/io.py#L43-L79
[ "def wrap_geom(geom):\n \"\"\" Wraps a geometry dict in an GeoJSON Feature\n \"\"\"\n return {'type': 'Feature',\n 'properties': {},\n 'geometry': geom}\n" ]
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division import sys import json import math import fiona from fiona.errors import DriverError import rasterio import warnings from rasterio.transform import guard_transform from affine import Affine import numpy as np try: from sh...
perrygeo/python-rasterstats
src/rasterstats/io.py
rowcol
python
def rowcol(x, y, affine, op=math.floor): r = int(op((y - affine.f) / affine.e)) c = int(op((x - affine.c) / affine.a)) return r, c
Get row/col for a x/y
train
https://github.com/perrygeo/python-rasterstats/blob/910455cd7c9c21eadf464927db72b38ef62b7dfb/src/rasterstats/io.py#L137-L142
null
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division import sys import json import math import fiona from fiona.errors import DriverError import rasterio import warnings from rasterio.transform import guard_transform from affine import Affine import numpy as np try: from sh...
perrygeo/python-rasterstats
src/rasterstats/io.py
bounds_window
python
def bounds_window(bounds, affine): w, s, e, n = bounds row_start, col_start = rowcol(w, n, affine) row_stop, col_stop = rowcol(e, s, affine, op=math.ceil) return (row_start, row_stop), (col_start, col_stop)
Create a full cover rasterio-style window
train
https://github.com/perrygeo/python-rasterstats/blob/910455cd7c9c21eadf464927db72b38ef62b7dfb/src/rasterstats/io.py#L145-L151
[ "def rowcol(x, y, affine, op=math.floor):\n \"\"\" Get row/col for a x/y\n \"\"\"\n r = int(op((y - affine.f) / affine.e))\n c = int(op((x - affine.c) / affine.a))\n return r, c\n" ]
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division import sys import json import math import fiona from fiona.errors import DriverError import rasterio import warnings from rasterio.transform import guard_transform from affine import Affine import numpy as np try: from sh...
perrygeo/python-rasterstats
src/rasterstats/io.py
Raster.index
python
def index(self, x, y): col, row = [math.floor(a) for a in (~self.affine * (x, y))] return row, col
Given (x, y) in crs, return the (row, column) on the raster
train
https://github.com/perrygeo/python-rasterstats/blob/910455cd7c9c21eadf464927db72b38ef62b7dfb/src/rasterstats/io.py#L258-L262
null
class Raster(object): """ Raster abstraction for data access to 2/3D array-like things Use as a context manager to ensure dataset gets closed properly:: >>> with Raster(path) as rast: ... Parameters ---------- raster: 2/3D array-like data source, required Currently support...
perrygeo/python-rasterstats
src/rasterstats/io.py
Raster.read
python
def read(self, bounds=None, window=None, masked=False): # Calculate the window if bounds and window: raise ValueError("Specify either bounds or window") if bounds: win = bounds_window(bounds, self.affine) elif window: win = window else: ...
Performs a boundless read against the underlying array source Parameters ---------- bounds: bounding box in w, s, e, n order, iterable, optional window: rasterio-style window, optional bounds OR window are required, specifying both or neither will rai...
train
https://github.com/perrygeo/python-rasterstats/blob/910455cd7c9c21eadf464927db72b38ef62b7dfb/src/rasterstats/io.py#L264-L311
[ "def bounds_window(bounds, affine):\n \"\"\"Create a full cover rasterio-style window\n \"\"\"\n w, s, e, n = bounds\n row_start, col_start = rowcol(w, n, affine)\n row_stop, col_stop = rowcol(e, s, affine, op=math.ceil)\n return (row_start, row_stop), (col_start, col_stop)\n", "def window_bound...
class Raster(object): """ Raster abstraction for data access to 2/3D array-like things Use as a context manager to ensure dataset gets closed properly:: >>> with Raster(path) as rast: ... Parameters ---------- raster: 2/3D array-like data source, required Currently support...
perrygeo/python-rasterstats
src/rasterstats/main.py
gen_zonal_stats
python
def gen_zonal_stats( vectors, raster, layer=0, band=1, nodata=None, affine=None, stats=None, all_touched=False, categorical=False, category_map=None, add_stats=None, zone_func=None, raster_out=False, prefix=None, ...
Zonal statistics of raster values aggregated to vector geometries. Parameters ---------- vectors: path to an vector source or geo-like python objects raster: ndarray or path to a GDAL raster source If ndarray is passed, the ``affine`` kwarg is required. layer: int or string, optional ...
train
https://github.com/perrygeo/python-rasterstats/blob/910455cd7c9c21eadf464927db72b38ef62b7dfb/src/rasterstats/main.py#L34-L278
[ "def read_features(obj, layer=0):\n features_iter = None\n\n if isinstance(obj, string_types):\n try:\n # test it as fiona data source\n with fiona.open(obj, 'r', layer=layer) as src:\n assert len(src) > 0\n\n def fiona_generator(obj):\n wi...
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from affine import Affine from shapely.geometry import shape import numpy as np import numpy.distutils.system_info as sysinfo import warnings from .io import read_features, Raster from .utils import (rasterize_geom, get_per...
perrygeo/python-rasterstats
examples/multiproc.py
chunks
python
def chunks(data, n): for i in range(0, len(data), n): yield data[i:i+n]
Yield successive n-sized chunks from a slice-able iterable.
train
https://github.com/perrygeo/python-rasterstats/blob/910455cd7c9c21eadf464927db72b38ef62b7dfb/examples/multiproc.py#L13-L16
null
#!/usr/bin/env python import itertools import multiprocessing from rasterstats import zonal_stats import fiona shp = "benchmark_data/ne_50m_admin_0_countries.shp" tif = "benchmark_data/srtm.tif" def zonal_stats_partial(feats): """Wrapper for zonal stats, takes a list of features""" return zonal_stats(feat...
ecmwf/cfgrib
cfgrib/cfmessage.py
from_grib_date_time
python
def from_grib_date_time(message, date_key='dataDate', time_key='dataTime', epoch=DEFAULT_EPOCH): # type: (T.Mapping, str, str, datetime.datetime) -> int date = message[date_key] time = message[time_key] hour = time // 100 minute = time % 100 year = date // 10000 month = date // 100 % 100 ...
Return the number of seconds since the ``epoch`` from the values of the ``message`` keys, using datetime.total_seconds(). :param message: the target GRIB message :param date_key: the date key, defaults to "dataDate" :param time_key: the time key, defaults to "dataTime" :param epoch: the reference d...
train
https://github.com/ecmwf/cfgrib/blob/d6d533f49c1eebf78f2f16ed0671c666de08c666/cfgrib/cfmessage.py#L40-L61
null
# # Copyright 2017-2019 European Centre for Medium-Range Weather Forecasts (ECMWF). # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
ecmwf/cfgrib
cfgrib/cfmessage.py
build_valid_time
python
def build_valid_time(time, step): # type: (np.ndarray, np.ndarray) -> T.Tuple[T.Tuple[str, ...], np.ndarray] step_s = step * 3600 if len(time.shape) == 0 and len(step.shape) == 0: data = time + step_s dims = () # type: T.Tuple[str, ...] elif len(time.shape) > 0 and len(step.shape) == 0:...
Return dimensions and data of the valid_time corresponding to the given ``time`` and ``step``. The data is seconds from the same epoch as ``time`` and may have one or two dimensions. :param time: given in seconds from an epoch, as returned by ``from_grib_date_time`` :param step: given in hours, as returned...
train
https://github.com/ecmwf/cfgrib/blob/d6d533f49c1eebf78f2f16ed0671c666de08c666/cfgrib/cfmessage.py#L92-L114
null
# # Copyright 2017-2019 European Centre for Medium-Range Weather Forecasts (ECMWF). # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
ecmwf/cfgrib
cfgrib/dataset.py
open_file
python
def open_file(path, grib_errors='warn', **kwargs): if 'mode' in kwargs: warnings.warn("the `mode` keyword argument is ignored and deprecated", FutureWarning) kwargs.pop('mode') stream = messages.FileStream(path, message_class=cfmessage.CfMessage, errors=grib_errors) return Dataset(*build_dat...
Open a GRIB file as a ``cfgrib.Dataset``.
train
https://github.com/ecmwf/cfgrib/blob/d6d533f49c1eebf78f2f16ed0671c666de08c666/cfgrib/dataset.py#L502-L508
[ "def build_dataset_components(\n stream, indexpath='{path}.{short_hash}.idx', filter_by_keys={}, errors='warn',\n encode_cf=('parameter', 'time', 'geography', 'vertical'), timestamp=None, log=LOG,\n):\n filter_by_keys = dict(filter_by_keys)\n index = stream.index(ALL_KEYS, indexpath=indexpath).s...
# # Copyright 2017-2019 European Centre for Medium-Range Weather Forecasts (ECMWF). # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
ecmwf/cfgrib
cfgrib/xarray_to_grib.py
canonical_dataarray_to_grib
python
def canonical_dataarray_to_grib( data_var, file, grib_keys={}, default_grib_keys=DEFAULT_GRIB_KEYS, **kwargs ): # type: (T.IO[bytes], xr.DataArray, T.Dict[str, T.Any], T.Dict[str, T.Any], T.Any) -> None # validate Dataset keys, DataArray names, and attr keys/values detected_keys, suggested_keys = de...
Write a ``xr.DataArray`` in *canonical* form to a GRIB file.
train
https://github.com/ecmwf/cfgrib/blob/d6d533f49c1eebf78f2f16ed0671c666de08c666/cfgrib/xarray_to_grib.py#L197-L239
[ "def detect_grib_keys(data_var, default_grib_keys, grib_keys={}):\n # type: (xr.DataArray, T.Dict[str, T.Any], T.Dict[str, T.Any]) -> T.Tuple[dict, dict]\n detected_grib_keys = {}\n suggested_grib_keys = default_grib_keys.copy()\n\n for key, value in data_var.attrs.items():\n if key[:5] == 'GRIB_...
# # Copyright 2017-2019 European Centre for Medium-Range Weather Forecasts (ECMWF). # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
ecmwf/cfgrib
cfgrib/xarray_to_grib.py
canonical_dataset_to_grib
python
def canonical_dataset_to_grib(dataset, path, mode='wb', no_warn=False, grib_keys={}, **kwargs): # type: (xr.Dataset, str, str, bool, T.Dict[str, T.Any] T.Any) -> None if not no_warn: warnings.warn("GRIB write support is experimental, DO NOT RELY ON IT!", FutureWarning) # validate Dataset keys, Data...
Write a ``xr.Dataset`` in *canonical* form to a GRIB file.
train
https://github.com/ecmwf/cfgrib/blob/d6d533f49c1eebf78f2f16ed0671c666de08c666/cfgrib/xarray_to_grib.py#L242-L259
[ "def canonical_dataarray_to_grib(\n data_var, file, grib_keys={}, default_grib_keys=DEFAULT_GRIB_KEYS, **kwargs\n):\n # type: (T.IO[bytes], xr.DataArray, T.Dict[str, T.Any], T.Dict[str, T.Any], T.Any) -> None\n \"\"\"\n Write a ``xr.DataArray`` in *canonical* form to a GRIB file.\n \"\"\"\n # ...
# # Copyright 2017-2019 European Centre for Medium-Range Weather Forecasts (ECMWF). # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
ecmwf/cfgrib
cfgrib/xarray_store.py
open_dataset
python
def open_dataset(path, **kwargs): # type: (str, T.Any) -> xr.Dataset if 'engine' in kwargs and kwargs['engine'] != 'cfgrib': raise ValueError("only engine=='cfgrib' is supported") kwargs['engine'] = 'cfgrib' return xr.backends.api.open_dataset(path, **kwargs)
Return a ``xr.Dataset`` with the requested ``backend_kwargs`` from a GRIB file.
train
https://github.com/ecmwf/cfgrib/blob/d6d533f49c1eebf78f2f16ed0671c666de08c666/cfgrib/xarray_store.py#L31-L39
null
# # Copyright 2017-2019 European Centre for Medium-Range Weather Forecasts (ECMWF). # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
ecmwf/cfgrib
cfgrib/xarray_store.py
open_datasets
python
def open_datasets(path, backend_kwargs={}, no_warn=False, **kwargs): # type: (str, T.Dict[str, T.Any], bool, T.Any) -> T.List[xr.Dataset] if not no_warn: warnings.warn("open_datasets is an experimental API, DO NOT RELY ON IT!", FutureWarning) fbks = [] datasets = [] try: datasets.ap...
Open a GRIB file groupping incompatible hypercubes to different datasets via simple heuristics.
train
https://github.com/ecmwf/cfgrib/blob/d6d533f49c1eebf78f2f16ed0671c666de08c666/cfgrib/xarray_store.py#L42-L62
[ "def open_dataset(path, **kwargs):\n # type: (str, T.Any) -> xr.Dataset\n \"\"\"\n Return a ``xr.Dataset`` with the requested ``backend_kwargs`` from a GRIB file.\n \"\"\"\n if 'engine' in kwargs and kwargs['engine'] != 'cfgrib':\n raise ValueError(\"only engine=='cfgrib' is supported\")\n ...
# # Copyright 2017-2019 European Centre for Medium-Range Weather Forecasts (ECMWF). # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
ecmwf/cfgrib
cfgrib/bindings.py
codes_get_size
python
def codes_get_size(handle, key): # type: (cffi.FFI.CData, str) -> int size = ffi.new('size_t *') _codes_get_size(handle, key.encode(ENC), size) return size[0]
Get the number of coded value from a key. If several keys of the same name are present, the total sum is returned. :param bytes key: the keyword to get the size of :rtype: int
train
https://github.com/ecmwf/cfgrib/blob/d6d533f49c1eebf78f2f16ed0671c666de08c666/cfgrib/bindings.py#L212-L224
null
# # Copyright 2017-2019 European Centre for Medium-Range Weather Forecasts (ECMWF). # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
ecmwf/cfgrib
cfgrib/bindings.py
codes_get_string_length
python
def codes_get_string_length(handle, key): # type: (cffi.FFI.CData, str) -> int size = ffi.new('size_t *') _codes_get_length(handle, key.encode(ENC), size) return size[0]
Get the length of the string representation of the key. If several keys of the same name are present, the maximum length is returned. :param bytes key: the keyword to get the string representation size of. :rtype: int
train
https://github.com/ecmwf/cfgrib/blob/d6d533f49c1eebf78f2f16ed0671c666de08c666/cfgrib/bindings.py#L230-L242
null
# # Copyright 2017-2019 European Centre for Medium-Range Weather Forecasts (ECMWF). # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
ecmwf/cfgrib
cfgrib/bindings.py
codes_get_bytes_array
python
def codes_get_bytes_array(handle, key, size): # type: (cffi.FFI.CData, str, int) -> T.List[int] values = ffi.new('unsigned char[]', size) size_p = ffi.new('size_t *', size) _codes_get_bytes(handle, key.encode(ENC), values, size_p) return list(values)
Get unsigned chars array values from a key. :param bytes key: the keyword whose value(s) are to be extracted :rtype: List(int)
train
https://github.com/ecmwf/cfgrib/blob/d6d533f49c1eebf78f2f16ed0671c666de08c666/cfgrib/bindings.py#L248-L260
null
# # Copyright 2017-2019 European Centre for Medium-Range Weather Forecasts (ECMWF). # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
ecmwf/cfgrib
cfgrib/bindings.py
codes_get_long_array
python
def codes_get_long_array(handle, key, size): # type: (cffi.FFI.CData, str, int) -> T.List[int] values = ffi.new('long[]', size) size_p = ffi.new('size_t *', size) _codes_get_long_array(handle, key.encode(ENC), values, size_p) return list(values)
Get long array values from a key. :param bytes key: the keyword whose value(s) are to be extracted :rtype: List(int)
train
https://github.com/ecmwf/cfgrib/blob/d6d533f49c1eebf78f2f16ed0671c666de08c666/cfgrib/bindings.py#L266-L278
null
# # Copyright 2017-2019 European Centre for Medium-Range Weather Forecasts (ECMWF). # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
ecmwf/cfgrib
cfgrib/bindings.py
codes_get_double_array
python
def codes_get_double_array(handle, key, size): # type: (cffi.FFI.CData, str, int) -> T.List[float] values = ffi.new('double[]', size) size_p = ffi.new('size_t *', size) _codes_get_double_array(handle, key.encode(ENC), values, size_p) return list(values)
Get double array values from a key. :param bytes key: the keyword whose value(s) are to be extracted :rtype: T.List(float)
train
https://github.com/ecmwf/cfgrib/blob/d6d533f49c1eebf78f2f16ed0671c666de08c666/cfgrib/bindings.py#L284-L296
null
# # Copyright 2017-2019 European Centre for Medium-Range Weather Forecasts (ECMWF). # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
ecmwf/cfgrib
cfgrib/bindings.py
codes_get_string_array
python
def codes_get_string_array(handle, key, size, length=None): # type: (cffi.FFI.CData, bytes, int, int) -> T.List[bytes] if length is None: length = codes_get_string_length(handle, key) values_keepalive = [ffi.new('char[]', length) for _ in range(size)] values = ffi.new('char*[]', values_keepalive...
Get string array values from a key. :param bytes key: the keyword whose value(s) are to be extracted :rtype: T.List[bytes]
train
https://github.com/ecmwf/cfgrib/blob/d6d533f49c1eebf78f2f16ed0671c666de08c666/cfgrib/bindings.py#L302-L317
[ "def codes_get_string_length(handle, key):\n # type: (cffi.FFI.CData, str) -> int\n \"\"\"\n Get the length of the string representation of the key.\n If several keys of the same name are present, the maximum length is returned.\n\n :param bytes key: the keyword to get the string representation size ...
# # Copyright 2017-2019 European Centre for Medium-Range Weather Forecasts (ECMWF). # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
ecmwf/cfgrib
cfgrib/bindings.py
codes_get_string
python
def codes_get_string(handle, key, length=None): # type: (cffi.FFI.CData, str, int) -> str if length is None: length = codes_get_string_length(handle, key) values = ffi.new('char[]', length) length_p = ffi.new('size_t *', length) _codes_get_string = check_return(lib.codes_get_string) _cod...
Get string element from a key. It may or may not fail in case there are more than one key in a message. Outputs the last element. :param bytes key: the keyword to select the value of :param bool strict: flag to select if the method should fail in case of more than one key in single message ...
train
https://github.com/ecmwf/cfgrib/blob/d6d533f49c1eebf78f2f16ed0671c666de08c666/cfgrib/bindings.py#L336-L355
[ "def check_return(func):\n\n @functools.wraps(func)\n def wrapper(*args):\n code = func(*args)\n if code != lib.GRIB_SUCCESS:\n if code in ERROR_MAP:\n raise ERROR_MAP[code](code)\n else:\n raise GribInternalError(code)\n\n return wrapper\n"...
# # Copyright 2017-2019 European Centre for Medium-Range Weather Forecasts (ECMWF). # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
ecmwf/cfgrib
cfgrib/bindings.py
codes_get_api_version
python
def codes_get_api_version(): ver = lib.codes_get_api_version() patch = ver % 100 ver = ver // 100 minor = ver % 100 major = ver // 100 return "%d.%d.%d" % (major, minor, patch)
Get the API version. Returns the version of the API as a string in the format "major.minor.revision".
train
https://github.com/ecmwf/cfgrib/blob/d6d533f49c1eebf78f2f16ed0671c666de08c666/cfgrib/bindings.py#L427-L439
null
# # Copyright 2017-2019 European Centre for Medium-Range Weather Forecasts (ECMWF). # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
ecmwf/cfgrib
cfgrib/bindings.py
codes_write
python
def codes_write(handle, outfile): # type: (cffi.FFI.CData, T.BinaryIO) -> None mess = ffi.new('const void **') mess_len = ffi.new('size_t*') codes_get_message = check_return(lib.codes_get_message) codes_get_message(handle, mess, mess_len) message = ffi.buffer(mess[0], size=mess_len[0]) outfi...
Write a coded message to a file. If the file does not exist, it is created. :param str path: (optional) the path to the GRIB file; defaults to the one of the open index.
train
https://github.com/ecmwf/cfgrib/blob/d6d533f49c1eebf78f2f16ed0671c666de08c666/cfgrib/bindings.py#L553-L566
[ "def check_return(func):\n\n @functools.wraps(func)\n def wrapper(*args):\n code = func(*args)\n if code != lib.GRIB_SUCCESS:\n if code in ERROR_MAP:\n raise ERROR_MAP[code](code)\n else:\n raise GribInternalError(code)\n\n return wrapper\n"...
# # Copyright 2017-2019 European Centre for Medium-Range Weather Forecasts (ECMWF). # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
hyperledger-archives/indy-anoncreds
anoncreds/protocol/utils.py
get_hash_as_int
python
def get_hash_as_int(*args, group: cmod.PairingGroup = None): group = group if group else cmod.PairingGroup(PAIRING_GROUP) h_challenge = sha256() serialedArgs = [group.serialize(arg) if isGroupElement(arg) else cmod.Conversion.IP2OS(arg) for arg in args] for arg...
Enumerate over the input tuple and generate a hash using the tuple values :param args: sequence of either group or integer elements :param group: pairing group if an element is a group element :return:
train
https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/utils.py#L29-L47
[ "def bytes_to_int(bytesHash):\n return int.from_bytes(bytesHash, byteorder=byteorder)\n" ]
import logging import string import time from collections import OrderedDict from enum import Enum from hashlib import sha256 from math import sqrt, floor from random import randint, sample from sys import byteorder from typing import Dict, List, Set import base58 from anoncreds.protocol.globals import KEYS, PK_R fro...
hyperledger-archives/indy-anoncreds
anoncreds/protocol/utils.py
randomString
python
def randomString(size: int = 20, chars: str = string.ascii_letters + string.digits) -> str: return ''.join(sample(chars, size))
Generate a random string of the specified size. Ensure that the size is less than the length of chars as this function uses random.choice which uses random sampling without replacement. :param size: size of the random string to generate :param chars: the set of characters to use to generate the random...
train
https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/utils.py#L200-L213
null
import logging import string import time from collections import OrderedDict from enum import Enum from hashlib import sha256 from math import sqrt, floor from random import randint, sample from sys import byteorder from typing import Dict, List, Set import base58 from anoncreds.protocol.globals import KEYS, PK_R fro...
hyperledger-archives/indy-anoncreds
anoncreds/protocol/utils.py
genPrime
python
def genPrime(): prime = cmod.randomPrime(LARGE_PRIME) i = 0 while not cmod.isPrime(2 * prime + 1): prime = cmod.randomPrime(LARGE_PRIME) i += 1 return prime
Generate 2 large primes `p_prime` and `q_prime` and use them to generate another 2 primes `p` and `q` of 1024 bits
train
https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/utils.py#L264-L274
null
import logging import string import time from collections import OrderedDict from enum import Enum from hashlib import sha256 from math import sqrt, floor from random import randint, sample from sys import byteorder from typing import Dict, List, Set import base58 from anoncreds.protocol.globals import KEYS, PK_R fro...
hyperledger-archives/indy-anoncreds
anoncreds/protocol/types.py
Attribs.encoded
python
def encoded(self): encoded = {} for i in range(len(self.credType.names)): self.credType.names[i] attr_types = self.credType.attrTypes[i] for at in attr_types: attrName = at.name if attrName in self._vals: if at.enc...
This function will encode all the attributes to 256 bit integers :return:
train
https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/types.py#L77-L96
[ "def encodeAttr(attrValue):\n return cmod.Conversion.bytes2integer(sha256(str(attrValue).encode()).digest())\n" ]
class Attribs: def __init__(self, credType: AttribDef = None, **vals): self.credType = credType if credType else AttribDef([], []) self._vals = vals def __add__(self, other): vals = self._vals.copy() vals.update(other._vals) return Attribs(self.credType + other.credType...
hyperledger-archives/indy-anoncreds
anoncreds/protocol/issuer.py
Issuer.genSchema
python
async def genSchema(self, name, version, attrNames) -> Schema: schema = Schema(name, version, attrNames, self.issuerId) return await self.wallet.submitSchema(schema)
Generates and submits Schema. :param name: schema name :param version: schema version :param attrNames: a list of attributes the schema contains :return: submitted Schema
train
https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/issuer.py#L34-L44
[ "async def submitSchema(self,\n schema: Schema) -> Schema:\n schema = await self._repo.submitSchema(schema)\n if schema:\n self._cacheSchema(schema)\n return schema\n" ]
class Issuer: def __init__(self, wallet: IssuerWallet, attrRepo: AttributeRepo): self.wallet = wallet self._attrRepo = attrRepo self._primaryIssuer = PrimaryClaimIssuer(wallet) self._nonRevocationIssuer = NonRevocationClaimIssuer(wallet) # # PUBLIC # @property d...
hyperledger-archives/indy-anoncreds
anoncreds/protocol/issuer.py
Issuer.genKeys
python
async def genKeys(self, schemaId: ID, p_prime=None, q_prime=None) -> ( PublicKey, RevocationPublicKey): pk, sk = await self._primaryIssuer.genKeys(schemaId, p_prime, q_prime) pkR, skR = await self._nonRevocationIssuer.genRevocationKeys() pk = await self.wallet.submitPublicKeys(schema...
Generates and submits keys (both public and secret, primary and non-revocation). :param schemaId: The schema ID (reference to claim definition schema) :param p_prime: optional p_prime parameter :param q_prime: optional q_prime parameter :return: Submitted Public keys (bo...
train
https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/issuer.py#L46-L64
[ "async def submitPublicKeys(self, schemaId: ID, pk: PublicKey,\n pkR: RevocationPublicKey = None) -> (\n PublicKey, RevocationPublicKey):\n pk, pkR = await self._repo.submitPublicKeys(schemaId, pk, pkR)\n await self._cacheValueForId(self._pks, schemaId, pk)\n if pkR:\n ...
class Issuer: def __init__(self, wallet: IssuerWallet, attrRepo: AttributeRepo): self.wallet = wallet self._attrRepo = attrRepo self._primaryIssuer = PrimaryClaimIssuer(wallet) self._nonRevocationIssuer = NonRevocationClaimIssuer(wallet) # # PUBLIC # @property d...
hyperledger-archives/indy-anoncreds
anoncreds/protocol/issuer.py
Issuer.issueAccumulator
python
async def issueAccumulator(self, schemaId: ID, iA, L) -> AccumulatorPublicKey: accum, tails, accPK, accSK = await self._nonRevocationIssuer.issueAccumulator( schemaId, iA, L) accPK = await self.wallet.submitAccumPublic(schemaId=schemaId, ...
Issues and submits an accumulator used for non-revocation proof. :param schemaId: The schema ID (reference to claim definition schema) :param iA: accumulator ID :param L: maximum number of claims within accumulator. :return: Submitted accumulator public key
train
https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/issuer.py#L66-L84
[ "async def submitAccumPublic(self, schemaId: ID,\n accumPK: AccumulatorPublicKey,\n accum: Accumulator,\n tails: Tails) -> AccumulatorPublicKey:\n accumPK = await self._repo.submitAccumulator(schemaId, accumPK, accum,\n ...
class Issuer: def __init__(self, wallet: IssuerWallet, attrRepo: AttributeRepo): self.wallet = wallet self._attrRepo = attrRepo self._primaryIssuer = PrimaryClaimIssuer(wallet) self._nonRevocationIssuer = NonRevocationClaimIssuer(wallet) # # PUBLIC # @property d...
hyperledger-archives/indy-anoncreds
anoncreds/protocol/issuer.py
Issuer.revoke
python
async def revoke(self, schemaId: ID, i): acc, ts = await self._nonRevocationIssuer.revoke(schemaId, i) await self.wallet.submitAccumUpdate(schemaId=schemaId, accum=acc, timestampMs=ts)
Performs revocation of a Claim. :param schemaId: The schema ID (reference to claim definition schema) :param i: claim's sequence number within accumulator
train
https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/issuer.py#L86-L96
null
class Issuer: def __init__(self, wallet: IssuerWallet, attrRepo: AttributeRepo): self.wallet = wallet self._attrRepo = attrRepo self._primaryIssuer = PrimaryClaimIssuer(wallet) self._nonRevocationIssuer = NonRevocationClaimIssuer(wallet) # # PUBLIC # @property d...
hyperledger-archives/indy-anoncreds
anoncreds/protocol/issuer.py
Issuer.issueClaim
python
async def issueClaim(self, schemaId: ID, claimRequest: ClaimRequest, iA=None, i=None) -> (Claims, Dict[str, ClaimAttributeValues]): schemaKey = (await self.wallet.getSchema(schemaId)).getKey() attributes = self._attrRepo.getAttributes(schemaKey, ...
Issue a claim for the given user and schema. :param schemaId: The schema ID (reference to claim definition schema) :param claimRequest: A claim request containing prover ID and prover-generated values :param iA: accumulator ID :param i: claim's sequence number within acc...
train
https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/issuer.py#L98-L132
[ "def getAttributes(self, schemaKey: SchemaKey, userId) -> Attribs:\n return self.attributes.get((schemaKey, userId))\n", "async def _genContxt(self, schemaId: ID, iA, userId):\n iA = strToInt(str(iA))\n userId = strToInt(str(userId))\n S = iA | userId\n H = get_hash_as_int(S)\n m2 = cmod.integer...
class Issuer: def __init__(self, wallet: IssuerWallet, attrRepo: AttributeRepo): self.wallet = wallet self._attrRepo = attrRepo self._primaryIssuer = PrimaryClaimIssuer(wallet) self._nonRevocationIssuer = NonRevocationClaimIssuer(wallet) # # PUBLIC # @property d...
hyperledger-archives/indy-anoncreds
anoncreds/protocol/issuer.py
Issuer.issueClaims
python
async def issueClaims(self, allClaimRequest: Dict[ID, ClaimRequest]) -> \ Dict[ID, Claims]: res = {} for schemaId, claimReq in allClaimRequest.items(): res[schemaId] = await self.issueClaim(schemaId, claimReq) return res
Issue claims for the given users and schemas. :param allClaimRequest: a map of schema ID to a claim request containing prover ID and prover-generated values :return: The claims (both primary and non-revocation)
train
https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/issuer.py#L134-L146
[ "async def issueClaim(self, schemaId: ID, claimRequest: ClaimRequest,\n iA=None,\n i=None) -> (Claims, Dict[str, ClaimAttributeValues]):\n \"\"\"\n Issue a claim for the given user and schema.\n\n :param schemaId: The schema ID (reference to claim\n definition sch...
class Issuer: def __init__(self, wallet: IssuerWallet, attrRepo: AttributeRepo): self.wallet = wallet self._attrRepo = attrRepo self._primaryIssuer = PrimaryClaimIssuer(wallet) self._nonRevocationIssuer = NonRevocationClaimIssuer(wallet) # # PUBLIC # @property d...
hyperledger-archives/indy-anoncreds
anoncreds/protocol/verifier.py
Verifier.verify
python
async def verify(self, proofRequest: ProofRequest, proof: FullProof): if proofRequest.verifiableAttributes.keys() != proof.requestedProof.revealed_attrs.keys(): raise ValueError('Received attributes ={} do not correspond to requested={}'.format( proof.requestedProof.revealed_attrs.k...
Verifies a proof from the prover. :param proofRequest: description of a proof to be presented (revealed attributes, predicates, timestamps for non-revocation) :param proof: a proof :return: True if verified successfully and false otherwise.
train
https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/verifier.py#L27-L59
null
class Verifier: def __init__(self, wallet: Wallet): self.wallet = wallet self._primaryVerifier = PrimaryProofVerifier(wallet) self._nonRevocVerifier = NonRevocationProofVerifier(wallet) @property def verifierId(self): return self.wallet.walletId def generateNonce(self):...
hyperledger-archives/indy-anoncreds
anoncreds/protocol/prover.py
Prover.createClaimRequest
python
async def createClaimRequest(self, schemaId: ID, proverId=None, reqNonRevoc=True) -> ClaimRequest: await self._genMasterSecret(schemaId) U = await self._genU(schemaId) Ur = None if not reqNonRevoc else await self._genUr(schemaId) proverId = proverId if pr...
Creates a claim request to the issuer. :param schemaId: The schema ID (reference to claim definition schema) :param proverId: a prover ID request a claim for (if None then the current prover default ID is used) :param reqNonRevoc: whether to request non-revocation claim ...
train
https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/prover.py#L37-L53
[ "async def _genMasterSecret(self, schemaId: ID):\n ms = cmod.integer(cmod.randomBits(LARGE_MASTER_SECRET))\n await self.wallet.submitMasterSecret(schemaId=schemaId, ms=ms)\n", "async def _genU(self, schemaId: ID):\n claimInitData = await self._primaryClaimInitializer.genClaimInitData(\n schemaId)\...
class Prover: def __init__(self, wallet: ProverWallet): self.wallet = wallet self._primaryClaimInitializer = PrimaryClaimInitializer(wallet) self._nonRevocClaimInitializer = NonRevocationClaimInitializer(wallet) self._primaryProofBuilder = PrimaryProofBuilder(wallet) self._...
hyperledger-archives/indy-anoncreds
anoncreds/protocol/prover.py
Prover.createClaimRequests
python
async def createClaimRequests(self, schemaIds: Sequence[ID], proverId=None, reqNonRevoc=True) -> Dict[ID, ClaimRequest]: res = {} for schemaId in schemaIds: res[schemaId] = await self.createClaimRequest(schemaId, ...
Creates a claim request to the issuer. :param schemaIds: The schema IDs (references to claim definition schema) :param proverId: a prover ID request a claim for (if None then the current prover default ID is used) :param reqNonRevoc: whether to request non-revocation claim ...
train
https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/prover.py#L55-L73
[ "async def createClaimRequest(self, schemaId: ID, proverId=None,\n reqNonRevoc=True) -> ClaimRequest:\n \"\"\"\n Creates a claim request to the issuer.\n\n :param schemaId: The schema ID (reference to claim\n definition schema)\n :param proverId: a prover ID request a clai...
class Prover: def __init__(self, wallet: ProverWallet): self.wallet = wallet self._primaryClaimInitializer = PrimaryClaimInitializer(wallet) self._nonRevocClaimInitializer = NonRevocationClaimInitializer(wallet) self._primaryProofBuilder = PrimaryProofBuilder(wallet) self._...
hyperledger-archives/indy-anoncreds
anoncreds/protocol/prover.py
Prover.processClaim
python
async def processClaim(self, schemaId: ID, claimAttributes: Dict[str, ClaimAttributeValues], signature: Claims): await self.wallet.submitContextAttr(schemaId, signature.primaryClaim.m2) await self.wallet.submitClaimAttributes(schemaId, claimAttributes) await self._initPrimaryClaim(schemaId, sig...
Processes and saves a received Claim for the given Schema. :param schemaId: The schema ID (reference to claim definition schema) :param claims: claims to be processed and saved
train
https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/prover.py#L75-L88
[ "async def _initPrimaryClaim(self, schemaId: ID, claim: PrimaryClaim):\n claim = await self._primaryClaimInitializer.preparePrimaryClaim(\n schemaId,\n claim)\n await self.wallet.submitPrimaryClaim(schemaId=schemaId, claim=claim)\n", "async def _initNonRevocationClaim(self, schemaId: ID,\n ...
class Prover: def __init__(self, wallet: ProverWallet): self.wallet = wallet self._primaryClaimInitializer = PrimaryClaimInitializer(wallet) self._nonRevocClaimInitializer = NonRevocationClaimInitializer(wallet) self._primaryProofBuilder = PrimaryProofBuilder(wallet) self._...
hyperledger-archives/indy-anoncreds
anoncreds/protocol/prover.py
Prover.processClaims
python
async def processClaims(self, allClaims: Dict[ID, Claims]): res = [] for schemaId, (claim_signature, claim_attributes) in allClaims.items(): res.append(await self.processClaim(schemaId, claim_attributes, claim_signature)) return res
Processes and saves received Claims. :param claims: claims to be processed and saved for each claim definition.
train
https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/prover.py#L90-L100
[ "async def processClaim(self, schemaId: ID, claimAttributes: Dict[str, ClaimAttributeValues], signature: Claims):\n \"\"\"\n Processes and saves a received Claim for the given Schema.\n\n :param schemaId: The schema ID (reference to claim\n definition schema)\n :param claims: claims to be processed a...
class Prover: def __init__(self, wallet: ProverWallet): self.wallet = wallet self._primaryClaimInitializer = PrimaryClaimInitializer(wallet) self._nonRevocClaimInitializer = NonRevocationClaimInitializer(wallet) self._primaryProofBuilder = PrimaryProofBuilder(wallet) self._...
hyperledger-archives/indy-anoncreds
anoncreds/protocol/prover.py
Prover.presentProof
python
async def presentProof(self, proofRequest: ProofRequest) -> FullProof: claims, requestedProof = await self._findClaims(proofRequest) proof = await self._prepareProof(claims, proofRequest.nonce, requestedProof) return proof
Presents a proof to the verifier. :param proofRequest: description of a proof to be presented (revealed attributes, predicates, timestamps for non-revocation) :return: a proof (both primary and non-revocation) and revealed attributes (initial non-encoded values)
train
https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/prover.py#L102-L112
[ "async def _findClaims(self, proofRequest: ProofRequest) -> (\n Dict[SchemaKey, ProofClaims], Dict[str, Any]):\n revealedAttrs, predicates = proofRequest.verifiableAttributes, proofRequest.predicates\n\n foundRevealedAttrs = {}\n foundPredicates = {}\n proofClaims = {}\n schemas = {}\n allC...
class Prover: def __init__(self, wallet: ProverWallet): self.wallet = wallet self._primaryClaimInitializer = PrimaryClaimInitializer(wallet) self._nonRevocClaimInitializer = NonRevocationClaimInitializer(wallet) self._primaryProofBuilder = PrimaryProofBuilder(wallet) self._...
rmax/scrapy-redis
src/scrapy_redis/dupefilter.py
RFPDupeFilter.from_settings
python
def from_settings(cls, settings): server = get_redis_from_settings(settings) # XXX: This creates one-time key. needed to support to use this # class as standalone dupefilter with scrapy's default scheduler # if scrapy passes spider on open() method this wouldn't be needed # TODO:...
Returns an instance from given settings. This uses by default the key ``dupefilter:<timestamp>``. When using the ``scrapy_redis.scheduler.Scheduler`` class, this method is not used as it needs to pass the spider name in the key. Parameters ---------- settings : scrapy.s...
train
https://github.com/rmax/scrapy-redis/blob/31c022dd145654cb4ea1429f09852a82afa0a01c/src/scrapy_redis/dupefilter.py#L43-L68
[ "def get_redis_from_settings(settings):\n \"\"\"Returns a redis client instance from given Scrapy settings object.\n\n This function uses ``get_client`` to instantiate the client and uses\n ``defaults.REDIS_PARAMS`` global as defaults values for the parameters. You\n can override them using the ``REDIS_...
class RFPDupeFilter(BaseDupeFilter): """Redis-based request duplicates filter. This class can also be used with default Scrapy's scheduler. """ logger = logger def __init__(self, server, key, debug=False): """Initialize the duplicates filter. Parameters ---------- ...
rmax/scrapy-redis
src/scrapy_redis/dupefilter.py
RFPDupeFilter.request_seen
python
def request_seen(self, request): fp = self.request_fingerprint(request) # This returns the number of values added, zero if already exists. added = self.server.sadd(self.key, fp) return added == 0
Returns True if request was already seen. Parameters ---------- request : scrapy.http.Request Returns ------- bool
train
https://github.com/rmax/scrapy-redis/blob/31c022dd145654cb4ea1429f09852a82afa0a01c/src/scrapy_redis/dupefilter.py#L86-L101
null
class RFPDupeFilter(BaseDupeFilter): """Redis-based request duplicates filter. This class can also be used with default Scrapy's scheduler. """ logger = logger def __init__(self, server, key, debug=False): """Initialize the duplicates filter. Parameters ---------- ...
rmax/scrapy-redis
src/scrapy_redis/dupefilter.py
RFPDupeFilter.log
python
def log(self, request, spider): if self.debug: msg = "Filtered duplicate request: %(request)s" self.logger.debug(msg, {'request': request}, extra={'spider': spider}) elif self.logdupes: msg = ("Filtered duplicate request %(request)s" " - no more dup...
Logs given request. Parameters ---------- request : scrapy.http.Request spider : scrapy.spiders.Spider
train
https://github.com/rmax/scrapy-redis/blob/31c022dd145654cb4ea1429f09852a82afa0a01c/src/scrapy_redis/dupefilter.py#L140-L157
null
class RFPDupeFilter(BaseDupeFilter): """Redis-based request duplicates filter. This class can also be used with default Scrapy's scheduler. """ logger = logger def __init__(self, server, key, debug=False): """Initialize the duplicates filter. Parameters ---------- ...
rmax/scrapy-redis
example-project/process_items.py
process_items
python
def process_items(r, keys, timeout, limit=0, log_every=1000, wait=.1): limit = limit or float('inf') processed = 0 while processed < limit: # Change ``blpop`` to ``brpop`` to process as LIFO. ret = r.blpop(keys, timeout) # If data is found before the timeout then we consider we are d...
Process items from a redis queue. Parameters ---------- r : Redis Redis connection instance. keys : list List of keys to read the items from. timeout: int Read timeout.
train
https://github.com/rmax/scrapy-redis/blob/31c022dd145654cb4ea1429f09852a82afa0a01c/example-project/process_items.py#L20-L61
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """A script to process items from a redis queue.""" from __future__ import print_function, unicode_literals import argparse import json import logging import pprint import sys import time from scrapy_redis import get_redis logger = logging.getLogger('process_items') ...
rmax/scrapy-redis
src/scrapy_redis/connection.py
get_redis_from_settings
python
def get_redis_from_settings(settings): params = defaults.REDIS_PARAMS.copy() params.update(settings.getdict('REDIS_PARAMS')) # XXX: Deprecate REDIS_* settings. for source, dest in SETTINGS_PARAMS_MAP.items(): val = settings.get(source) if val: params[dest] = val # Allow ...
Returns a redis client instance from given Scrapy settings object. This function uses ``get_client`` to instantiate the client and uses ``defaults.REDIS_PARAMS`` global as defaults values for the parameters. You can override them using the ``REDIS_PARAMS`` setting. Parameters ---------- settin...
train
https://github.com/rmax/scrapy-redis/blob/31c022dd145654cb4ea1429f09852a82afa0a01c/src/scrapy_redis/connection.py#L17-L60
[ "def get_redis(**kwargs):\n \"\"\"Returns a redis client instance.\n\n Parameters\n ----------\n redis_cls : class, optional\n Defaults to ``redis.StrictRedis``.\n url : str, optional\n If given, ``redis_cls.from_url`` is used to instantiate the class.\n **kwargs\n Extra param...
import six from scrapy.utils.misc import load_object from . import defaults # Shortcut maps 'setting name' -> 'parmater name'. SETTINGS_PARAMS_MAP = { 'REDIS_URL': 'url', 'REDIS_HOST': 'host', 'REDIS_PORT': 'port', 'REDIS_ENCODING': 'encoding', } # Backwards compatible alias. from_settings = get_...
rmax/scrapy-redis
src/scrapy_redis/connection.py
get_redis
python
def get_redis(**kwargs): redis_cls = kwargs.pop('redis_cls', defaults.REDIS_CLS) url = kwargs.pop('url', None) if url: return redis_cls.from_url(url, **kwargs) else: return redis_cls(**kwargs)
Returns a redis client instance. Parameters ---------- redis_cls : class, optional Defaults to ``redis.StrictRedis``. url : str, optional If given, ``redis_cls.from_url`` is used to instantiate the class. **kwargs Extra parameters to be passed to the ``redis_cls`` class. ...
train
https://github.com/rmax/scrapy-redis/blob/31c022dd145654cb4ea1429f09852a82afa0a01c/src/scrapy_redis/connection.py#L67-L90
null
import six from scrapy.utils.misc import load_object from . import defaults # Shortcut maps 'setting name' -> 'parmater name'. SETTINGS_PARAMS_MAP = { 'REDIS_URL': 'url', 'REDIS_HOST': 'host', 'REDIS_PORT': 'port', 'REDIS_ENCODING': 'encoding', } def get_redis_from_settings(settings): """Retur...
rmax/scrapy-redis
src/scrapy_redis/utils.py
bytes_to_str
python
def bytes_to_str(s, encoding='utf-8'): if six.PY3 and isinstance(s, bytes): return s.decode(encoding) return s
Returns a str if a bytes object is given.
train
https://github.com/rmax/scrapy-redis/blob/31c022dd145654cb4ea1429f09852a82afa0a01c/src/scrapy_redis/utils.py#L4-L8
null
import six
rmax/scrapy-redis
src/scrapy_redis/spiders.py
RedisMixin.setup_redis
python
def setup_redis(self, crawler=None): if self.server is not None: return if crawler is None: # We allow optional crawler argument to keep backwards # compatibility. # XXX: Raise a deprecation warning. crawler = getattr(self, 'crawler', None) ...
Setup redis connection and idle signal. This should be called after the spider has set its crawler object.
train
https://github.com/rmax/scrapy-redis/blob/31c022dd145654cb4ea1429f09852a82afa0a01c/src/scrapy_redis/spiders.py#L22-L73
[ "def get_redis_from_settings(settings):\n \"\"\"Returns a redis client instance from given Scrapy settings object.\n\n This function uses ``get_client`` to instantiate the client and uses\n ``defaults.REDIS_PARAMS`` global as defaults values for the parameters. You\n can override them using the ``REDIS_...
class RedisMixin(object): """Mixin class to implement reading urls from a redis queue.""" redis_key = None redis_batch_size = None redis_encoding = None # Redis client placeholder. server = None def start_requests(self): """Returns a batch of start requests from redis.""" r...
rmax/scrapy-redis
src/scrapy_redis/spiders.py
RedisMixin.next_requests
python
def next_requests(self): use_set = self.settings.getbool('REDIS_START_URLS_AS_SET', defaults.START_URLS_AS_SET) fetch_one = self.server.spop if use_set else self.server.lpop # XXX: Do we need to use a timeout here? found = 0 # TODO: Use redis pipeline execution. while fou...
Returns a request to be scheduled or none.
train
https://github.com/rmax/scrapy-redis/blob/31c022dd145654cb4ea1429f09852a82afa0a01c/src/scrapy_redis/spiders.py#L75-L95
[ "def make_request_from_data(self, data):\n \"\"\"Returns a Request instance from data coming from Redis.\n\n By default, ``data`` is an encoded URL. You can override this method to\n provide your own message decoding.\n\n Parameters\n ----------\n data : bytes\n Message from redis.\n\n \...
class RedisMixin(object): """Mixin class to implement reading urls from a redis queue.""" redis_key = None redis_batch_size = None redis_encoding = None # Redis client placeholder. server = None def start_requests(self): """Returns a batch of start requests from redis.""" r...
rmax/scrapy-redis
src/scrapy_redis/spiders.py
RedisMixin.make_request_from_data
python
def make_request_from_data(self, data): url = bytes_to_str(data, self.redis_encoding) return self.make_requests_from_url(url)
Returns a Request instance from data coming from Redis. By default, ``data`` is an encoded URL. You can override this method to provide your own message decoding. Parameters ---------- data : bytes Message from redis.
train
https://github.com/rmax/scrapy-redis/blob/31c022dd145654cb4ea1429f09852a82afa0a01c/src/scrapy_redis/spiders.py#L97-L110
[ "def bytes_to_str(s, encoding='utf-8'):\n \"\"\"Returns a str if a bytes object is given.\"\"\"\n if six.PY3 and isinstance(s, bytes):\n return s.decode(encoding)\n return s\n" ]
class RedisMixin(object): """Mixin class to implement reading urls from a redis queue.""" redis_key = None redis_batch_size = None redis_encoding = None # Redis client placeholder. server = None def start_requests(self): """Returns a batch of start requests from redis.""" r...
rmax/scrapy-redis
src/scrapy_redis/spiders.py
RedisMixin.schedule_next_requests
python
def schedule_next_requests(self): # TODO: While there is capacity, schedule a batch of redis requests. for req in self.next_requests(): self.crawler.engine.crawl(req, spider=self)
Schedules a request if available
train
https://github.com/rmax/scrapy-redis/blob/31c022dd145654cb4ea1429f09852a82afa0a01c/src/scrapy_redis/spiders.py#L112-L116
[ "def next_requests(self):\n \"\"\"Returns a request to be scheduled or none.\"\"\"\n use_set = self.settings.getbool('REDIS_START_URLS_AS_SET', defaults.START_URLS_AS_SET)\n fetch_one = self.server.spop if use_set else self.server.lpop\n # XXX: Do we need to use a timeout here?\n found = 0\n # TOD...
class RedisMixin(object): """Mixin class to implement reading urls from a redis queue.""" redis_key = None redis_batch_size = None redis_encoding = None # Redis client placeholder. server = None def start_requests(self): """Returns a batch of start requests from redis.""" r...
rmax/scrapy-redis
src/scrapy_redis/queue.py
Base._encode_request
python
def _encode_request(self, request): obj = request_to_dict(request, self.spider) return self.serializer.dumps(obj)
Encode a request object
train
https://github.com/rmax/scrapy-redis/blob/31c022dd145654cb4ea1429f09852a82afa0a01c/src/scrapy_redis/queue.py#L40-L43
null
class Base(object): """Per-spider base queue class""" def __init__(self, server, spider, key, serializer=None): """Initialize per-spider redis queue. Parameters ---------- server : StrictRedis Redis client instance. spider : Spider Scrapy spider ...
rmax/scrapy-redis
src/scrapy_redis/queue.py
Base._decode_request
python
def _decode_request(self, encoded_request): obj = self.serializer.loads(encoded_request) return request_from_dict(obj, self.spider)
Decode an request previously encoded
train
https://github.com/rmax/scrapy-redis/blob/31c022dd145654cb4ea1429f09852a82afa0a01c/src/scrapy_redis/queue.py#L45-L48
null
class Base(object): """Per-spider base queue class""" def __init__(self, server, spider, key, serializer=None): """Initialize per-spider redis queue. Parameters ---------- server : StrictRedis Redis client instance. spider : Spider Scrapy spider ...
rmax/scrapy-redis
src/scrapy_redis/queue.py
FifoQueue.push
python
def push(self, request): self.server.lpush(self.key, self._encode_request(request))
Push a request
train
https://github.com/rmax/scrapy-redis/blob/31c022dd145654cb4ea1429f09852a82afa0a01c/src/scrapy_redis/queue.py#L74-L76
[ "def _encode_request(self, request):\n \"\"\"Encode a request object\"\"\"\n obj = request_to_dict(request, self.spider)\n return self.serializer.dumps(obj)\n" ]
class FifoQueue(Base): """Per-spider FIFO queue""" def __len__(self): """Return the length of the queue""" return self.server.llen(self.key) def pop(self, timeout=0): """Pop a request""" if timeout > 0: data = self.server.brpop(self.key, timeout) if...
rmax/scrapy-redis
src/scrapy_redis/queue.py
PriorityQueue.push
python
def push(self, request): data = self._encode_request(request) score = -request.priority # We don't use zadd method as the order of arguments change depending on # whether the class is Redis or StrictRedis, and the option of using # kwargs only accepts strings, not bytes. ...
Push a request
train
https://github.com/rmax/scrapy-redis/blob/31c022dd145654cb4ea1429f09852a82afa0a01c/src/scrapy_redis/queue.py#L97-L104
[ "def _encode_request(self, request):\n \"\"\"Encode a request object\"\"\"\n obj = request_to_dict(request, self.spider)\n return self.serializer.dumps(obj)\n" ]
class PriorityQueue(Base): """Per-spider priority queue abstraction using redis' sorted set""" def __len__(self): """Return the length of the queue""" return self.server.zcard(self.key) def pop(self, timeout=0): """ Pop a request timeout not support in this queue c...
rmax/scrapy-redis
src/scrapy_redis/queue.py
PriorityQueue.pop
python
def pop(self, timeout=0): # use atomic range/remove using multi/exec pipe = self.server.pipeline() pipe.multi() pipe.zrange(self.key, 0, 0).zremrangebyrank(self.key, 0, 0) results, count = pipe.execute() if results: return self._decode_request(results[0])
Pop a request timeout not support in this queue class
train
https://github.com/rmax/scrapy-redis/blob/31c022dd145654cb4ea1429f09852a82afa0a01c/src/scrapy_redis/queue.py#L106-L117
[ "def _decode_request(self, encoded_request):\n \"\"\"Decode an request previously encoded\"\"\"\n obj = self.serializer.loads(encoded_request)\n return request_from_dict(obj, self.spider)\n" ]
class PriorityQueue(Base): """Per-spider priority queue abstraction using redis' sorted set""" def __len__(self): """Return the length of the queue""" return self.server.zcard(self.key) def push(self, request): """Push a request""" data = self._encode_request(request) ...
gusutabopb/aioinflux
aioinflux/serialization/common.py
escape
python
def escape(string, escape_pattern): try: return string.translate(escape_pattern) except AttributeError: warnings.warn("Non-string-like data passed. " "Attempting to convert to 'str'.") return str(string).translate(tag_escape)
Assistant function for string escaping
train
https://github.com/gusutabopb/aioinflux/blob/2e4b7b3e13604e7618c686d89a0673f0bc70b24e/aioinflux/serialization/common.py#L13-L20
null
import warnings # Special characters documentation: # https://docs.influxdata.com/influxdb/v1.4/write_protocols/line_protocol_reference/#special-characters # Although not in the official docs, new line characters are removed in order to avoid issues. # Go implementation: https://github.com/influxdata/influxdb/blob/mas...
gusutabopb/aioinflux
aioinflux/serialization/usertype.py
_make_serializer
python
def _make_serializer(meas, schema, rm_none, extra_tags, placeholder): # noqa: C901 _validate_schema(schema, placeholder) tags = [] fields = [] ts = None meas = meas for k, t in schema.items(): if t is MEASUREMENT: meas = f"{{i.{k}}}" elif t is TIMEINT: ts...
Factory of line protocol parsers
train
https://github.com/gusutabopb/aioinflux/blob/2e4b7b3e13604e7618c686d89a0673f0bc70b24e/aioinflux/serialization/usertype.py#L67-L122
[ "def _validate_schema(schema, placeholder):\n c = Counter(schema.values())\n if not c:\n raise SchemaError(\"Schema/type annotations missing\")\n if c[MEASUREMENT] > 1:\n raise SchemaError(\"Class can't have more than one 'MEASUREMENT' attribute\")\n if sum(c[e] for e in time_types) > 1:\n...
import enum import ciso8601 import time # noinspection PyUnresolvedReferences import re # noqa from collections import Counter from typing import TypeVar, Optional, Mapping from datetime import datetime # noinspection PyUnresolvedReferences from .common import * # noqa from ..compat import pd __all__ = [ 'linep...
gusutabopb/aioinflux
aioinflux/serialization/usertype.py
lineprotocol
python
def lineprotocol( cls=None, *, schema: Optional[Mapping[str, type]] = None, rm_none: bool = False, extra_tags: Optional[Mapping[str, str]] = None, placeholder: bool = False ): def _lineprotocol(cls): _schema = schema or getattr(cls, '__annotations__', {}) ...
Adds ``to_lineprotocol`` method to arbitrary user-defined classes :param cls: Class to monkey-patch :param schema: Schema dictionary (attr/type pairs). :param rm_none: Whether apply a regex to remove ``None`` values. If ``False``, passing ``None`` values to boolean, integer or float or time fields ...
train
https://github.com/gusutabopb/aioinflux/blob/2e4b7b3e13604e7618c686d89a0673f0bc70b24e/aioinflux/serialization/usertype.py#L125-L152
[ "def _lineprotocol(cls):\n _schema = schema or getattr(cls, '__annotations__', {})\n f = _make_serializer(cls.__name__, _schema, rm_none, extra_tags, placeholder)\n cls.to_lineprotocol = f\n return cls\n" ]
import enum import ciso8601 import time # noinspection PyUnresolvedReferences import re # noqa from collections import Counter from typing import TypeVar, Optional, Mapping from datetime import datetime # noinspection PyUnresolvedReferences from .common import * # noqa from ..compat import pd __all__ = [ 'linep...
gusutabopb/aioinflux
aioinflux/serialization/mapping.py
serialize
python
def serialize(point: Mapping, measurement=None, **extra_tags) -> bytes: tags = _serialize_tags(point, extra_tags) return ( f'{_serialize_measurement(point, measurement)}' f'{"," if tags else ""}{tags} ' f'{_serialize_fields(point)} ' f'{_serialize_timestamp(point)}' ).encode(...
Converts dictionary-like data into a single line protocol line (point)
train
https://github.com/gusutabopb/aioinflux/blob/2e4b7b3e13604e7618c686d89a0673f0bc70b24e/aioinflux/serialization/mapping.py#L9-L17
[ "def _serialize_tags(point, extra_tags):\n output = []\n for k, v in {**point.get('tags', {}), **extra_tags}.items():\n k = escape(k, key_escape)\n v = escape(v, tag_escape)\n if not v:\n continue # ignore blank/null string tags\n output.append(f'{k}={v}')\n return '...
import time from typing import Mapping import ciso8601 from .common import * def _serialize_measurement(point, measurement): try: return escape(point['measurement'], measurement_escape) except KeyError: if measurement is None: raise ValueError("'measurement' missing") re...
gusutabopb/aioinflux
aioinflux/serialization/mapping.py
_serialize_fields
python
def _serialize_fields(point): output = [] for k, v in point['fields'].items(): k = escape(k, key_escape) if isinstance(v, bool): output.append(f'{k}={v}') elif isinstance(v, int): output.append(f'{k}={v}i') elif isinstance(v, str): output.appen...
Field values can be floats, integers, strings, or Booleans.
train
https://github.com/gusutabopb/aioinflux/blob/2e4b7b3e13604e7618c686d89a0673f0bc70b24e/aioinflux/serialization/mapping.py#L57-L74
[ "def escape(string, escape_pattern):\n \"\"\"Assistant function for string escaping\"\"\"\n try:\n return string.translate(escape_pattern)\n except AttributeError:\n warnings.warn(\"Non-string-like data passed. \"\n \"Attempting to convert to 'str'.\")\n return str...
import time from typing import Mapping import ciso8601 from .common import * def serialize(point: Mapping, measurement=None, **extra_tags) -> bytes: """Converts dictionary-like data into a single line protocol line (point)""" tags = _serialize_tags(point, extra_tags) return ( f'{_serialize_measu...
gusutabopb/aioinflux
aioinflux/serialization/__init__.py
serialize
python
def serialize(data, measurement=None, tag_columns=None, **extra_tags): if isinstance(data, bytes): return data elif isinstance(data, str): return data.encode('utf-8') elif hasattr(data, 'to_lineprotocol'): return data.to_lineprotocol() elif pd is not None and isinstance(data, pd....
Converts input data into line protocol format
train
https://github.com/gusutabopb/aioinflux/blob/2e4b7b3e13604e7618c686d89a0673f0bc70b24e/aioinflux/serialization/__init__.py#L9-L24
[ "def serialize(df, measurement, tag_columns=None, **extra_tags) -> bytes:\n \"\"\"Converts a Pandas DataFrame into line protocol format\"\"\"\n # Pre-processing\n if measurement is None:\n raise ValueError(\"Missing 'measurement'\")\n if not isinstance(df.index, pd.DatetimeIndex):\n raise ...
# flake8: noqa 402 from ..compat import pd if pd: from . import dataframe from . import mapping
gusutabopb/aioinflux
aioinflux/iterutils.py
iterpoints
python
def iterpoints(resp: dict, parser: Optional[Callable] = None) -> Iterator[Any]: for statement in resp['results']: if 'series' not in statement: continue for series in statement['series']: if parser is None: return (x for x in series['values']) elif...
Iterates a response JSON yielding data point by point. Can be used with both regular and chunked responses. By default, returns just a plain list of values representing each point, without column names, or other metadata. In case a specific format is needed, an optional ``parser`` argument can be pass...
train
https://github.com/gusutabopb/aioinflux/blob/2e4b7b3e13604e7618c686d89a0673f0bc70b24e/aioinflux/iterutils.py#L6-L48
null
import inspect from typing import Optional, Iterator, Callable, Any
gusutabopb/aioinflux
aioinflux/serialization/dataframe.py
parse
python
def parse(resp) -> DataFrameType: statements = [] for statement in resp['results']: series = {} for s in statement.get('series', []): series[_get_name(s)] = _drop_zero_index(_serializer(s)) statements.append(series) if len(statements) == 1: series: dict = stateme...
Makes a dictionary of DataFrames from a response object
train
https://github.com/gusutabopb/aioinflux/blob/2e4b7b3e13604e7618c686d89a0673f0bc70b24e/aioinflux/serialization/dataframe.py#L44-L59
[ "def _serializer(series) -> pd.DataFrame:\n df = pd.DataFrame(series.get('values', []), columns=series['columns'])\n if 'time' not in df.columns:\n return df\n df: pd.DataFrame = df.set_index(pd.to_datetime(df['time'])).drop('time', axis=1)\n df.index = df.index.tz_localize('UTC')\n df.index.n...
import re from functools import reduce from itertools import chain from typing import Union, Dict, List import pandas as pd import numpy as np from .common import * DataFrameType = Union[pd.DataFrame, Dict[str, pd.DataFrame], List[Dict[str, pd.DataFrame]]] # Serialization helper functions # -----------------------...
gusutabopb/aioinflux
aioinflux/serialization/dataframe.py
_itertuples
python
def _itertuples(df): cols = [df.iloc[:, k] for k in range(len(df.columns))] return zip(df.index, *cols)
Custom implementation of ``DataFrame.itertuples`` that returns plain tuples instead of namedtuples. About 50% faster.
train
https://github.com/gusutabopb/aioinflux/blob/2e4b7b3e13604e7618c686d89a0673f0bc70b24e/aioinflux/serialization/dataframe.py#L65-L70
null
import re from functools import reduce from itertools import chain from typing import Union, Dict, List import pandas as pd import numpy as np from .common import * DataFrameType = Union[pd.DataFrame, Dict[str, pd.DataFrame], List[Dict[str, pd.DataFrame]]] # Serialization helper functions # -----------------------...
gusutabopb/aioinflux
aioinflux/serialization/dataframe.py
serialize
python
def serialize(df, measurement, tag_columns=None, **extra_tags) -> bytes: # Pre-processing if measurement is None: raise ValueError("Missing 'measurement'") if not isinstance(df.index, pd.DatetimeIndex): raise ValueError('DataFrame index is not DatetimeIndex') tag_columns = set(tag_column...
Converts a Pandas DataFrame into line protocol format
train
https://github.com/gusutabopb/aioinflux/blob/2e4b7b3e13604e7618c686d89a0673f0bc70b24e/aioinflux/serialization/dataframe.py#L86-L127
[ "def escape(string, escape_pattern):\n \"\"\"Assistant function for string escaping\"\"\"\n try:\n return string.translate(escape_pattern)\n except AttributeError:\n warnings.warn(\"Non-string-like data passed. \"\n \"Attempting to convert to 'str'.\")\n return str...
import re from functools import reduce from itertools import chain from typing import Union, Dict, List import pandas as pd import numpy as np from .common import * DataFrameType = Union[pd.DataFrame, Dict[str, pd.DataFrame], List[Dict[str, pd.DataFrame]]] # Serialization helper functions # -----------------------...
gusutabopb/aioinflux
aioinflux/client.py
runner
python
def runner(coro): @wraps(coro) def inner(self, *args, **kwargs): if self.mode == 'async': return coro(self, *args, **kwargs) return self._loop.run_until_complete(coro(self, *args, **kwargs)) return inner
Function execution decorator.
train
https://github.com/gusutabopb/aioinflux/blob/2e4b7b3e13604e7618c686d89a0673f0bc70b24e/aioinflux/client.py#L25-L34
null
import asyncio import json import logging import warnings from functools import wraps from typing import TypeVar, Union, AnyStr, Mapping, Iterable, Optional, AsyncGenerator import aiohttp from . import serialization from .compat import * if pd: PointType = TypeVar('PointType', Mapping, dict, bytes, pd.DataFrame)...
gusutabopb/aioinflux
aioinflux/client.py
InfluxDBClient.create_session
python
async def create_session(self, **kwargs): self.opts.update(kwargs) self._session = aiohttp.ClientSession(**self.opts, loop=self._loop) if self.redis_opts: if aioredis: self._redis = await aioredis.create_redis(**self.redis_opts, ...
Creates an :class:`aiohttp.ClientSession` Override this or call it with ``kwargs`` to use other :mod:`aiohttp` functionality not covered by :class:`~.InfluxDBClient.__init__`
train
https://github.com/gusutabopb/aioinflux/blob/2e4b7b3e13604e7618c686d89a0673f0bc70b24e/aioinflux/client.py#L146-L159
null
class InfluxDBClient: def __init__( self, host: str = 'localhost', port: int = 8086, mode: str = 'async', output: str = 'json', db: Optional[str] = None, database: Optional[str] = None, ssl: bool = False, *, unix_socket: Optional[str] =...
gusutabopb/aioinflux
aioinflux/client.py
InfluxDBClient.ping
python
async def ping(self) -> dict: if not self._session: await self.create_session() async with self._session.get(self.url.format(endpoint='ping')) as resp: logger.debug(f'{resp.status}: {resp.reason}') return dict(resp.headers.items())
Pings InfluxDB Returns a dictionary containing the headers of the response from ``influxd``.
train
https://github.com/gusutabopb/aioinflux/blob/2e4b7b3e13604e7618c686d89a0673f0bc70b24e/aioinflux/client.py#L228-L237
[ "async def create_session(self, **kwargs):\n \"\"\"Creates an :class:`aiohttp.ClientSession`\n\n Override this or call it with ``kwargs`` to use other :mod:`aiohttp`\n functionality not covered by :class:`~.InfluxDBClient.__init__`\n \"\"\"\n self.opts.update(kwargs)\n self._session = aiohttp.Clie...
class InfluxDBClient: def __init__( self, host: str = 'localhost', port: int = 8086, mode: str = 'async', output: str = 'json', db: Optional[str] = None, database: Optional[str] = None, ssl: bool = False, *, unix_socket: Optional[str] =...
gusutabopb/aioinflux
aioinflux/client.py
InfluxDBClient.write
python
async def write( self, data: Union[PointType, Iterable[PointType]], measurement: Optional[str] = None, db: Optional[str] = None, precision: Optional[str] = None, rp: Optional[str] = None, tag_columns: Optional[Iterable] = None, **extra_tags, ) -> bool:...
Writes data to InfluxDB. Input can be: 1. A mapping (e.g. ``dict``) containing the keys: ``measurement``, ``time``, ``tags``, ``fields`` 2. A Pandas :class:`~pandas.DataFrame` with a :class:`~pandas.DatetimeIndex` 3. A user defined class decorated w/ :func:`~aioin...
train
https://github.com/gusutabopb/aioinflux/blob/2e4b7b3e13604e7618c686d89a0673f0bc70b24e/aioinflux/client.py#L240-L295
[ "def serialize(data, measurement=None, tag_columns=None, **extra_tags):\n \"\"\"Converts input data into line protocol format\"\"\"\n if isinstance(data, bytes):\n return data\n elif isinstance(data, str):\n return data.encode('utf-8')\n elif hasattr(data, 'to_lineprotocol'):\n retu...
class InfluxDBClient: def __init__( self, host: str = 'localhost', port: int = 8086, mode: str = 'async', output: str = 'json', db: Optional[str] = None, database: Optional[str] = None, ssl: bool = False, *, unix_socket: Optional[str] =...
gusutabopb/aioinflux
aioinflux/client.py
InfluxDBClient.query
python
async def query( self, q: AnyStr, *, epoch: str = 'ns', chunked: bool = False, chunk_size: Optional[int] = None, db: Optional[str] = None, use_cache: bool = False, ) -> Union[AsyncGenerator[ResultType, None], ResultType]: async def _chunked_ge...
Sends a query to InfluxDB. Please refer to the InfluxDB documentation for all the possible queries: https://docs.influxdata.com/influxdb/latest/query_language/ :param q: Raw query string :param db: Database to be queried. Defaults to `self.db`. :param epoch: Precision level of r...
train
https://github.com/gusutabopb/aioinflux/blob/2e4b7b3e13604e7618c686d89a0673f0bc70b24e/aioinflux/client.py#L298-L381
[ "def parse(resp) -> DataFrameType:\n \"\"\"Makes a dictionary of DataFrames from a response object\"\"\"\n statements = []\n for statement in resp['results']:\n series = {}\n for s in statement.get('series', []):\n series[_get_name(s)] = _drop_zero_index(_serializer(s))\n st...
class InfluxDBClient: def __init__( self, host: str = 'localhost', port: int = 8086, mode: str = 'async', output: str = 'json', db: Optional[str] = None, database: Optional[str] = None, ssl: bool = False, *, unix_socket: Optional[str] =...
gusutabopb/aioinflux
aioinflux/client.py
InfluxDBClient._check_error
python
def _check_error(response): if 'error' in response: raise InfluxDBError(response['error']) elif 'results' in response: for statement in response['results']: if 'error' in statement: msg = '{d[error]} (statement {d[statement_id]})' ...
Checks for JSON error messages and raises Python exception
train
https://github.com/gusutabopb/aioinflux/blob/2e4b7b3e13604e7618c686d89a0673f0bc70b24e/aioinflux/client.py#L384-L392
null
class InfluxDBClient: def __init__( self, host: str = 'localhost', port: int = 8086, mode: str = 'async', output: str = 'json', db: Optional[str] = None, database: Optional[str] = None, ssl: bool = False, *, unix_socket: Optional[str] =...
elmotec/massedit
massedit.py
get_function
python
def get_function(fn_name): module_name, callable_name = fn_name.split(':') current = globals() if not callable_name: callable_name = module_name else: import importlib try: module = importlib.import_module(module_name) except ImportError: log.error...
Retrieve the function defined by the function_name. Arguments: fn_name: specification of the type module:function_name.
train
https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L66-L90
null
#!/usr/bin/env python # encoding: utf-8 """A python bulk editor class to apply the same code to many files.""" # Copyright (c) 2012-19 Jérôme Lecomte # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in th...
elmotec/massedit
massedit.py
parse_command_line
python
def parse_command_line(argv): import textwrap example = textwrap.dedent(""" Examples: # Simple string substitution (-e). Will show a diff. No changes applied. {0} -e "re.sub('failIf', 'assertFalse', line)" *.py # File level modifications (-f). Overwrites the files in place (-w). {0} -w -f ...
Parse command line argument. See -h option. Arguments: argv: arguments on the command line must include caller file name.
train
https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L332-L402
null
#!/usr/bin/env python # encoding: utf-8 """A python bulk editor class to apply the same code to many files.""" # Copyright (c) 2012-19 Jérôme Lecomte # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in th...
elmotec/massedit
massedit.py
get_paths
python
def get_paths(patterns, start_dirs=None, max_depth=1): # Shortcut: if there is only one pattern, make sure we process just that. if len(patterns) == 1 and not start_dirs: pattern = patterns[0] directory = os.path.dirname(pattern) if directory: patterns = [os.path.basename(pat...
Retrieve files that match any of the patterns.
train
https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L405-L430
null
#!/usr/bin/env python # encoding: utf-8 """A python bulk editor class to apply the same code to many files.""" # Copyright (c) 2012-19 Jérôme Lecomte # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in th...
elmotec/massedit
massedit.py
edit_files
python
def edit_files(patterns, expressions=None, functions=None, executables=None, start_dirs=None, max_depth=1, dry_run=True, output=sys.stdout, encoding=None, newline=None): if not is_list(patterns): raise TypeError("patterns should be a list") if expressions and...
Process patterns with MassEdit. Arguments: patterns: file pattern to identify the files to be processed. expressions: single python expression to be applied line by line. functions: functions to process files contents. executables: os executables to execute on the argument files. Keywo...
train
https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L469-L530
[ "def is_list(arg):\n \"\"\"Factor determination if arg is a list.\n\n Small utility for a better diagnostic because str/unicode are also\n iterable.\n\n \"\"\"\n return iter(arg) and not isinstance(arg, unicode)\n", "def get_paths(patterns, start_dirs=None, max_depth=1):\n \"\"\"Retrieve files t...
#!/usr/bin/env python # encoding: utf-8 """A python bulk editor class to apply the same code to many files.""" # Copyright (c) 2012-19 Jérôme Lecomte # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in th...
elmotec/massedit
massedit.py
command_line
python
def command_line(argv): arguments = parse_command_line(argv) if arguments.generate: generate_fixer_file(arguments.generate) paths = edit_files(arguments.patterns, expressions=arguments.expressions, functions=arguments.functions, ex...
Instantiate an editor and process arguments. Optional argument: - processed_paths: paths processed are appended to the list.
train
https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L533-L558
[ "def parse_command_line(argv):\n \"\"\"Parse command line argument. See -h option.\n\n Arguments:\n argv: arguments on the command line must include caller file name.\n\n \"\"\"\n import textwrap\n\n example = textwrap.dedent(\"\"\"\n Examples:\n # Simple string substitution (-e). Will sho...
#!/usr/bin/env python # encoding: utf-8 """A python bulk editor class to apply the same code to many files.""" # Copyright (c) 2012-19 Jérôme Lecomte # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in th...
elmotec/massedit
massedit.py
main
python
def main(): logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) try: command_line(sys.argv) finally: logging.shutdown()
Main function.
train
https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L561-L567
[ "def command_line(argv):\n \"\"\"Instantiate an editor and process arguments.\n\n Optional argument:\n - processed_paths: paths processed are appended to the list.\n\n \"\"\"\n arguments = parse_command_line(argv)\n if arguments.generate:\n generate_fixer_file(arguments.generate)\n pat...
#!/usr/bin/env python # encoding: utf-8 """A python bulk editor class to apply the same code to many files.""" # Copyright (c) 2012-19 Jérôme Lecomte # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in th...
elmotec/massedit
massedit.py
MassEdit.import_module
python
def import_module(module): # pylint: disable=R0201 if isinstance(module, list): all_modules = module else: all_modules = [module] for mod in all_modules: globals()[mod] = __import__(mod.strip())
Import module that are needed for the code expr to compile. Argument: module (str or list): module(s) to import.
train
https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L131-L143
null
class MassEdit(object): """Mass edit lines of files.""" def __init__(self, **kwds): """Initialize MassEdit object. Args: - code (byte code object): code to execute on input file. - function (str or callable): function to call on input file. - module (str): module...
elmotec/massedit
massedit.py
MassEdit.__edit_line
python
def __edit_line(line, code, code_obj): # pylint: disable=R0201 try: # pylint: disable=eval-used result = eval(code_obj, globals(), locals()) except TypeError as ex: log.error("failed to execute %s: %s", code, ex) raise if result is None: ...
Edit a line with one code object built in the ctor.
train
https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L146-L162
null
class MassEdit(object): """Mass edit lines of files.""" def __init__(self, **kwds): """Initialize MassEdit object. Args: - code (byte code object): code to execute on input file. - function (str or callable): function to call on input file. - module (str): module...
elmotec/massedit
massedit.py
MassEdit.edit_line
python
def edit_line(self, line): for code, code_obj in self.code_objs.items(): line = self.__edit_line(line, code, code_obj) return line
Edit a single line using the code expression.
train
https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L164-L168
[ "def __edit_line(line, code, code_obj): # pylint: disable=R0201\n \"\"\"Edit a line with one code object built in the ctor.\"\"\"\n try:\n # pylint: disable=eval-used\n result = eval(code_obj, globals(), locals())\n except TypeError as ex:\n log.error(\"failed to execute %s: %s\", cod...
class MassEdit(object): """Mass edit lines of files.""" def __init__(self, **kwds): """Initialize MassEdit object. Args: - code (byte code object): code to execute on input file. - function (str or callable): function to call on input file. - module (str): module...
elmotec/massedit
massedit.py
MassEdit.edit_content
python
def edit_content(self, original_lines, file_name): lines = [self.edit_line(line) for line in original_lines] for function in self._functions: try: lines = list(function(lines, file_name)) except UnicodeDecodeError as err: log.error('failed to proce...
Processes a file contents. First processes the contents line by line applying the registered expressions, then process the resulting contents using the registered functions. Arguments: original_lines (list of str): file content. file_name (str): name of the file.
train
https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L170-L193
null
class MassEdit(object): """Mass edit lines of files.""" def __init__(self, **kwds): """Initialize MassEdit object. Args: - code (byte code object): code to execute on input file. - function (str or callable): function to call on input file. - module (str): module...
elmotec/massedit
massedit.py
MassEdit.edit_file
python
def edit_file(self, file_name): with io.open(file_name, "r", encoding=self.encoding) as from_file: try: from_lines = from_file.readlines() except UnicodeDecodeError as err: log.error("encoding error (see --encoding): %s", err) raise ...
Edit file in place, returns a list of modifications (unified diff). Arguments: file_name (str, unicode): The name of the file.
train
https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L195-L260
[ "def edit_content(self, original_lines, file_name):\n \"\"\"Processes a file contents.\n\n First processes the contents line by line applying the registered\n expressions, then process the resulting contents using the\n registered functions.\n\n Arguments:\n original_lines (list of str): file co...
class MassEdit(object): """Mass edit lines of files.""" def __init__(self, **kwds): """Initialize MassEdit object. Args: - code (byte code object): code to execute on input file. - function (str or callable): function to call on input file. - module (str): module...
elmotec/massedit
massedit.py
MassEdit.append_code_expr
python
def append_code_expr(self, code): # expects a string. if isinstance(code, str) and not isinstance(code, unicode): code = unicode(code) if not isinstance(code, unicode): raise TypeError("string expected") log.debug("compiling code %s...", code) try: ...
Compile argument and adds it to the list of code objects.
train
https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L262-L276
null
class MassEdit(object): """Mass edit lines of files.""" def __init__(self, **kwds): """Initialize MassEdit object. Args: - code (byte code object): code to execute on input file. - function (str or callable): function to call on input file. - module (str): module...
elmotec/massedit
massedit.py
MassEdit.append_function
python
def append_function(self, function): if not hasattr(function, '__call__'): function = get_function(function) if not hasattr(function, '__call__'): raise ValueError("function is expected to be callable") self._functions.append(function) log.debug("registere...
Append the function to the list of functions to be called. If the function is already a callable, use it. If it's a type str try to interpret it as [module]:?<callable>, load the module if there is one and retrieve the callable. Argument: function (str or callable): function ...
train
https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L278-L294
[ "def get_function(fn_name):\n \"\"\"Retrieve the function defined by the function_name.\n\n Arguments:\n fn_name: specification of the type module:function_name.\n\n \"\"\"\n module_name, callable_name = fn_name.split(':')\n current = globals()\n if not callable_name:\n callable_name =...
class MassEdit(object): """Mass edit lines of files.""" def __init__(self, **kwds): """Initialize MassEdit object. Args: - code (byte code object): code to execute on input file. - function (str or callable): function to call on input file. - module (str): module...
elmotec/massedit
massedit.py
MassEdit.append_executable
python
def append_executable(self, executable): if isinstance(executable, str) and not isinstance(executable, unicode): executable = unicode(executable) if not isinstance(executable, unicode): raise TypeError("expected executable name as str, not {}". format(...
Append san executable os command to the list to be called. Argument: executable (str): os callable executable.
train
https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L296-L308
null
class MassEdit(object): """Mass edit lines of files.""" def __init__(self, **kwds): """Initialize MassEdit object. Args: - code (byte code object): code to execute on input file. - function (str or callable): function to call on input file. - module (str): module...