body
stringlengths
26
98.2k
body_hash
int64
-9,222,864,604,528,158,000
9,221,803,474B
docstring
stringlengths
1
16.8k
path
stringlengths
5
230
name
stringlengths
1
96
repository_name
stringlengths
7
89
lang
stringclasses
1 value
body_without_docstring
stringlengths
20
98.2k
def __setstate__(self, state): 'Necessary for making this object picklable' if (not isinstance(state, dict)): raise Exception('invalid pickle state') if (('_categories' not in state) and ('_levels' in state)): state['_categories'] = self.dtype.validate_categories(state.pop('_levels')) if...
-6,085,031,369,710,524,000
Necessary for making this object picklable
pandas/core/arrays/categorical.py
__setstate__
Adirio/pandas
python
def __setstate__(self, state): if (not isinstance(state, dict)): raise Exception('invalid pickle state') if (('_categories' not in state) and ('_levels' in state)): state['_categories'] = self.dtype.validate_categories(state.pop('_levels')) if (('_codes' not in state) and ('labels' in s...
def memory_usage(self, deep=False): '\n Memory usage of my values\n\n Parameters\n ----------\n deep : bool\n Introspect the data deeply, interrogate\n `object` dtypes for system-level memory consumption\n\n Returns\n -------\n bytes used\n\n ...
-9,068,621,834,873,815,000
Memory usage of my values Parameters ---------- deep : bool Introspect the data deeply, interrogate `object` dtypes for system-level memory consumption Returns ------- bytes used Notes ----- Memory usage does not include memory consumed by elements that are not components of the array if deep=False See Also...
pandas/core/arrays/categorical.py
memory_usage
Adirio/pandas
python
def memory_usage(self, deep=False): '\n Memory usage of my values\n\n Parameters\n ----------\n deep : bool\n Introspect the data deeply, interrogate\n `object` dtypes for system-level memory consumption\n\n Returns\n -------\n bytes used\n\n ...
def isna(self): '\n Detect missing values\n\n Missing values (-1 in .codes) are detected.\n\n Returns\n -------\n a boolean array of whether my values are null\n\n See also\n --------\n isna : top-level isna\n isnull : alias of isna\n Categorical...
-5,370,868,005,612,063,000
Detect missing values Missing values (-1 in .codes) are detected. Returns ------- a boolean array of whether my values are null See also -------- isna : top-level isna isnull : alias of isna Categorical.notna : boolean inverse of Categorical.isna
pandas/core/arrays/categorical.py
isna
Adirio/pandas
python
def isna(self): '\n Detect missing values\n\n Missing values (-1 in .codes) are detected.\n\n Returns\n -------\n a boolean array of whether my values are null\n\n See also\n --------\n isna : top-level isna\n isnull : alias of isna\n Categorical...
def notna(self): '\n Inverse of isna\n\n Both missing values (-1 in .codes) and NA as a category are detected as\n null.\n\n Returns\n -------\n a boolean array of whether my values are not null\n\n See also\n --------\n notna : top-level notna\n ...
6,422,727,367,209,304,000
Inverse of isna Both missing values (-1 in .codes) and NA as a category are detected as null. Returns ------- a boolean array of whether my values are not null See also -------- notna : top-level notna notnull : alias of notna Categorical.isna : boolean inverse of Categorical.notna
pandas/core/arrays/categorical.py
notna
Adirio/pandas
python
def notna(self): '\n Inverse of isna\n\n Both missing values (-1 in .codes) and NA as a category are detected as\n null.\n\n Returns\n -------\n a boolean array of whether my values are not null\n\n See also\n --------\n notna : top-level notna\n ...
def put(self, *args, **kwargs): '\n Replace specific elements in the Categorical with given values.\n ' raise NotImplementedError("'put' is not yet implemented for Categorical")
2,810,362,659,536,142,000
Replace specific elements in the Categorical with given values.
pandas/core/arrays/categorical.py
put
Adirio/pandas
python
def put(self, *args, **kwargs): '\n \n ' raise NotImplementedError("'put' is not yet implemented for Categorical")
def dropna(self): '\n Return the Categorical without null values.\n\n Missing values (-1 in .codes) are detected.\n\n Returns\n -------\n valid : Categorical\n ' result = self[self.notna()] return result
7,246,204,869,647,670,000
Return the Categorical without null values. Missing values (-1 in .codes) are detected. Returns ------- valid : Categorical
pandas/core/arrays/categorical.py
dropna
Adirio/pandas
python
def dropna(self): '\n Return the Categorical without null values.\n\n Missing values (-1 in .codes) are detected.\n\n Returns\n -------\n valid : Categorical\n ' result = self[self.notna()] return result
def value_counts(self, dropna=True): "\n Returns a Series containing counts of each category.\n\n Every category will have an entry, even those with a count of 0.\n\n Parameters\n ----------\n dropna : boolean, default True\n Don't include counts of NaN.\n\n Retu...
4,811,169,102,183,675,000
Returns a Series containing counts of each category. Every category will have an entry, even those with a count of 0. Parameters ---------- dropna : boolean, default True Don't include counts of NaN. Returns ------- counts : Series See Also -------- Series.value_counts
pandas/core/arrays/categorical.py
value_counts
Adirio/pandas
python
def value_counts(self, dropna=True): "\n Returns a Series containing counts of each category.\n\n Every category will have an entry, even those with a count of 0.\n\n Parameters\n ----------\n dropna : boolean, default True\n Don't include counts of NaN.\n\n Retu...
def get_values(self): ' Return the values.\n\n For internal compatibility with pandas formatting.\n\n Returns\n -------\n values : numpy array\n A numpy array of the same dtype as categorical.categories.dtype or\n Index if datetime / periods\n ' if is_dat...
8,280,021,067,267,941,000
Return the values. For internal compatibility with pandas formatting. Returns ------- values : numpy array A numpy array of the same dtype as categorical.categories.dtype or Index if datetime / periods
pandas/core/arrays/categorical.py
get_values
Adirio/pandas
python
def get_values(self): ' Return the values.\n\n For internal compatibility with pandas formatting.\n\n Returns\n -------\n values : numpy array\n A numpy array of the same dtype as categorical.categories.dtype or\n Index if datetime / periods\n ' if is_dat...
def check_for_ordered(self, op): ' assert that we are ordered ' if (not self.ordered): raise TypeError('Categorical is not ordered for operation {op}\nyou can use .as_ordered() to change the Categorical to an ordered one\n'.format(op=op))
-2,233,153,919,381,657,000
assert that we are ordered
pandas/core/arrays/categorical.py
check_for_ordered
Adirio/pandas
python
def check_for_ordered(self, op): ' ' if (not self.ordered): raise TypeError('Categorical is not ordered for operation {op}\nyou can use .as_ordered() to change the Categorical to an ordered one\n'.format(op=op))
def argsort(self, *args, **kwargs): "Return the indices that would sort the Categorical.\n\n Parameters\n ----------\n ascending : bool, default True\n Whether the indices should result in an ascending\n or descending sort.\n kind : {'quicksort', 'mergesort', 'heaps...
4,805,162,541,346,104,000
Return the indices that would sort the Categorical. Parameters ---------- ascending : bool, default True Whether the indices should result in an ascending or descending sort. kind : {'quicksort', 'mergesort', 'heapsort'}, optional Sorting algorithm. *args, **kwargs: passed through to :func:`numpy.argso...
pandas/core/arrays/categorical.py
argsort
Adirio/pandas
python
def argsort(self, *args, **kwargs): "Return the indices that would sort the Categorical.\n\n Parameters\n ----------\n ascending : bool, default True\n Whether the indices should result in an ascending\n or descending sort.\n kind : {'quicksort', 'mergesort', 'heaps...
def sort_values(self, inplace=False, ascending=True, na_position='last'): " Sorts the Categorical by category value returning a new\n Categorical by default.\n\n While an ordering is applied to the category values, sorting in this\n context refers more to organizing and grouping together based ...
-4,179,080,878,714,503,700
Sorts the Categorical by category value returning a new Categorical by default. While an ordering is applied to the category values, sorting in this context refers more to organizing and grouping together based on matching category values. Thus, this function can be called on an unordered Categorical instance unlike t...
pandas/core/arrays/categorical.py
sort_values
Adirio/pandas
python
def sort_values(self, inplace=False, ascending=True, na_position='last'): " Sorts the Categorical by category value returning a new\n Categorical by default.\n\n While an ordering is applied to the category values, sorting in this\n context refers more to organizing and grouping together based ...
def _values_for_rank(self): '\n For correctly ranking ordered categorical data. See GH#15420\n\n Ordered categorical data should be ranked on the basis of\n codes with -1 translated to NaN.\n\n Returns\n -------\n numpy array\n\n ' from pandas import Series i...
8,110,166,736,292,636,000
For correctly ranking ordered categorical data. See GH#15420 Ordered categorical data should be ranked on the basis of codes with -1 translated to NaN. Returns ------- numpy array
pandas/core/arrays/categorical.py
_values_for_rank
Adirio/pandas
python
def _values_for_rank(self): '\n For correctly ranking ordered categorical data. See GH#15420\n\n Ordered categorical data should be ranked on the basis of\n codes with -1 translated to NaN.\n\n Returns\n -------\n numpy array\n\n ' from pandas import Series i...
def ravel(self, order='C'): ' Return a flattened (numpy) array.\n\n For internal compatibility with numpy arrays.\n\n Returns\n -------\n raveled : numpy array\n ' return np.array(self)
2,510,775,633,478,743,600
Return a flattened (numpy) array. For internal compatibility with numpy arrays. Returns ------- raveled : numpy array
pandas/core/arrays/categorical.py
ravel
Adirio/pandas
python
def ravel(self, order='C'): ' Return a flattened (numpy) array.\n\n For internal compatibility with numpy arrays.\n\n Returns\n -------\n raveled : numpy array\n ' return np.array(self)
def view(self): 'Return a view of myself.\n\n For internal compatibility with numpy arrays.\n\n Returns\n -------\n view : Categorical\n Returns `self`!\n ' return self
7,402,810,746,540,229,000
Return a view of myself. For internal compatibility with numpy arrays. Returns ------- view : Categorical Returns `self`!
pandas/core/arrays/categorical.py
view
Adirio/pandas
python
def view(self): 'Return a view of myself.\n\n For internal compatibility with numpy arrays.\n\n Returns\n -------\n view : Categorical\n Returns `self`!\n ' return self
def to_dense(self): "Return my 'dense' representation\n\n For internal compatibility with numpy arrays.\n\n Returns\n -------\n dense : array\n " return np.asarray(self)
-296,838,486,681,540,900
Return my 'dense' representation For internal compatibility with numpy arrays. Returns ------- dense : array
pandas/core/arrays/categorical.py
to_dense
Adirio/pandas
python
def to_dense(self): "Return my 'dense' representation\n\n For internal compatibility with numpy arrays.\n\n Returns\n -------\n dense : array\n " return np.asarray(self)
@deprecate_kwarg(old_arg_name='fill_value', new_arg_name='value') def fillna(self, value=None, method=None, limit=None): " Fill NA/NaN values using the specified method.\n\n Parameters\n ----------\n value : scalar, dict, Series\n If a scalar value is passed it is used to fill all mi...
-1,140,899,440,471,338,100
Fill NA/NaN values using the specified method. Parameters ---------- value : scalar, dict, Series If a scalar value is passed it is used to fill all missing values. Alternatively, a Series or dict can be used to fill in different values for each index. The value should not be a list. The value(s) passe...
pandas/core/arrays/categorical.py
fillna
Adirio/pandas
python
@deprecate_kwarg(old_arg_name='fill_value', new_arg_name='value') def fillna(self, value=None, method=None, limit=None): " Fill NA/NaN values using the specified method.\n\n Parameters\n ----------\n value : scalar, dict, Series\n If a scalar value is passed it is used to fill all mi...
def take_nd(self, indexer, allow_fill=None, fill_value=None): '\n Take elements from the Categorical.\n\n Parameters\n ----------\n indexer : sequence of integers\n allow_fill : bool, default None.\n How to handle negative values in `indexer`.\n\n * False: ne...
-7,154,992,052,181,375,000
Take elements from the Categorical. Parameters ---------- indexer : sequence of integers allow_fill : bool, default None. How to handle negative values in `indexer`. * False: negative values in `indices` indicate positional indices from the right. This is similar to :func:`numpy.take`. * True...
pandas/core/arrays/categorical.py
take_nd
Adirio/pandas
python
def take_nd(self, indexer, allow_fill=None, fill_value=None): '\n Take elements from the Categorical.\n\n Parameters\n ----------\n indexer : sequence of integers\n allow_fill : bool, default None.\n How to handle negative values in `indexer`.\n\n * False: ne...
def _slice(self, slicer): ' Return a slice of myself.\n\n For internal compatibility with numpy arrays.\n ' if (isinstance(slicer, tuple) and (len(slicer) == 2)): if (not com.is_null_slice(slicer[0])): raise AssertionError('invalid slicing for a 1-ndim categorical') sli...
-1,092,373,934,511,431,700
Return a slice of myself. For internal compatibility with numpy arrays.
pandas/core/arrays/categorical.py
_slice
Adirio/pandas
python
def _slice(self, slicer): ' Return a slice of myself.\n\n For internal compatibility with numpy arrays.\n ' if (isinstance(slicer, tuple) and (len(slicer) == 2)): if (not com.is_null_slice(slicer[0])): raise AssertionError('invalid slicing for a 1-ndim categorical') sli...
def __len__(self): 'The length of this Categorical.' return len(self._codes)
8,220,366,926,502,292,000
The length of this Categorical.
pandas/core/arrays/categorical.py
__len__
Adirio/pandas
python
def __len__(self): return len(self._codes)
def __iter__(self): 'Returns an Iterator over the values of this Categorical.' return iter(self.get_values().tolist())
-8,865,596,715,025,023,000
Returns an Iterator over the values of this Categorical.
pandas/core/arrays/categorical.py
__iter__
Adirio/pandas
python
def __iter__(self): return iter(self.get_values().tolist())
def __contains__(self, key): 'Returns True if `key` is in this Categorical.' if isna(key): return self.isna().any() return contains(self, key, container=self._codes)
8,849,127,086,134,680,000
Returns True if `key` is in this Categorical.
pandas/core/arrays/categorical.py
__contains__
Adirio/pandas
python
def __contains__(self, key): if isna(key): return self.isna().any() return contains(self, key, container=self._codes)
def _tidy_repr(self, max_vals=10, footer=True): ' a short repr displaying only max_vals and an optional (but default\n footer)\n ' num = (max_vals // 2) head = self[:num]._get_repr(length=False, footer=False) tail = self[(- (max_vals - num)):]._get_repr(length=False, footer=False) resu...
-7,886,453,035,888,673,000
a short repr displaying only max_vals and an optional (but default footer)
pandas/core/arrays/categorical.py
_tidy_repr
Adirio/pandas
python
def _tidy_repr(self, max_vals=10, footer=True): ' a short repr displaying only max_vals and an optional (but default\n footer)\n ' num = (max_vals // 2) head = self[:num]._get_repr(length=False, footer=False) tail = self[(- (max_vals - num)):]._get_repr(length=False, footer=False) resu...
def _repr_categories(self): ' return the base repr for the categories ' max_categories = (10 if (get_option('display.max_categories') == 0) else get_option('display.max_categories')) from pandas.io.formats import format as fmt if (len(self.categories) > max_categories): num = (max_categories // ...
2,356,138,557,134,862,300
return the base repr for the categories
pandas/core/arrays/categorical.py
_repr_categories
Adirio/pandas
python
def _repr_categories(self): ' ' max_categories = (10 if (get_option('display.max_categories') == 0) else get_option('display.max_categories')) from pandas.io.formats import format as fmt if (len(self.categories) > max_categories): num = (max_categories // 2) head = fmt.format_array(self...
def _repr_categories_info(self): ' Returns a string representation of the footer.' category_strs = self._repr_categories() dtype = getattr(self.categories, 'dtype_str', str(self.categories.dtype)) levheader = 'Categories ({length}, {dtype}): '.format(length=len(self.categories), dtype=dtype) (width,...
-1,056,543,306,580,598,300
Returns a string representation of the footer.
pandas/core/arrays/categorical.py
_repr_categories_info
Adirio/pandas
python
def _repr_categories_info(self): ' ' category_strs = self._repr_categories() dtype = getattr(self.categories, 'dtype_str', str(self.categories.dtype)) levheader = 'Categories ({length}, {dtype}): '.format(length=len(self.categories), dtype=dtype) (width, height) = get_terminal_size() max_width =...
def __unicode__(self): ' Unicode representation. ' _maxlen = 10 if (len(self._codes) > _maxlen): result = self._tidy_repr(_maxlen) elif (len(self._codes) > 0): result = self._get_repr(length=(len(self) > _maxlen)) else: msg = self._get_repr(length=False, footer=True).replace(...
-2,285,762,338,194,706,700
Unicode representation.
pandas/core/arrays/categorical.py
__unicode__
Adirio/pandas
python
def __unicode__(self): ' ' _maxlen = 10 if (len(self._codes) > _maxlen): result = self._tidy_repr(_maxlen) elif (len(self._codes) > 0): result = self._get_repr(length=(len(self) > _maxlen)) else: msg = self._get_repr(length=False, footer=True).replace('\n', ', ') res...
def _maybe_coerce_indexer(self, indexer): ' return an indexer coerced to the codes dtype ' if (isinstance(indexer, np.ndarray) and (indexer.dtype.kind == 'i')): indexer = indexer.astype(self._codes.dtype) return indexer
-8,060,042,278,688,720,000
return an indexer coerced to the codes dtype
pandas/core/arrays/categorical.py
_maybe_coerce_indexer
Adirio/pandas
python
def _maybe_coerce_indexer(self, indexer): ' ' if (isinstance(indexer, np.ndarray) and (indexer.dtype.kind == 'i')): indexer = indexer.astype(self._codes.dtype) return indexer
def __getitem__(self, key): ' Return an item. ' if isinstance(key, (int, np.integer)): i = self._codes[key] if (i == (- 1)): return np.nan else: return self.categories[i] else: return self._constructor(values=self._codes[key], dtype=self.dtype, fastpat...
7,442,828,030,867,244,000
Return an item.
pandas/core/arrays/categorical.py
__getitem__
Adirio/pandas
python
def __getitem__(self, key): ' ' if isinstance(key, (int, np.integer)): i = self._codes[key] if (i == (- 1)): return np.nan else: return self.categories[i] else: return self._constructor(values=self._codes[key], dtype=self.dtype, fastpath=True)
def __setitem__(self, key, value): ' Item assignment.\n\n\n Raises\n ------\n ValueError\n If (one or more) Value is not in categories or if a assigned\n `Categorical` does not have the same categories\n ' if isinstance(value, Categorical): if (not value...
4,775,883,318,009,241,000
Item assignment. Raises ------ ValueError If (one or more) Value is not in categories or if a assigned `Categorical` does not have the same categories
pandas/core/arrays/categorical.py
__setitem__
Adirio/pandas
python
def __setitem__(self, key, value): ' Item assignment.\n\n\n Raises\n ------\n ValueError\n If (one or more) Value is not in categories or if a assigned\n `Categorical` does not have the same categories\n ' if isinstance(value, Categorical): if (not value...
def _reverse_indexer(self): "\n Compute the inverse of a categorical, returning\n a dict of categories -> indexers.\n\n *This is an internal function*\n\n Returns\n -------\n dict of categories -> indexers\n\n Example\n -------\n In [1]: c = pd.Categori...
-6,168,884,411,218,855,000
Compute the inverse of a categorical, returning a dict of categories -> indexers. *This is an internal function* Returns ------- dict of categories -> indexers Example ------- In [1]: c = pd.Categorical(list('aabca')) In [2]: c Out[2]: [a, a, b, c, a] Categories (3, object): [a, b, c] In [3]: c.categories Out[3]: ...
pandas/core/arrays/categorical.py
_reverse_indexer
Adirio/pandas
python
def _reverse_indexer(self): "\n Compute the inverse of a categorical, returning\n a dict of categories -> indexers.\n\n *This is an internal function*\n\n Returns\n -------\n dict of categories -> indexers\n\n Example\n -------\n In [1]: c = pd.Categori...
def min(self, numeric_only=None, **kwargs): ' The minimum value of the object.\n\n Only ordered `Categoricals` have a minimum!\n\n Raises\n ------\n TypeError\n If the `Categorical` is not `ordered`.\n\n Returns\n -------\n min : the minimum of this `Categ...
3,181,977,709,918,372,000
The minimum value of the object. Only ordered `Categoricals` have a minimum! Raises ------ TypeError If the `Categorical` is not `ordered`. Returns ------- min : the minimum of this `Categorical`
pandas/core/arrays/categorical.py
min
Adirio/pandas
python
def min(self, numeric_only=None, **kwargs): ' The minimum value of the object.\n\n Only ordered `Categoricals` have a minimum!\n\n Raises\n ------\n TypeError\n If the `Categorical` is not `ordered`.\n\n Returns\n -------\n min : the minimum of this `Categ...
def max(self, numeric_only=None, **kwargs): ' The maximum value of the object.\n\n Only ordered `Categoricals` have a maximum!\n\n Raises\n ------\n TypeError\n If the `Categorical` is not `ordered`.\n\n Returns\n -------\n max : the maximum of this `Categ...
2,410,826,779,364,321,000
The maximum value of the object. Only ordered `Categoricals` have a maximum! Raises ------ TypeError If the `Categorical` is not `ordered`. Returns ------- max : the maximum of this `Categorical`
pandas/core/arrays/categorical.py
max
Adirio/pandas
python
def max(self, numeric_only=None, **kwargs): ' The maximum value of the object.\n\n Only ordered `Categoricals` have a maximum!\n\n Raises\n ------\n TypeError\n If the `Categorical` is not `ordered`.\n\n Returns\n -------\n max : the maximum of this `Categ...
def mode(self, dropna=True): "\n Returns the mode(s) of the Categorical.\n\n Always returns `Categorical` even if only one value.\n\n Parameters\n ----------\n dropna : boolean, default True\n Don't consider counts of NaN/NaT.\n\n .. versionadded:: 0.24.0\n\n...
2,182,157,549,901,241,900
Returns the mode(s) of the Categorical. Always returns `Categorical` even if only one value. Parameters ---------- dropna : boolean, default True Don't consider counts of NaN/NaT. .. versionadded:: 0.24.0 Returns ------- modes : `Categorical` (sorted)
pandas/core/arrays/categorical.py
mode
Adirio/pandas
python
def mode(self, dropna=True): "\n Returns the mode(s) of the Categorical.\n\n Always returns `Categorical` even if only one value.\n\n Parameters\n ----------\n dropna : boolean, default True\n Don't consider counts of NaN/NaT.\n\n .. versionadded:: 0.24.0\n\n...
def unique(self): "\n Return the ``Categorical`` which ``categories`` and ``codes`` are\n unique. Unused categories are NOT returned.\n\n - unordered category: values and categories are sorted by appearance\n order.\n - ordered category: values are sorted by appearance order, ca...
1,525,540,672,474,470,100
Return the ``Categorical`` which ``categories`` and ``codes`` are unique. Unused categories are NOT returned. - unordered category: values and categories are sorted by appearance order. - ordered category: values are sorted by appearance order, categories keeps existing order. Returns ------- unique values : ``Ca...
pandas/core/arrays/categorical.py
unique
Adirio/pandas
python
def unique(self): "\n Return the ``Categorical`` which ``categories`` and ``codes`` are\n unique. Unused categories are NOT returned.\n\n - unordered category: values and categories are sorted by appearance\n order.\n - ordered category: values are sorted by appearance order, ca...
def equals(self, other): '\n Returns True if categorical arrays are equal.\n\n Parameters\n ----------\n other : `Categorical`\n\n Returns\n -------\n are_equal : boolean\n ' if self.is_dtype_equal(other): if self.categories.equals(other.categories...
2,929,335,446,468,426,000
Returns True if categorical arrays are equal. Parameters ---------- other : `Categorical` Returns ------- are_equal : boolean
pandas/core/arrays/categorical.py
equals
Adirio/pandas
python
def equals(self, other): '\n Returns True if categorical arrays are equal.\n\n Parameters\n ----------\n other : `Categorical`\n\n Returns\n -------\n are_equal : boolean\n ' if self.is_dtype_equal(other): if self.categories.equals(other.categories...
def is_dtype_equal(self, other): '\n Returns True if categoricals are the same dtype\n same categories, and same ordered\n\n Parameters\n ----------\n other : Categorical\n\n Returns\n -------\n are_equal : boolean\n ' try: return (hash(se...
-2,454,401,285,141,445,600
Returns True if categoricals are the same dtype same categories, and same ordered Parameters ---------- other : Categorical Returns ------- are_equal : boolean
pandas/core/arrays/categorical.py
is_dtype_equal
Adirio/pandas
python
def is_dtype_equal(self, other): '\n Returns True if categoricals are the same dtype\n same categories, and same ordered\n\n Parameters\n ----------\n other : Categorical\n\n Returns\n -------\n are_equal : boolean\n ' try: return (hash(se...
def describe(self): ' Describes this Categorical\n\n Returns\n -------\n description: `DataFrame`\n A dataframe with frequency and counts by category.\n ' counts = self.value_counts(dropna=False) freqs = (counts / float(counts.sum())) from pandas.core.reshape.conca...
4,132,264,890,513,181,000
Describes this Categorical Returns ------- description: `DataFrame` A dataframe with frequency and counts by category.
pandas/core/arrays/categorical.py
describe
Adirio/pandas
python
def describe(self): ' Describes this Categorical\n\n Returns\n -------\n description: `DataFrame`\n A dataframe with frequency and counts by category.\n ' counts = self.value_counts(dropna=False) freqs = (counts / float(counts.sum())) from pandas.core.reshape.conca...
def repeat(self, repeats, *args, **kwargs): '\n Repeat elements of a Categorical.\n\n See also\n --------\n numpy.ndarray.repeat\n\n ' nv.validate_repeat(args, kwargs) codes = self._codes.repeat(repeats) return self._constructor(values=codes, dtype=self.dtype, fastpath...
1,980,116,856,874,389,800
Repeat elements of a Categorical. See also -------- numpy.ndarray.repeat
pandas/core/arrays/categorical.py
repeat
Adirio/pandas
python
def repeat(self, repeats, *args, **kwargs): '\n Repeat elements of a Categorical.\n\n See also\n --------\n numpy.ndarray.repeat\n\n ' nv.validate_repeat(args, kwargs) codes = self._codes.repeat(repeats) return self._constructor(values=codes, dtype=self.dtype, fastpath...
def isin(self, values): "\n Check whether `values` are contained in Categorical.\n\n Return a boolean NumPy Array showing whether each element in\n the Categorical matches an element in the passed sequence of\n `values` exactly.\n\n Parameters\n ----------\n values :...
7,898,877,785,712,441,000
Check whether `values` are contained in Categorical. Return a boolean NumPy Array showing whether each element in the Categorical matches an element in the passed sequence of `values` exactly. Parameters ---------- values : set or list-like The sequence of values to test. Passing in a single string will raise...
pandas/core/arrays/categorical.py
isin
Adirio/pandas
python
def isin(self, values): "\n Check whether `values` are contained in Categorical.\n\n Return a boolean NumPy Array showing whether each element in\n the Categorical matches an element in the passed sequence of\n `values` exactly.\n\n Parameters\n ----------\n values :...
def submit(self, request, transaction, mobile: str=None, valid_card_number: str=None, callback: str=None): "Submits a transaction to Pay.ir.\n\n When called, the method submits the necessary information about the transaction to Pay.ir and returns a\n HttpResponseRedirect object that can redirect the u...
-8,579,580,414,340,304,000
Submits a transaction to Pay.ir. When called, the method submits the necessary information about the transaction to Pay.ir and returns a HttpResponseRedirect object that can redirect the user to the gateway, if nothing goes wrong. In case of an error, a GatewayError is raised, containing the error_code and error_messa...
payir/models.py
submit
farahmand-m/django-payir
python
def submit(self, request, transaction, mobile: str=None, valid_card_number: str=None, callback: str=None): "Submits a transaction to Pay.ir.\n\n When called, the method submits the necessary information about the transaction to Pay.ir and returns a\n HttpResponseRedirect object that can redirect the u...
def create_and_submit(self, request, account, amount: int, mobile: str=None, valid_card_number: str=None, callback: str=None): "Creates a transaction object and submits the transaction to Pay.ir.\n\n When called, the method submits the necessary information about the transaction to Pay.ir and returns a\n ...
-2,672,328,821,681,613,000
Creates a transaction object and submits the transaction to Pay.ir. When called, the method submits the necessary information about the transaction to Pay.ir and returns a HttpResponseRedirect object that can redirect the user to the gateway, if nothing goes wrong. In case of an error, a GatewayError is raised, contai...
payir/models.py
create_and_submit
farahmand-m/django-payir
python
def create_and_submit(self, request, account, amount: int, mobile: str=None, valid_card_number: str=None, callback: str=None): "Creates a transaction object and submits the transaction to Pay.ir.\n\n When called, the method submits the necessary information about the transaction to Pay.ir and returns a\n ...
def verify(self, transaction): "Verifies the transaction with Pay.ir.\n\n When a transaction returns with status '1', it must be verified with Pay.ir. Otherwise, it will be returned to\n the payer's bank account in 30 minutes. The method returns the updated transaction object and a boolean value.\n ...
-1,236,591,773,615,743,000
Verifies the transaction with Pay.ir. When a transaction returns with status '1', it must be verified with Pay.ir. Otherwise, it will be returned to the payer's bank account in 30 minutes. The method returns the updated transaction object and a boolean value. The boolean value would be True if the `verified` flag of t...
payir/models.py
verify
farahmand-m/django-payir
python
def verify(self, transaction): "Verifies the transaction with Pay.ir.\n\n When a transaction returns with status '1', it must be verified with Pay.ir. Otherwise, it will be returned to\n the payer's bank account in 30 minutes. The method returns the updated transaction object and a boolean value.\n ...
def find_and_verify(self, token: str): "Finds a transaction with a matching token value and verifies it with Pay.ir.\n\n When a transaction returns with status '1', it must be verified with Pay.ir. Otherwise, it will be returned to\n the payer's bank account in 30 minutes. The method returns the updat...
7,657,918,661,398,567,000
Finds a transaction with a matching token value and verifies it with Pay.ir. When a transaction returns with status '1', it must be verified with Pay.ir. Otherwise, it will be returned to the payer's bank account in 30 minutes. The method returns the updated transaction object and a boolean value. The boolean value wo...
payir/models.py
find_and_verify
farahmand-m/django-payir
python
def find_and_verify(self, token: str): "Finds a transaction with a matching token value and verifies it with Pay.ir.\n\n When a transaction returns with status '1', it must be verified with Pay.ir. Otherwise, it will be returned to\n the payer's bank account in 30 minutes. The method returns the updat...
async def test_hls_stream(hass, hass_client, stream_worker_sync): '\n Test hls stream.\n\n Purposefully not mocking anything here to test full\n integration with the stream component.\n ' (await async_setup_component(hass, 'stream', {'stream': {}})) stream_worker_sync.pause() source = genera...
8,384,524,558,263,135,000
Test hls stream. Purposefully not mocking anything here to test full integration with the stream component.
tests/components/stream/test_hls.py
test_hls_stream
BoresXP/core
python
async def test_hls_stream(hass, hass_client, stream_worker_sync): '\n Test hls stream.\n\n Purposefully not mocking anything here to test full\n integration with the stream component.\n ' (await async_setup_component(hass, 'stream', {'stream': {}})) stream_worker_sync.pause() source = genera...
async def test_stream_timeout(hass, hass_client, stream_worker_sync): 'Test hls stream timeout.' (await async_setup_component(hass, 'stream', {'stream': {}})) stream_worker_sync.pause() source = generate_h264_video() stream = preload_stream(hass, source) stream.add_provider('hls') url = requ...
1,161,223,324,562,560,800
Test hls stream timeout.
tests/components/stream/test_hls.py
test_stream_timeout
BoresXP/core
python
async def test_stream_timeout(hass, hass_client, stream_worker_sync): (await async_setup_component(hass, 'stream', {'stream': {}})) stream_worker_sync.pause() source = generate_h264_video() stream = preload_stream(hass, source) stream.add_provider('hls') url = request_stream(hass, source) ...
async def test_stream_ended(hass, stream_worker_sync): 'Test hls stream packets ended.' (await async_setup_component(hass, 'stream', {'stream': {}})) stream_worker_sync.pause() source = generate_h264_video() stream = preload_stream(hass, source) track = stream.add_provider('hls') request_str...
-5,946,003,191,077,505,000
Test hls stream packets ended.
tests/components/stream/test_hls.py
test_stream_ended
BoresXP/core
python
async def test_stream_ended(hass, stream_worker_sync): (await async_setup_component(hass, 'stream', {'stream': {}})) stream_worker_sync.pause() source = generate_h264_video() stream = preload_stream(hass, source) track = stream.add_provider('hls') request_stream(hass, source) while True...
async def test_stream_keepalive(hass): 'Test hls stream retries the stream when keepalive=True.' (await async_setup_component(hass, 'stream', {'stream': {}})) source = 'test_stream_keepalive_source' stream = preload_stream(hass, source) track = stream.add_provider('hls') track.num_segments = 2 ...
5,628,805,682,028,231,000
Test hls stream retries the stream when keepalive=True.
tests/components/stream/test_hls.py
test_stream_keepalive
BoresXP/core
python
async def test_stream_keepalive(hass): (await async_setup_component(hass, 'stream', {'stream': {}})) source = 'test_stream_keepalive_source' stream = preload_stream(hass, source) track = stream.add_provider('hls') track.num_segments = 2 cur_time = 0 def time_side_effect(): nonl...
def split(self, batch_size, data): 'TODO: Annotation\n params:\n batch_size: int\n data: [B, x]\n ' if self.memory_net.use_rnn: data = tf.reshape(data, [batch_size, (- 1), tf.shape(data)[(- 1)]]) (d, d_) = (data[:, :(- 1)], data[:, 1:]) (d, d_) = (tf.r...
-1,039,740,822,517,881,500
TODO: Annotation params: batch_size: int data: [B, x]
rls/utils/build_networks.py
split
kiminh/RLs
python
def split(self, batch_size, data): 'TODO: Annotation\n params:\n batch_size: int\n data: [B, x]\n ' if self.memory_net.use_rnn: data = tf.reshape(data, [batch_size, (- 1), tf.shape(data)[(- 1)]]) (d, d_) = (data[:, :(- 1)], data[:, 1:]) (d, d_) = (tf.r...
def __call__(self, s, visual_s, cell_state, *, need_split=False): '\n params:\n s: [B*T, x]\n visual_s: [B*T, y]\n cell_state: Tuple([B, z],)\n return:\n feat: [B, a]\n cell_state: Tuple([B, z],)\n ' batch_size = tf.shape(s)[0] if s...
170,773,381,567,324,300
params: s: [B*T, x] visual_s: [B*T, y] cell_state: Tuple([B, z],) return: feat: [B, a] cell_state: Tuple([B, z],)
rls/utils/build_networks.py
__call__
kiminh/RLs
python
def __call__(self, s, visual_s, cell_state, *, need_split=False): '\n params:\n s: [B*T, x]\n visual_s: [B*T, y]\n cell_state: Tuple([B, z],)\n return:\n feat: [B, a]\n cell_state: Tuple([B, z],)\n ' batch_size = tf.shape(s)[0] if s...
def get_vis_feature(self, visual_s): '\n params:\n visual_s: [B, N, H, W, C]\n return:\n feat: [B, x]\n ' viss = [visual_s[:, i] for i in range(visual_s.shape[1])] return self.visual_net(*viss)
-8,670,938,418,787,934,000
params: visual_s: [B, N, H, W, C] return: feat: [B, x]
rls/utils/build_networks.py
get_vis_feature
kiminh/RLs
python
def get_vis_feature(self, visual_s): '\n params:\n visual_s: [B, N, H, W, C]\n return:\n feat: [B, x]\n ' viss = [visual_s[:, i] for i in range(visual_s.shape[1])] return self.visual_net(*viss)
def get_vec_feature(self, s): '\n params:\n s: [B, x]\n return:\n feat: [B, y]\n ' return self.vector_net(s)
1,844,289,576,694,748,700
params: s: [B, x] return: feat: [B, y]
rls/utils/build_networks.py
get_vec_feature
kiminh/RLs
python
def get_vec_feature(self, s): '\n params:\n s: [B, x]\n return:\n feat: [B, y]\n ' return self.vector_net(s)
def get_encoder_feature(self, s, visual_s): '\n params:\n s: [B, x]\n visual_s: [B, y]\n return:\n feat: [B, z]\n ' if (self.vector_net.use_vector and self.visual_net.use_visual): feat = self.get_vec_feature(s) vis_feat = self.get_vis_feature...
4,595,706,411,565,255,000
params: s: [B, x] visual_s: [B, y] return: feat: [B, z]
rls/utils/build_networks.py
get_encoder_feature
kiminh/RLs
python
def get_encoder_feature(self, s, visual_s): '\n params:\n s: [B, x]\n visual_s: [B, y]\n return:\n feat: [B, z]\n ' if (self.vector_net.use_vector and self.visual_net.use_visual): feat = self.get_vec_feature(s) vis_feat = self.get_vis_feature...
@property def _policy_models(self): '重载' models = super()._policy_models models.update({((self.name + '/') + 'policy_net'): self.policy_net}) return models
-3,166,260,519,035,728,000
重载
rls/utils/build_networks.py
_policy_models
kiminh/RLs
python
@property def _policy_models(self): models = super()._policy_models models.update({((self.name + '/') + 'policy_net'): self.policy_net}) return models
def update_bid(self, bid_basket_item_id, amount): '\n Update amount of bid. Delete bid if amount is 0.\n ' try: amount = Decimal(amount) except Exception as e: amount = Decimal('0') bid_basket_item = self.bids.get(pk=bid_basket_item_id) if (not bid_basket_item.is_locked...
-4,093,918,117,560,578,000
Update amount of bid. Delete bid if amount is 0.
auction/models/bases.py
update_bid
JohnRomanski/django-auction
python
def update_bid(self, bid_basket_item_id, amount): '\n \n ' try: amount = Decimal(amount) except Exception as e: amount = Decimal('0') bid_basket_item = self.bids.get(pk=bid_basket_item_id) if (not bid_basket_item.is_locked()): if (amount == 0): bid_b...
def delete_bid(self, bid_basket_item_id): '\n Delete a single item from bid basket.\n ' bid_basket_item = self.bids.get(pk=bid_basket_item_id) if (not bid_basket_item.is_locked()): bid_basket_item.delete() return bid_basket_item
8,172,840,115,005,275,000
Delete a single item from bid basket.
auction/models/bases.py
delete_bid
JohnRomanski/django-auction
python
def delete_bid(self, bid_basket_item_id): '\n \n ' bid_basket_item = self.bids.get(pk=bid_basket_item_id) if (not bid_basket_item.is_locked()): bid_basket_item.delete() return bid_basket_item
def empty(self): '\n Remove all bids from bid basket.\n ' if self.pk: bids = self.bids.all() for bid in bids: if (not bid.is_locked()): bid.delete()
-8,989,054,926,361,665,000
Remove all bids from bid basket.
auction/models/bases.py
empty
JohnRomanski/django-auction
python
def empty(self): '\n \n ' if self.pk: bids = self.bids.all() for bid in bids: if (not bid.is_locked()): bid.delete()
@property def bids(self): '\n Used as accessor for abstract related (BaseBidItem.bid_items).\n\n If you override BaseBidItem and use a label other than "auction"\n you will also need to set AUCTION_BIDBASKET_BIDS_RELATED_NAME.\n Example: foo_biditem_related\n (where your ...
-5,169,305,097,375,760,000
Used as accessor for abstract related (BaseBidItem.bid_items). If you override BaseBidItem and use a label other than "auction" you will also need to set AUCTION_BIDBASKET_BIDS_RELATED_NAME. Example: foo_biditem_related (where your label is "foo" and your model is "BidItem")
auction/models/bases.py
bids
JohnRomanski/django-auction
python
@property def bids(self): '\n Used as accessor for abstract related (BaseBidItem.bid_items).\n\n If you override BaseBidItem and use a label other than "auction"\n you will also need to set AUCTION_BIDBASKET_BIDS_RELATED_NAME.\n Example: foo_biditem_related\n (where your ...
@property def total_bids(self): '\n Returns total bids in basket.\n ' return len(self.bids.all())
-476,392,268,769,202,370
Returns total bids in basket.
auction/models/bases.py
total_bids
JohnRomanski/django-auction
python
@property def total_bids(self): '\n \n ' return len(self.bids.all())
@property def is_locked(self): '\n This property is meant to be overwritten with your own logic. Bid baskets\n check this method to find out if a bid can be manipulated.\n ' import auction.utils.generic now = auction.utils.generic.get_current_time() return (self.content_object.end_d...
4,951,673,990,888,619,000
This property is meant to be overwritten with your own logic. Bid baskets check this method to find out if a bid can be manipulated.
auction/models/bases.py
is_locked
JohnRomanski/django-auction
python
@property def is_locked(self): '\n This property is meant to be overwritten with your own logic. Bid baskets\n check this method to find out if a bid can be manipulated.\n ' import auction.utils.generic now = auction.utils.generic.get_current_time() return (self.content_object.end_d...
def __init__(self, session, object_factory, request_validator): 'Initialize a new Clients\n object with the provided RestSession.\n\n Args:\n session(RestSession): The RESTful session object to be used for\n API calls to the DNA Center service.\n\n Raises:\n ...
9,048,934,399,632,874,000
Initialize a new Clients object with the provided RestSession. Args: session(RestSession): The RESTful session object to be used for API calls to the DNA Center service. Raises: TypeError: If the parameter types are incorrect.
dnacentersdk/api/v1_3_1/clients.py
__init__
cisco-en-programmability/dnacentersdk
python
def __init__(self, session, object_factory, request_validator): 'Initialize a new Clients\n object with the provided RestSession.\n\n Args:\n session(RestSession): The RESTful session object to be used for\n API calls to the DNA Center service.\n\n Raises:\n ...
def get_client_enrichment_details(self, headers=None, **request_parameters): "Enriches a given network End User context (a network user-id or\n end user's device Mac Address) with details about the\n user, the devices that the user is connected to and the\n assurance issues that the user is imp...
-7,564,726,252,209,738,000
Enriches a given network End User context (a network user-id or end user's device Mac Address) with details about the user, the devices that the user is connected to and the assurance issues that the user is impacted by. Args: headers(dict): Dictionary of HTTP Headers to send with the Request . **reque...
dnacentersdk/api/v1_3_1/clients.py
get_client_enrichment_details
cisco-en-programmability/dnacentersdk
python
def get_client_enrichment_details(self, headers=None, **request_parameters): "Enriches a given network End User context (a network user-id or\n end user's device Mac Address) with details about the\n user, the devices that the user is connected to and the\n assurance issues that the user is imp...
def get_overall_client_health(self, timestamp=None, headers=None, **request_parameters): "Returns Overall Client Health information by Client type (Wired\n and Wireless) for any given point of time.\n\n Args:\n timestamp(basestring, int): Epoch time(in milliseconds) when the Client health d...
-784,818,564,822,489,000
Returns Overall Client Health information by Client type (Wired and Wireless) for any given point of time. Args: timestamp(basestring, int): Epoch time(in milliseconds) when the Client health data is required. headers(dict): Dictionary of HTTP Headers to send with the Request . **request_parameters...
dnacentersdk/api/v1_3_1/clients.py
get_overall_client_health
cisco-en-programmability/dnacentersdk
python
def get_overall_client_health(self, timestamp=None, headers=None, **request_parameters): "Returns Overall Client Health information by Client type (Wired\n and Wireless) for any given point of time.\n\n Args:\n timestamp(basestring, int): Epoch time(in milliseconds) when the Client health d...
def get_client_detail(self, mac_address, timestamp=None, headers=None, **request_parameters): "Returns detailed Client information retrieved by Mac Address for\n any given point of time. .\n\n Args:\n timestamp(basestring, int): Epoch time(in milliseconds) when the Client health data is req...
5,349,272,156,075,314,000
Returns detailed Client information retrieved by Mac Address for any given point of time. . Args: timestamp(basestring, int): Epoch time(in milliseconds) when the Client health data is required. mac_address(basestring): MAC Address of the client. headers(dict): Dictionary of HTTP Headers to send with the R...
dnacentersdk/api/v1_3_1/clients.py
get_client_detail
cisco-en-programmability/dnacentersdk
python
def get_client_detail(self, mac_address, timestamp=None, headers=None, **request_parameters): "Returns detailed Client information retrieved by Mac Address for\n any given point of time. .\n\n Args:\n timestamp(basestring, int): Epoch time(in milliseconds) when the Client health data is req...
@property def download_url(self): '\n the URL at which the file can be downloaded. This is only valid for a short time, so should not be cached.\n ' file_url = ('/files/%s' % self.id) rsp = self.session.get(file_url, allow_redirects=False) return rsp.headers['location']
-3,402,634,989,467,524,000
the URL at which the file can be downloaded. This is only valid for a short time, so should not be cached.
yandeley/models/files.py
download_url
shuichiro-makigaki/yandeley-python-sdk
python
@property def download_url(self): '\n \n ' file_url = ('/files/%s' % self.id) rsp = self.session.get(file_url, allow_redirects=False) return rsp.headers['location']
def document(self, view=None): '\n :param view: document view to return.\n :return: a :class:`UserDocument <yandeley.models.documents.UserDocument>` or\n :class:`CatalogDocument <yandeley.models.catalog.CatalogDocument>`, depending on which the document is\n attached to...
-7,163,505,978,791,217,000
:param view: document view to return. :return: a :class:`UserDocument <yandeley.models.documents.UserDocument>` or :class:`CatalogDocument <yandeley.models.catalog.CatalogDocument>`, depending on which the document is attached to.
yandeley/models/files.py
document
shuichiro-makigaki/yandeley-python-sdk
python
def document(self, view=None): '\n :param view: document view to return.\n :return: a :class:`UserDocument <yandeley.models.documents.UserDocument>` or\n :class:`CatalogDocument <yandeley.models.catalog.CatalogDocument>`, depending on which the document is\n attached to...
def download(self, directory): '\n Downloads the file.\n\n :param directory: the directory to download the file to. This must exist.\n :return: the path to the downloaded file.\n ' rsp = self.session.get(('/files/%s' % self.id), stream=True) filename = self.filename_regex.search...
-7,057,783,901,090,330,000
Downloads the file. :param directory: the directory to download the file to. This must exist. :return: the path to the downloaded file.
yandeley/models/files.py
download
shuichiro-makigaki/yandeley-python-sdk
python
def download(self, directory): '\n Downloads the file.\n\n :param directory: the directory to download the file to. This must exist.\n :return: the path to the downloaded file.\n ' rsp = self.session.get(('/files/%s' % self.id), stream=True) filename = self.filename_regex.search...
def delete(self): '\n Deletes the file.\n ' self.session.delete(('/files/%s' % self.id))
-7,918,245,386,690,900,000
Deletes the file.
yandeley/models/files.py
delete
shuichiro-makigaki/yandeley-python-sdk
python
def delete(self): '\n \n ' self.session.delete(('/files/%s' % self.id))
def add_sticky_note(self, text, x_position, y_position, page_number): '\n Adds a sticky note to this file.\n\n :param text: the text of the sticky_note.\n :param x_position: the x position on the file of the sticky_note.\n :param y_position: the y position on the file of the stick_note.\...
-6,243,088,608,459,309,000
Adds a sticky note to this file. :param text: the text of the sticky_note. :param x_position: the x position on the file of the sticky_note. :param y_position: the y position on the file of the stick_note. :param page_number: the page_number on the file of the sticky_note. :return: a :class:`Annotation <yandeley.model...
yandeley/models/files.py
add_sticky_note
shuichiro-makigaki/yandeley-python-sdk
python
def add_sticky_note(self, text, x_position, y_position, page_number): '\n Adds a sticky note to this file.\n\n :param text: the text of the sticky_note.\n :param x_position: the x position on the file of the sticky_note.\n :param y_position: the y position on the file of the stick_note.\...
def add_highlight(self, bounding_boxes, color): '\n Adds a highlight to this file.\n\n :param bounding_boxes: the area the highlight covers on the file.\n :param color: the color of the highlight.\n :return: a :class:`Annotation <yandeley.models.annotations.Annotation>`.\n ' a...
-813,811,400,724,956,800
Adds a highlight to this file. :param bounding_boxes: the area the highlight covers on the file. :param color: the color of the highlight. :return: a :class:`Annotation <yandeley.models.annotations.Annotation>`.
yandeley/models/files.py
add_highlight
shuichiro-makigaki/yandeley-python-sdk
python
def add_highlight(self, bounding_boxes, color): '\n Adds a highlight to this file.\n\n :param bounding_boxes: the area the highlight covers on the file.\n :param color: the color of the highlight.\n :return: a :class:`Annotation <yandeley.models.annotations.Annotation>`.\n ' a...
def _middle(values): 'Lower bound of median, without using numpy (heavy reqs)' n = len(values) is_odd = (n % 2) middle_idx = (int(((n + is_odd) / 2)) - 1) return sorted(values)[middle_idx]
958,713,930,854,413,800
Lower bound of median, without using numpy (heavy reqs)
nuts_finder/nuts_finder.py
_middle
nestauk/nuts_finder
python
def _middle(values): n = len(values) is_odd = (n % 2) middle_idx = (int(((n + is_odd) / 2)) - 1) return sorted(values)[middle_idx]
def _setattr(obj, value, value_name, regex, selector): 'Either apply setattr on `obj` with value `value`, if `value` is not None, otherwise\n select a `value` from the available range of allowed values, selected by a custom `selector`\n function.\n\n Args:\n obj: An object on which to run setattr\n ...
6,017,101,556,157,815,000
Either apply setattr on `obj` with value `value`, if `value` is not None, otherwise select a `value` from the available range of allowed values, selected by a custom `selector` function. Args: obj: An object on which to run setattr value: A value which if not None will be set as an attribute of object valu...
nuts_finder/nuts_finder.py
_setattr
nestauk/nuts_finder
python
def _setattr(obj, value, value_name, regex, selector): 'Either apply setattr on `obj` with value `value`, if `value` is not None, otherwise\n select a `value` from the available range of allowed values, selected by a custom `selector`\n function.\n\n Args:\n obj: An object on which to run setattr\n ...
@lru_cache() def _get_available(regex): 'Use the provided regex to find allowed values on the NUTS website.' r = requests.get(TOP_URL, verify=True) values = set((int(yr) for yr in re.findall(regex, r.text))) return values
-3,870,046,505,436,721,000
Use the provided regex to find allowed values on the NUTS website.
nuts_finder/nuts_finder.py
_get_available
nestauk/nuts_finder
python
@lru_cache() def _get_available(regex): r = requests.get(TOP_URL, verify=True) values = set((int(yr) for yr in re.findall(regex, r.text))) return values
def __init__(self, year=None, scale=None): '\n Args:\n year (int): If provided, NUTS regions for this year will be used (if available)\n scale (int): If provided, NUTS regions at this resolution will be used (if available)\n ' self.years = list(_get_available(YEAR_REGEX)) ...
3,857,591,972,723,282,000
Args: year (int): If provided, NUTS regions for this year will be used (if available) scale (int): If provided, NUTS regions at this resolution will be used (if available)
nuts_finder/nuts_finder.py
__init__
nestauk/nuts_finder
python
def __init__(self, year=None, scale=None): '\n Args:\n year (int): If provided, NUTS regions for this year will be used (if available)\n scale (int): If provided, NUTS regions at this resolution will be used (if available)\n ' self.years = list(_get_available(YEAR_REGEX)) ...
def _get_shapes(self): 'Load the shape files for the given year and scale' scale = str(self.scale).zfill(2) filename = NESTED_FILE.format(year=self.year, scale=scale) url = ZIP_URL.format(year=self.year, scale=scale) r = requests.get(url, verify=True) r.raise_for_status() try: with Z...
1,341,815,081,636,938,800
Load the shape files for the given year and scale
nuts_finder/nuts_finder.py
_get_shapes
nestauk/nuts_finder
python
def _get_shapes(self): scale = str(self.scale).zfill(2) filename = NESTED_FILE.format(year=self.year, scale=scale) url = ZIP_URL.format(year=self.year, scale=scale) r = requests.get(url, verify=True) r.raise_for_status() try: with ZipFile(BytesIO(r.content)) as zipfile: ...
def find(self, lat, lon): 'Find every NUTS region for this lat, lon' p = geometry.Point(lon, lat) nuts = [] for region in self.shapes['features']: s = geometry.shape(region['geometry']) if s.contains(p): nuts.append(region['properties']) return sorted(nuts, key=(lambda ro...
4,858,413,133,958,075,000
Find every NUTS region for this lat, lon
nuts_finder/nuts_finder.py
find
nestauk/nuts_finder
python
def find(self, lat, lon): p = geometry.Point(lon, lat) nuts = [] for region in self.shapes['features']: s = geometry.shape(region['geometry']) if s.contains(p): nuts.append(region['properties']) return sorted(nuts, key=(lambda row: row['LEVL_CODE']))
def _pad_tensors_to_same_length(x, y): 'Pad x and y so that the results have the same length (second dimension).' with tf.name_scope('pad_to_same_length'): x_length = tf.shape(x)[1] y_length = tf.shape(y)[1] max_length = tf.maximum(x_length, y_length) x = tf.pad(x, [[0, 0], [0, (...
6,004,746,840,324,201,000
Pad x and y so that the results have the same length (second dimension).
official/nlp/transformer/utils/metrics.py
_pad_tensors_to_same_length
1110sillabo/models
python
def _pad_tensors_to_same_length(x, y): with tf.name_scope('pad_to_same_length'): x_length = tf.shape(x)[1] y_length = tf.shape(y)[1] max_length = tf.maximum(x_length, y_length) x = tf.pad(x, [[0, 0], [0, (max_length - x_length)], [0, 0]]) y = tf.pad(y, [[0, 0], [0, (max_...
def padded_cross_entropy_loss(logits, labels, smoothing, vocab_size): 'Calculate cross entropy loss while ignoring padding.\n\n Args:\n logits: Tensor of size [batch_size, length_logits, vocab_size]\n labels: Tensor of size [batch_size, length_labels]\n smoothing: Label smoothing constant, used to determi...
3,564,442,464,147,787,300
Calculate cross entropy loss while ignoring padding. Args: logits: Tensor of size [batch_size, length_logits, vocab_size] labels: Tensor of size [batch_size, length_labels] smoothing: Label smoothing constant, used to determine the on and off values vocab_size: int size of the vocabulary Returns: Returns the...
official/nlp/transformer/utils/metrics.py
padded_cross_entropy_loss
1110sillabo/models
python
def padded_cross_entropy_loss(logits, labels, smoothing, vocab_size): 'Calculate cross entropy loss while ignoring padding.\n\n Args:\n logits: Tensor of size [batch_size, length_logits, vocab_size]\n labels: Tensor of size [batch_size, length_labels]\n smoothing: Label smoothing constant, used to determi...
def _convert_to_eval_metric(metric_fn): "Wrap a metric fn that returns scores and weights as an eval metric fn.\n\n The input metric_fn returns values for the current batch. The wrapper\n aggregates the return values collected over all of the batches evaluated.\n\n Args:\n metric_fn: function that returns sco...
-2,359,971,840,431,848,000
Wrap a metric fn that returns scores and weights as an eval metric fn. The input metric_fn returns values for the current batch. The wrapper aggregates the return values collected over all of the batches evaluated. Args: metric_fn: function that returns scores and weights for the current batch's logits and pred...
official/nlp/transformer/utils/metrics.py
_convert_to_eval_metric
1110sillabo/models
python
def _convert_to_eval_metric(metric_fn): "Wrap a metric fn that returns scores and weights as an eval metric fn.\n\n The input metric_fn returns values for the current batch. The wrapper\n aggregates the return values collected over all of the batches evaluated.\n\n Args:\n metric_fn: function that returns sco...
def get_eval_metrics(logits, labels, params): 'Return dictionary of model evaluation metrics.' metrics = {'accuracy': _convert_to_eval_metric(padded_accuracy)(logits, labels), 'accuracy_top5': _convert_to_eval_metric(padded_accuracy_top5)(logits, labels), 'accuracy_per_sequence': _convert_to_eval_metric(padded_...
3,380,199,622,328,414,000
Return dictionary of model evaluation metrics.
official/nlp/transformer/utils/metrics.py
get_eval_metrics
1110sillabo/models
python
def get_eval_metrics(logits, labels, params): metrics = {'accuracy': _convert_to_eval_metric(padded_accuracy)(logits, labels), 'accuracy_top5': _convert_to_eval_metric(padded_accuracy_top5)(logits, labels), 'accuracy_per_sequence': _convert_to_eval_metric(padded_sequence_accuracy)(logits, labels), 'neg_log_per...
def padded_accuracy(logits, labels): 'Percentage of times that predictions matches labels on non-0s.' with tf.variable_scope('padded_accuracy', values=[logits, labels]): (logits, labels) = _pad_tensors_to_same_length(logits, labels) weights = tf.to_float(tf.not_equal(labels, 0)) outputs ...
8,946,189,065,367,476,000
Percentage of times that predictions matches labels on non-0s.
official/nlp/transformer/utils/metrics.py
padded_accuracy
1110sillabo/models
python
def padded_accuracy(logits, labels): with tf.variable_scope('padded_accuracy', values=[logits, labels]): (logits, labels) = _pad_tensors_to_same_length(logits, labels) weights = tf.to_float(tf.not_equal(labels, 0)) outputs = tf.to_int32(tf.argmax(logits, axis=(- 1))) padded_labe...
def padded_accuracy_topk(logits, labels, k): 'Percentage of times that top-k predictions matches labels on non-0s.' with tf.variable_scope('padded_accuracy_topk', values=[logits, labels]): (logits, labels) = _pad_tensors_to_same_length(logits, labels) weights = tf.to_float(tf.not_equal(labels, 0...
4,883,132,312,032,429,000
Percentage of times that top-k predictions matches labels on non-0s.
official/nlp/transformer/utils/metrics.py
padded_accuracy_topk
1110sillabo/models
python
def padded_accuracy_topk(logits, labels, k): with tf.variable_scope('padded_accuracy_topk', values=[logits, labels]): (logits, labels) = _pad_tensors_to_same_length(logits, labels) weights = tf.to_float(tf.not_equal(labels, 0)) effective_k = tf.minimum(k, tf.shape(logits)[(- 1)]) ...
def padded_sequence_accuracy(logits, labels): 'Percentage of times that predictions matches labels everywhere (non-0).' with tf.variable_scope('padded_sequence_accuracy', values=[logits, labels]): (logits, labels) = _pad_tensors_to_same_length(logits, labels) weights = tf.to_float(tf.not_equal(l...
-1,587,949,503,459,970,300
Percentage of times that predictions matches labels everywhere (non-0).
official/nlp/transformer/utils/metrics.py
padded_sequence_accuracy
1110sillabo/models
python
def padded_sequence_accuracy(logits, labels): with tf.variable_scope('padded_sequence_accuracy', values=[logits, labels]): (logits, labels) = _pad_tensors_to_same_length(logits, labels) weights = tf.to_float(tf.not_equal(labels, 0)) outputs = tf.to_int32(tf.argmax(logits, axis=(- 1))) ...
def padded_neg_log_perplexity(logits, labels, vocab_size): 'Average log-perplexity excluding padding 0s. No smoothing.' (num, den) = padded_cross_entropy_loss(logits, labels, 0, vocab_size) return ((- num), den)
4,644,916,350,470,578,000
Average log-perplexity excluding padding 0s. No smoothing.
official/nlp/transformer/utils/metrics.py
padded_neg_log_perplexity
1110sillabo/models
python
def padded_neg_log_perplexity(logits, labels, vocab_size): (num, den) = padded_cross_entropy_loss(logits, labels, 0, vocab_size) return ((- num), den)
def bleu_score(logits, labels): 'Approximate BLEU score computation between labels and predictions.\n\n An approximate BLEU scoring method since we do not glue word pieces or\n decode the ids and tokenize the output. By default, we use ngram order of 4\n and use brevity penalty. Also, this does not have beam sea...
292,391,744,416,105,400
Approximate BLEU score computation between labels and predictions. An approximate BLEU scoring method since we do not glue word pieces or decode the ids and tokenize the output. By default, we use ngram order of 4 and use brevity penalty. Also, this does not have beam search. Args: logits: Tensor of size [batch_siz...
official/nlp/transformer/utils/metrics.py
bleu_score
1110sillabo/models
python
def bleu_score(logits, labels): 'Approximate BLEU score computation between labels and predictions.\n\n An approximate BLEU scoring method since we do not glue word pieces or\n decode the ids and tokenize the output. By default, we use ngram order of 4\n and use brevity penalty. Also, this does not have beam sea...
def _get_ngrams_with_counter(segment, max_order): 'Extracts all n-grams up to a given maximum order from an input segment.\n\n Args:\n segment: text segment from which n-grams will be extracted.\n max_order: maximum length in tokens of the n-grams returned by this\n methods.\n\n Returns:\n The Cou...
1,716,925,804,233,848,000
Extracts all n-grams up to a given maximum order from an input segment. Args: segment: text segment from which n-grams will be extracted. max_order: maximum length in tokens of the n-grams returned by this methods. Returns: The Counter containing all n-grams upto max_order in segment with a count of how...
official/nlp/transformer/utils/metrics.py
_get_ngrams_with_counter
1110sillabo/models
python
def _get_ngrams_with_counter(segment, max_order): 'Extracts all n-grams up to a given maximum order from an input segment.\n\n Args:\n segment: text segment from which n-grams will be extracted.\n max_order: maximum length in tokens of the n-grams returned by this\n methods.\n\n Returns:\n The Cou...
def compute_bleu(reference_corpus, translation_corpus, max_order=4, use_bp=True): 'Computes BLEU score of translated segments against one or more references.\n\n Args:\n reference_corpus: list of references for each translation. Each\n reference should be tokenized into a list of tokens.\n translation...
8,272,636,851,736,137,000
Computes BLEU score of translated segments against one or more references. Args: reference_corpus: list of references for each translation. Each reference should be tokenized into a list of tokens. translation_corpus: list of translations to score. Each translation should be tokenized into a list of to...
official/nlp/transformer/utils/metrics.py
compute_bleu
1110sillabo/models
python
def compute_bleu(reference_corpus, translation_corpus, max_order=4, use_bp=True): 'Computes BLEU score of translated segments against one or more references.\n\n Args:\n reference_corpus: list of references for each translation. Each\n reference should be tokenized into a list of tokens.\n translation...
def rouge_2_fscore(logits, labels): 'ROUGE-2 F1 score computation between labels and predictions.\n\n This is an approximate ROUGE scoring method since we do not glue word pieces\n or decode the ids and tokenize the output.\n\n Args:\n logits: tensor, model predictions\n labels: tensor, gold output.\n\n R...
8,274,710,431,071,724,000
ROUGE-2 F1 score computation between labels and predictions. This is an approximate ROUGE scoring method since we do not glue word pieces or decode the ids and tokenize the output. Args: logits: tensor, model predictions labels: tensor, gold output. Returns: rouge2_fscore: approx rouge-2 f1 score.
official/nlp/transformer/utils/metrics.py
rouge_2_fscore
1110sillabo/models
python
def rouge_2_fscore(logits, labels): 'ROUGE-2 F1 score computation between labels and predictions.\n\n This is an approximate ROUGE scoring method since we do not glue word pieces\n or decode the ids and tokenize the output.\n\n Args:\n logits: tensor, model predictions\n labels: tensor, gold output.\n\n R...
def _get_ngrams(n, text): 'Calculates n-grams.\n\n Args:\n n: which n-grams to calculate\n text: An array of tokens\n\n Returns:\n A set of n-grams\n ' ngram_set = set() text_length = len(text) max_index_ngram_start = (text_length - n) for i in range((max_index_ngram_start + 1)): ...
2,263,363,960,569,367,600
Calculates n-grams. Args: n: which n-grams to calculate text: An array of tokens Returns: A set of n-grams
official/nlp/transformer/utils/metrics.py
_get_ngrams
1110sillabo/models
python
def _get_ngrams(n, text): 'Calculates n-grams.\n\n Args:\n n: which n-grams to calculate\n text: An array of tokens\n\n Returns:\n A set of n-grams\n ' ngram_set = set() text_length = len(text) max_index_ngram_start = (text_length - n) for i in range((max_index_ngram_start + 1)): ...
def rouge_n(eval_sentences, ref_sentences, n=2): 'Computes ROUGE-N f1 score of two text collections of sentences.\n\n Source: https://www.microsoft.com/en-us/research/publication/\n rouge-a-package-for-automatic-evaluation-of-summaries/\n\n Args:\n eval_sentences: Predicted sentences.\n ref_sentences: Sent...
-306,006,793,984,337,500
Computes ROUGE-N f1 score of two text collections of sentences. Source: https://www.microsoft.com/en-us/research/publication/ rouge-a-package-for-automatic-evaluation-of-summaries/ Args: eval_sentences: Predicted sentences. ref_sentences: Sentences from the reference set n: Size of ngram. Defaults to 2. Retur...
official/nlp/transformer/utils/metrics.py
rouge_n
1110sillabo/models
python
def rouge_n(eval_sentences, ref_sentences, n=2): 'Computes ROUGE-N f1 score of two text collections of sentences.\n\n Source: https://www.microsoft.com/en-us/research/publication/\n rouge-a-package-for-automatic-evaluation-of-summaries/\n\n Args:\n eval_sentences: Predicted sentences.\n ref_sentences: Sent...
def rouge_l_fscore(predictions, labels): 'ROUGE scores computation between labels and predictions.\n\n This is an approximate ROUGE scoring method since we do not glue word pieces\n or decode the ids and tokenize the output.\n\n Args:\n predictions: tensor, model predictions\n labels: tensor, gold output.\...
3,165,181,742,827,321,000
ROUGE scores computation between labels and predictions. This is an approximate ROUGE scoring method since we do not glue word pieces or decode the ids and tokenize the output. Args: predictions: tensor, model predictions labels: tensor, gold output. Returns: rouge_l_fscore: approx rouge-l f1 score.
official/nlp/transformer/utils/metrics.py
rouge_l_fscore
1110sillabo/models
python
def rouge_l_fscore(predictions, labels): 'ROUGE scores computation between labels and predictions.\n\n This is an approximate ROUGE scoring method since we do not glue word pieces\n or decode the ids and tokenize the output.\n\n Args:\n predictions: tensor, model predictions\n labels: tensor, gold output.\...
def rouge_l_sentence_level(eval_sentences, ref_sentences): 'Computes ROUGE-L (sentence level) of two collections of sentences.\n\n Source: https://www.microsoft.com/en-us/research/publication/\n rouge-a-package-for-automatic-evaluation-of-summaries/\n\n Calculated according to:\n R_lcs = LCS(X,Y)/m\n P_lcs = L...
-6,966,317,381,581,726,000
Computes ROUGE-L (sentence level) of two collections of sentences. Source: https://www.microsoft.com/en-us/research/publication/ rouge-a-package-for-automatic-evaluation-of-summaries/ Calculated according to: R_lcs = LCS(X,Y)/m P_lcs = LCS(X,Y)/n F_lcs = ((1 + beta^2)*R_lcs*P_lcs) / (R_lcs + (beta^2) * P_lcs) where:...
official/nlp/transformer/utils/metrics.py
rouge_l_sentence_level
1110sillabo/models
python
def rouge_l_sentence_level(eval_sentences, ref_sentences): 'Computes ROUGE-L (sentence level) of two collections of sentences.\n\n Source: https://www.microsoft.com/en-us/research/publication/\n rouge-a-package-for-automatic-evaluation-of-summaries/\n\n Calculated according to:\n R_lcs = LCS(X,Y)/m\n P_lcs = L...
def _len_lcs(x, y): 'Returns the length of the Longest Common Subsequence between two seqs.\n\n Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence\n\n Args:\n x: sequence of words\n y: sequence of words\n\n Returns\n integer: Length of LCS between x and y\n ' table = _lcs(x, y...
8,835,899,292,213,967,000
Returns the length of the Longest Common Subsequence between two seqs. Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence Args: x: sequence of words y: sequence of words Returns integer: Length of LCS between x and y
official/nlp/transformer/utils/metrics.py
_len_lcs
1110sillabo/models
python
def _len_lcs(x, y): 'Returns the length of the Longest Common Subsequence between two seqs.\n\n Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence\n\n Args:\n x: sequence of words\n y: sequence of words\n\n Returns\n integer: Length of LCS between x and y\n ' table = _lcs(x, y...
def _lcs(x, y): 'Computes the length of the LCS between two seqs.\n\n The implementation below uses a DP programming algorithm and runs\n in O(nm) time where n = len(x) and m = len(y).\n Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence\n\n Args:\n x: collection of words\n y: collec...
4,657,099,889,117,814,000
Computes the length of the LCS between two seqs. The implementation below uses a DP programming algorithm and runs in O(nm) time where n = len(x) and m = len(y). Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence Args: x: collection of words y: collection of words Returns: Table of dictio...
official/nlp/transformer/utils/metrics.py
_lcs
1110sillabo/models
python
def _lcs(x, y): 'Computes the length of the LCS between two seqs.\n\n The implementation below uses a DP programming algorithm and runs\n in O(nm) time where n = len(x) and m = len(y).\n Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence\n\n Args:\n x: collection of words\n y: collec...
def _f_lcs(llcs, m, n): 'Computes the LCS-based F-measure score.\n\n Source: http://research.microsoft.com/en-us/um/people/cyl/download/papers/\n rouge-working-note-v1.3.1.pdf\n\n Args:\n llcs: Length of LCS\n m: number of words in reference summary\n n: number of words in candidate summary\n\n Returns...
1,444,177,794,281,056,500
Computes the LCS-based F-measure score. Source: http://research.microsoft.com/en-us/um/people/cyl/download/papers/ rouge-working-note-v1.3.1.pdf Args: llcs: Length of LCS m: number of words in reference summary n: number of words in candidate summary Returns: Float. LCS-based F-measure score
official/nlp/transformer/utils/metrics.py
_f_lcs
1110sillabo/models
python
def _f_lcs(llcs, m, n): 'Computes the LCS-based F-measure score.\n\n Source: http://research.microsoft.com/en-us/um/people/cyl/download/papers/\n rouge-working-note-v1.3.1.pdf\n\n Args:\n llcs: Length of LCS\n m: number of words in reference summary\n n: number of words in candidate summary\n\n Returns...
def problem_metric_fn(*args): "Returns an aggregation of the metric_fn's returned values." (scores, weights) = metric_fn(*args) return tf.metrics.mean(scores, weights)
1,779,688,788,499,172,900
Returns an aggregation of the metric_fn's returned values.
official/nlp/transformer/utils/metrics.py
problem_metric_fn
1110sillabo/models
python
def problem_metric_fn(*args): (scores, weights) = metric_fn(*args) return tf.metrics.mean(scores, weights)
def __init__(self, app=None): 'Initialize the Flask-CLI.' if (app is not None): self.init_app(app)
3,250,348,104,500,289,500
Initialize the Flask-CLI.
virtual/lib/python3.6/site-packages/flask_cli/ext.py
__init__
muneneee/blog
python
def __init__(self, app=None): if (app is not None): self.init_app(app)
def init_app(self, app): 'Initialize a Flask application.' if (not hasattr(app, 'extensions')): app.extensions = {} if ('flask-cli' in app.extensions): raise RuntimeError('Flask-CLI application already initialized') app.extensions['flask-cli'] = self self.setup_pre10(app)
-4,036,279,792,543,169,000
Initialize a Flask application.
virtual/lib/python3.6/site-packages/flask_cli/ext.py
init_app
muneneee/blog
python
def init_app(self, app): if (not hasattr(app, 'extensions')): app.extensions = {} if ('flask-cli' in app.extensions): raise RuntimeError('Flask-CLI application already initialized') app.extensions['flask-cli'] = self self.setup_pre10(app)
def setup_pre10(self, app): 'Setup Flask pre-1.0 application object.' if hasattr(app, 'cli'): return from flask_cli.app import make_shell_context, shell_context_processor app.cli = AppGroup(app.name) app.shell_context_processors = [] app.make_shell_context = types.MethodType(make_shell_c...
8,057,332,060,420,983,000
Setup Flask pre-1.0 application object.
virtual/lib/python3.6/site-packages/flask_cli/ext.py
setup_pre10
muneneee/blog
python
def setup_pre10(self, app): if hasattr(app, 'cli'): return from flask_cli.app import make_shell_context, shell_context_processor app.cli = AppGroup(app.name) app.shell_context_processors = [] app.make_shell_context = types.MethodType(make_shell_context, app) app.shell_context_proces...
def test_qnode_intergration(): 'Test a simple use of qnode with a JAX interface and non-JAX device' dev = qml.device('default.mixed', wires=2) @qml.qnode(dev, interface='jax') def circuit(weights): qml.RX(weights[0], wires=0) qml.RZ(weights[1], wires=1) return qml.expval((qml.Pa...
7,754,218,695,551,231,000
Test a simple use of qnode with a JAX interface and non-JAX device
tests/tape/interfaces/test_qnode_jax.py
test_qnode_intergration
PritishSehzpaul/pennylane
python
def test_qnode_intergration(): dev = qml.device('default.mixed', wires=2) @qml.qnode(dev, interface='jax') def circuit(weights): qml.RX(weights[0], wires=0) qml.RZ(weights[1], wires=1) return qml.expval((qml.PauliZ(0) @ qml.PauliZ(1))) weights = jnp.array([0.1, 0.2]) va...
def test_to_jax(): 'Test the to_jax method' dev = qml.device('default.mixed', wires=2) @qml.qnode(dev, interface='autograd') def circuit(weights): qml.RX(weights[0], wires=0) qml.RZ(weights[1], wires=1) return qml.expval((qml.PauliZ(0) @ qml.PauliZ(1))) circuit.to_jax() ...
5,437,203,877,633,381,000
Test the to_jax method
tests/tape/interfaces/test_qnode_jax.py
test_to_jax
PritishSehzpaul/pennylane
python
def test_to_jax(): dev = qml.device('default.mixed', wires=2) @qml.qnode(dev, interface='autograd') def circuit(weights): qml.RX(weights[0], wires=0) qml.RZ(weights[1], wires=1) return qml.expval((qml.PauliZ(0) @ qml.PauliZ(1))) circuit.to_jax() weights = jnp.array([0.1...
def test_simple_jacobian(): 'Test the use of jax.jaxrev' dev = qml.device('default.mixed', wires=2) @qml.qnode(dev, interface='jax', diff_method='parameter-shift') def circuit(weights): qml.RX(weights[0], wires=0) qml.RY(weights[1], wires=1) return qml.expval((qml.PauliZ(0) @ qm...
-2,640,744,455,169,629,000
Test the use of jax.jaxrev
tests/tape/interfaces/test_qnode_jax.py
test_simple_jacobian
PritishSehzpaul/pennylane
python
def test_simple_jacobian(): dev = qml.device('default.mixed', wires=2) @qml.qnode(dev, interface='jax', diff_method='parameter-shift') def circuit(weights): qml.RX(weights[0], wires=0) qml.RY(weights[1], wires=1) return qml.expval((qml.PauliZ(0) @ qml.PauliZ(1))) weights = ...