id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
14,200 | yt-project/unyt | unyt/array.py | ucross | def ucross(arr1, arr2, registry=None, axisa=-1, axisb=-1, axisc=-1, axis=None):
"""Applies the cross product to two YT arrays.
This wrapper around numpy.cross preserves units.
See the documentation of numpy.cross for full
details.
"""
v = np.cross(arr1, arr2, axisa=axisa, axisb=axisb, axisc=axi... | python | def ucross(arr1, arr2, registry=None, axisa=-1, axisb=-1, axisc=-1, axis=None):
"""Applies the cross product to two YT arrays.
This wrapper around numpy.cross preserves units.
See the documentation of numpy.cross for full
details.
"""
v = np.cross(arr1, arr2, axisa=axisa, axisb=axisb, axisc=axi... | [
"def",
"ucross",
"(",
"arr1",
",",
"arr2",
",",
"registry",
"=",
"None",
",",
"axisa",
"=",
"-",
"1",
",",
"axisb",
"=",
"-",
"1",
",",
"axisc",
"=",
"-",
"1",
",",
"axis",
"=",
"None",
")",
":",
"v",
"=",
"np",
".",
"cross",
"(",
"arr1",
"... | Applies the cross product to two YT arrays.
This wrapper around numpy.cross preserves units.
See the documentation of numpy.cross for full
details. | [
"Applies",
"the",
"cross",
"product",
"to",
"two",
"YT",
"arrays",
"."
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1966-L1976 |
14,201 | yt-project/unyt | unyt/array.py | uintersect1d | def uintersect1d(arr1, arr2, assume_unique=False):
"""Find the sorted unique elements of the two input arrays.
A wrapper around numpy.intersect1d that preserves units. All input arrays
must have the same units. See the documentation of numpy.intersect1d for
full details.
Examples
--------
... | python | def uintersect1d(arr1, arr2, assume_unique=False):
"""Find the sorted unique elements of the two input arrays.
A wrapper around numpy.intersect1d that preserves units. All input arrays
must have the same units. See the documentation of numpy.intersect1d for
full details.
Examples
--------
... | [
"def",
"uintersect1d",
"(",
"arr1",
",",
"arr2",
",",
"assume_unique",
"=",
"False",
")",
":",
"v",
"=",
"np",
".",
"intersect1d",
"(",
"arr1",
",",
"arr2",
",",
"assume_unique",
"=",
"assume_unique",
")",
"v",
"=",
"_validate_numpy_wrapper_units",
"(",
"v... | Find the sorted unique elements of the two input arrays.
A wrapper around numpy.intersect1d that preserves units. All input arrays
must have the same units. See the documentation of numpy.intersect1d for
full details.
Examples
--------
>>> from unyt import cm
>>> A = [1, 2, 3]*cm
>>>... | [
"Find",
"the",
"sorted",
"unique",
"elements",
"of",
"the",
"two",
"input",
"arrays",
"."
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1979-L1997 |
14,202 | yt-project/unyt | unyt/array.py | uunion1d | def uunion1d(arr1, arr2):
"""Find the union of two arrays.
A wrapper around numpy.intersect1d that preserves units. All input arrays
must have the same units. See the documentation of numpy.intersect1d for
full details.
Examples
--------
>>> from unyt import cm
>>> A = [1, 2, 3]*cm
... | python | def uunion1d(arr1, arr2):
"""Find the union of two arrays.
A wrapper around numpy.intersect1d that preserves units. All input arrays
must have the same units. See the documentation of numpy.intersect1d for
full details.
Examples
--------
>>> from unyt import cm
>>> A = [1, 2, 3]*cm
... | [
"def",
"uunion1d",
"(",
"arr1",
",",
"arr2",
")",
":",
"v",
"=",
"np",
".",
"union1d",
"(",
"arr1",
",",
"arr2",
")",
"v",
"=",
"_validate_numpy_wrapper_units",
"(",
"v",
",",
"[",
"arr1",
",",
"arr2",
"]",
")",
"return",
"v"
] | Find the union of two arrays.
A wrapper around numpy.intersect1d that preserves units. All input arrays
must have the same units. See the documentation of numpy.intersect1d for
full details.
Examples
--------
>>> from unyt import cm
>>> A = [1, 2, 3]*cm
>>> B = [2, 3, 4]*cm
>>> u... | [
"Find",
"the",
"union",
"of",
"two",
"arrays",
"."
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L2000-L2018 |
14,203 | yt-project/unyt | unyt/array.py | unorm | def unorm(data, ord=None, axis=None, keepdims=False):
"""Matrix or vector norm that preserves units
This is a wrapper around np.linalg.norm that preserves units. See
the documentation for that function for descriptions of the keyword
arguments.
Examples
--------
>>> from unyt import km
... | python | def unorm(data, ord=None, axis=None, keepdims=False):
"""Matrix or vector norm that preserves units
This is a wrapper around np.linalg.norm that preserves units. See
the documentation for that function for descriptions of the keyword
arguments.
Examples
--------
>>> from unyt import km
... | [
"def",
"unorm",
"(",
"data",
",",
"ord",
"=",
"None",
",",
"axis",
"=",
"None",
",",
"keepdims",
"=",
"False",
")",
":",
"norm",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"data",
",",
"ord",
"=",
"ord",
",",
"axis",
"=",
"axis",
",",
"keepdim... | Matrix or vector norm that preserves units
This is a wrapper around np.linalg.norm that preserves units. See
the documentation for that function for descriptions of the keyword
arguments.
Examples
--------
>>> from unyt import km
>>> data = [1, 2, 3]*km
>>> print(unorm(data))
3.741... | [
"Matrix",
"or",
"vector",
"norm",
"that",
"preserves",
"units"
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L2021-L2038 |
14,204 | yt-project/unyt | unyt/array.py | udot | def udot(op1, op2):
"""Matrix or vector dot product that preserves units
This is a wrapper around np.dot that preserves units.
Examples
--------
>>> from unyt import km, s
>>> a = np.eye(2)*km
>>> b = (np.ones((2, 2)) * 2)*s
>>> print(udot(a, b))
[[2. 2.]
[2. 2.]] km*s
"""... | python | def udot(op1, op2):
"""Matrix or vector dot product that preserves units
This is a wrapper around np.dot that preserves units.
Examples
--------
>>> from unyt import km, s
>>> a = np.eye(2)*km
>>> b = (np.ones((2, 2)) * 2)*s
>>> print(udot(a, b))
[[2. 2.]
[2. 2.]] km*s
"""... | [
"def",
"udot",
"(",
"op1",
",",
"op2",
")",
":",
"dot",
"=",
"np",
".",
"dot",
"(",
"op1",
".",
"d",
",",
"op2",
".",
"d",
")",
"units",
"=",
"op1",
".",
"units",
"*",
"op2",
".",
"units",
"if",
"dot",
".",
"shape",
"==",
"(",
")",
":",
"... | Matrix or vector dot product that preserves units
This is a wrapper around np.dot that preserves units.
Examples
--------
>>> from unyt import km, s
>>> a = np.eye(2)*km
>>> b = (np.ones((2, 2)) * 2)*s
>>> print(udot(a, b))
[[2. 2.]
[2. 2.]] km*s | [
"Matrix",
"or",
"vector",
"dot",
"product",
"that",
"preserves",
"units"
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L2041-L2059 |
14,205 | yt-project/unyt | unyt/array.py | uhstack | def uhstack(arrs):
"""Stack arrays in sequence horizontally while preserving units
This is a wrapper around np.hstack that preserves units.
Examples
--------
>>> from unyt import km
>>> a = [1, 2, 3]*km
>>> b = [2, 3, 4]*km
>>> print(uhstack([a, b]))
[1 2 3 2 3 4] km
>>> a = [[... | python | def uhstack(arrs):
"""Stack arrays in sequence horizontally while preserving units
This is a wrapper around np.hstack that preserves units.
Examples
--------
>>> from unyt import km
>>> a = [1, 2, 3]*km
>>> b = [2, 3, 4]*km
>>> print(uhstack([a, b]))
[1 2 3 2 3 4] km
>>> a = [[... | [
"def",
"uhstack",
"(",
"arrs",
")",
":",
"v",
"=",
"np",
".",
"hstack",
"(",
"arrs",
")",
"v",
"=",
"_validate_numpy_wrapper_units",
"(",
"v",
",",
"arrs",
")",
"return",
"v"
] | Stack arrays in sequence horizontally while preserving units
This is a wrapper around np.hstack that preserves units.
Examples
--------
>>> from unyt import km
>>> a = [1, 2, 3]*km
>>> b = [2, 3, 4]*km
>>> print(uhstack([a, b]))
[1 2 3 2 3 4] km
>>> a = [[1],[2],[3]]*km
>>> b =... | [
"Stack",
"arrays",
"in",
"sequence",
"horizontally",
"while",
"preserving",
"units"
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L2081-L2102 |
14,206 | yt-project/unyt | unyt/array.py | ustack | def ustack(arrs, axis=0):
"""Join a sequence of arrays along a new axis while preserving units
The axis parameter specifies the index of the new axis in the
dimensions of the result. For example, if ``axis=0`` it will be the
first dimension and if ``axis=-1`` it will be the last dimension.
This is... | python | def ustack(arrs, axis=0):
"""Join a sequence of arrays along a new axis while preserving units
The axis parameter specifies the index of the new axis in the
dimensions of the result. For example, if ``axis=0`` it will be the
first dimension and if ``axis=-1`` it will be the last dimension.
This is... | [
"def",
"ustack",
"(",
"arrs",
",",
"axis",
"=",
"0",
")",
":",
"v",
"=",
"np",
".",
"stack",
"(",
"arrs",
",",
"axis",
"=",
"axis",
")",
"v",
"=",
"_validate_numpy_wrapper_units",
"(",
"v",
",",
"arrs",
")",
"return",
"v"
] | Join a sequence of arrays along a new axis while preserving units
The axis parameter specifies the index of the new axis in the
dimensions of the result. For example, if ``axis=0`` it will be the
first dimension and if ``axis=-1`` it will be the last dimension.
This is a wrapper around np.stack that p... | [
"Join",
"a",
"sequence",
"of",
"arrays",
"along",
"a",
"new",
"axis",
"while",
"preserving",
"units"
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L2105-L2126 |
14,207 | yt-project/unyt | unyt/array.py | loadtxt | def loadtxt(fname, dtype="float", delimiter="\t", usecols=None, comments="#"):
r"""
Load unyt_arrays with unit information from a text file. Each row in the
text file must have the same number of values.
Parameters
----------
fname : str
Filename to read.
dtype : data-type, optional... | python | def loadtxt(fname, dtype="float", delimiter="\t", usecols=None, comments="#"):
r"""
Load unyt_arrays with unit information from a text file. Each row in the
text file must have the same number of values.
Parameters
----------
fname : str
Filename to read.
dtype : data-type, optional... | [
"def",
"loadtxt",
"(",
"fname",
",",
"dtype",
"=",
"\"float\"",
",",
"delimiter",
"=",
"\"\\t\"",
",",
"usecols",
"=",
"None",
",",
"comments",
"=",
"\"#\"",
")",
":",
"f",
"=",
"open",
"(",
"fname",
",",
"\"r\"",
")",
"next_one",
"=",
"False",
"unit... | r"""
Load unyt_arrays with unit information from a text file. Each row in the
text file must have the same number of values.
Parameters
----------
fname : str
Filename to read.
dtype : data-type, optional
Data-type of the resulting array; default: float.
delimiter : str, opt... | [
"r",
"Load",
"unyt_arrays",
"with",
"unit",
"information",
"from",
"a",
"text",
"file",
".",
"Each",
"row",
"in",
"the",
"text",
"file",
"must",
"have",
"the",
"same",
"number",
"of",
"values",
"."
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L2155-L2222 |
14,208 | yt-project/unyt | unyt/array.py | savetxt | def savetxt(
fname, arrays, fmt="%.18e", delimiter="\t", header="", footer="", comments="#"
):
r"""
Write unyt_arrays with unit information to a text file.
Parameters
----------
fname : str
The file to write the unyt_arrays to.
arrays : list of unyt_arrays or single unyt_array
... | python | def savetxt(
fname, arrays, fmt="%.18e", delimiter="\t", header="", footer="", comments="#"
):
r"""
Write unyt_arrays with unit information to a text file.
Parameters
----------
fname : str
The file to write the unyt_arrays to.
arrays : list of unyt_arrays or single unyt_array
... | [
"def",
"savetxt",
"(",
"fname",
",",
"arrays",
",",
"fmt",
"=",
"\"%.18e\"",
",",
"delimiter",
"=",
"\"\\t\"",
",",
"header",
"=",
"\"\"",
",",
"footer",
"=",
"\"\"",
",",
"comments",
"=",
"\"#\"",
")",
":",
"if",
"not",
"isinstance",
"(",
"arrays",
... | r"""
Write unyt_arrays with unit information to a text file.
Parameters
----------
fname : str
The file to write the unyt_arrays to.
arrays : list of unyt_arrays or single unyt_array
The array(s) to write to the file.
fmt : str or sequence of strs, optional
A single form... | [
"r",
"Write",
"unyt_arrays",
"with",
"unit",
"information",
"to",
"a",
"text",
"file",
"."
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L2225-L2280 |
14,209 | yt-project/unyt | unyt/array.py | unyt_array.convert_to_units | def convert_to_units(self, units, equivalence=None, **kwargs):
"""
Convert the array to the given units in-place.
Optionally, an equivalence can be specified to convert to an
equivalent quantity which is not in the same dimensions.
Parameters
----------
units : ... | python | def convert_to_units(self, units, equivalence=None, **kwargs):
"""
Convert the array to the given units in-place.
Optionally, an equivalence can be specified to convert to an
equivalent quantity which is not in the same dimensions.
Parameters
----------
units : ... | [
"def",
"convert_to_units",
"(",
"self",
",",
"units",
",",
"equivalence",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"units",
"=",
"_sanitize_units_convert",
"(",
"units",
",",
"self",
".",
"units",
".",
"registry",
")",
"if",
"equivalence",
"is",
"... | Convert the array to the given units in-place.
Optionally, an equivalence can be specified to convert to an
equivalent quantity which is not in the same dimensions.
Parameters
----------
units : Unit object or string
The units you want to convert to.
equival... | [
"Convert",
"the",
"array",
"to",
"the",
"given",
"units",
"in",
"-",
"place",
"."
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L552-L631 |
14,210 | yt-project/unyt | unyt/array.py | unyt_array.convert_to_base | def convert_to_base(self, unit_system=None, equivalence=None, **kwargs):
"""
Convert the array in-place to the equivalent base units in
the specified unit system.
Optionally, an equivalence can be specified to convert to an
equivalent quantity which is not in the same dimensions... | python | def convert_to_base(self, unit_system=None, equivalence=None, **kwargs):
"""
Convert the array in-place to the equivalent base units in
the specified unit system.
Optionally, an equivalence can be specified to convert to an
equivalent quantity which is not in the same dimensions... | [
"def",
"convert_to_base",
"(",
"self",
",",
"unit_system",
"=",
"None",
",",
"equivalence",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"convert_to_units",
"(",
"self",
".",
"units",
".",
"get_base_equivalent",
"(",
"unit_system",
")",
","... | Convert the array in-place to the equivalent base units in
the specified unit system.
Optionally, an equivalence can be specified to convert to an
equivalent quantity which is not in the same dimensions.
Parameters
----------
unit_system : string, optional
T... | [
"Convert",
"the",
"array",
"in",
"-",
"place",
"to",
"the",
"equivalent",
"base",
"units",
"in",
"the",
"specified",
"unit",
"system",
"."
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L633-L670 |
14,211 | yt-project/unyt | unyt/array.py | unyt_array.convert_to_cgs | def convert_to_cgs(self, equivalence=None, **kwargs):
"""
Convert the array and in-place to the equivalent cgs units.
Optionally, an equivalence can be specified to convert to an
equivalent quantity which is not in the same dimensions.
Parameters
----------
equi... | python | def convert_to_cgs(self, equivalence=None, **kwargs):
"""
Convert the array and in-place to the equivalent cgs units.
Optionally, an equivalence can be specified to convert to an
equivalent quantity which is not in the same dimensions.
Parameters
----------
equi... | [
"def",
"convert_to_cgs",
"(",
"self",
",",
"equivalence",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"convert_to_units",
"(",
"self",
".",
"units",
".",
"get_cgs_equivalent",
"(",
")",
",",
"equivalence",
"=",
"equivalence",
",",
"*",
"... | Convert the array and in-place to the equivalent cgs units.
Optionally, an equivalence can be specified to convert to an
equivalent quantity which is not in the same dimensions.
Parameters
----------
equivalence : string, optional
The equivalence you wish to use. To... | [
"Convert",
"the",
"array",
"and",
"in",
"-",
"place",
"to",
"the",
"equivalent",
"cgs",
"units",
"."
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L672-L704 |
14,212 | yt-project/unyt | unyt/array.py | unyt_array.convert_to_mks | def convert_to_mks(self, equivalence=None, **kwargs):
"""
Convert the array and units to the equivalent mks units.
Optionally, an equivalence can be specified to convert to an
equivalent quantity which is not in the same dimensions.
Parameters
----------
equival... | python | def convert_to_mks(self, equivalence=None, **kwargs):
"""
Convert the array and units to the equivalent mks units.
Optionally, an equivalence can be specified to convert to an
equivalent quantity which is not in the same dimensions.
Parameters
----------
equival... | [
"def",
"convert_to_mks",
"(",
"self",
",",
"equivalence",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"convert_to_units",
"(",
"self",
".",
"units",
".",
"get_mks_equivalent",
"(",
")",
",",
"equivalence",
",",
"*",
"*",
"kwargs",
")"
] | Convert the array and units to the equivalent mks units.
Optionally, an equivalence can be specified to convert to an
equivalent quantity which is not in the same dimensions.
Parameters
----------
equivalence : string, optional
The equivalence you wish to use. To se... | [
"Convert",
"the",
"array",
"and",
"units",
"to",
"the",
"equivalent",
"mks",
"units",
"."
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L706-L737 |
14,213 | yt-project/unyt | unyt/array.py | unyt_array.to_value | def to_value(self, units=None, equivalence=None, **kwargs):
"""
Creates a copy of this array with the data in the supplied
units, and returns it without units. Output is therefore a
bare NumPy array.
Optionally, an equivalence can be specified to convert to an
equivalent... | python | def to_value(self, units=None, equivalence=None, **kwargs):
"""
Creates a copy of this array with the data in the supplied
units, and returns it without units. Output is therefore a
bare NumPy array.
Optionally, an equivalence can be specified to convert to an
equivalent... | [
"def",
"to_value",
"(",
"self",
",",
"units",
"=",
"None",
",",
"equivalence",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"units",
"is",
"None",
":",
"v",
"=",
"self",
".",
"value",
"else",
":",
"v",
"=",
"self",
".",
"in_units",
"(",
... | Creates a copy of this array with the data in the supplied
units, and returns it without units. Output is therefore a
bare NumPy array.
Optionally, an equivalence can be specified to convert to an
equivalent quantity which is not in the same dimensions.
.. note::
A... | [
"Creates",
"a",
"copy",
"of",
"this",
"array",
"with",
"the",
"data",
"in",
"the",
"supplied",
"units",
"and",
"returns",
"it",
"without",
"units",
".",
"Output",
"is",
"therefore",
"a",
"bare",
"NumPy",
"array",
"."
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L855-L896 |
14,214 | yt-project/unyt | unyt/array.py | unyt_array.in_base | def in_base(self, unit_system=None):
"""
Creates a copy of this array with the data in the specified unit
system, and returns it in that system's base units.
Parameters
----------
unit_system : string, optional
The unit system to be used in the conversion. If... | python | def in_base(self, unit_system=None):
"""
Creates a copy of this array with the data in the specified unit
system, and returns it in that system's base units.
Parameters
----------
unit_system : string, optional
The unit system to be used in the conversion. If... | [
"def",
"in_base",
"(",
"self",
",",
"unit_system",
"=",
"None",
")",
":",
"us",
"=",
"_sanitize_unit_system",
"(",
"unit_system",
",",
"self",
")",
"try",
":",
"conv_data",
"=",
"_check_em_conversion",
"(",
"self",
".",
"units",
",",
"unit_system",
"=",
"u... | Creates a copy of this array with the data in the specified unit
system, and returns it in that system's base units.
Parameters
----------
unit_system : string, optional
The unit system to be used in the conversion. If not specified,
the configured default base u... | [
"Creates",
"a",
"copy",
"of",
"this",
"array",
"with",
"the",
"data",
"in",
"the",
"specified",
"unit",
"system",
"and",
"returns",
"it",
"in",
"that",
"system",
"s",
"base",
"units",
"."
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L898-L935 |
14,215 | yt-project/unyt | unyt/array.py | unyt_array.argsort | def argsort(self, axis=-1, kind="quicksort", order=None):
"""
Returns the indices that would sort the array.
See the documentation of ndarray.argsort for details about the keyword
arguments.
Example
-------
>>> from unyt import km
>>> data = [3, 8, 7]*km... | python | def argsort(self, axis=-1, kind="quicksort", order=None):
"""
Returns the indices that would sort the array.
See the documentation of ndarray.argsort for details about the keyword
arguments.
Example
-------
>>> from unyt import km
>>> data = [3, 8, 7]*km... | [
"def",
"argsort",
"(",
"self",
",",
"axis",
"=",
"-",
"1",
",",
"kind",
"=",
"\"quicksort\"",
",",
"order",
"=",
"None",
")",
":",
"return",
"self",
".",
"view",
"(",
"np",
".",
"ndarray",
")",
".",
"argsort",
"(",
"axis",
",",
"kind",
",",
"orde... | Returns the indices that would sort the array.
See the documentation of ndarray.argsort for details about the keyword
arguments.
Example
-------
>>> from unyt import km
>>> data = [3, 8, 7]*km
>>> print(np.argsort(data))
[0 2 1]
>>> print(data.ar... | [
"Returns",
"the",
"indices",
"that",
"would",
"sort",
"the",
"array",
"."
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1126-L1142 |
14,216 | yt-project/unyt | unyt/array.py | unyt_array.from_astropy | def from_astropy(cls, arr, unit_registry=None):
"""
Convert an AstroPy "Quantity" to a unyt_array or unyt_quantity.
Parameters
----------
arr : AstroPy Quantity
The Quantity to convert from.
unit_registry : yt UnitRegistry, optional
A yt unit regi... | python | def from_astropy(cls, arr, unit_registry=None):
"""
Convert an AstroPy "Quantity" to a unyt_array or unyt_quantity.
Parameters
----------
arr : AstroPy Quantity
The Quantity to convert from.
unit_registry : yt UnitRegistry, optional
A yt unit regi... | [
"def",
"from_astropy",
"(",
"cls",
",",
"arr",
",",
"unit_registry",
"=",
"None",
")",
":",
"# Converting from AstroPy Quantity",
"try",
":",
"u",
"=",
"arr",
".",
"unit",
"_arr",
"=",
"arr",
"except",
"AttributeError",
":",
"u",
"=",
"arr",
"_arr",
"=",
... | Convert an AstroPy "Quantity" to a unyt_array or unyt_quantity.
Parameters
----------
arr : AstroPy Quantity
The Quantity to convert from.
unit_registry : yt UnitRegistry, optional
A yt unit registry to use in the conversion. If one is not
supplied, t... | [
"Convert",
"an",
"AstroPy",
"Quantity",
"to",
"a",
"unyt_array",
"or",
"unyt_quantity",
"."
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1145-L1187 |
14,217 | yt-project/unyt | unyt/array.py | unyt_array.to_astropy | def to_astropy(self, **kwargs):
"""
Creates a new AstroPy quantity with the same unit information.
Example
-------
>>> from unyt import g, cm
>>> data = [3, 4, 5]*g/cm**3
>>> data.to_astropy()
<Quantity [3., 4., 5.] g / cm3>
"""
return sel... | python | def to_astropy(self, **kwargs):
"""
Creates a new AstroPy quantity with the same unit information.
Example
-------
>>> from unyt import g, cm
>>> data = [3, 4, 5]*g/cm**3
>>> data.to_astropy()
<Quantity [3., 4., 5.] g / cm3>
"""
return sel... | [
"def",
"to_astropy",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"value",
"*",
"_astropy",
".",
"units",
".",
"Unit",
"(",
"str",
"(",
"self",
".",
"units",
")",
",",
"*",
"*",
"kwargs",
")"
] | Creates a new AstroPy quantity with the same unit information.
Example
-------
>>> from unyt import g, cm
>>> data = [3, 4, 5]*g/cm**3
>>> data.to_astropy()
<Quantity [3., 4., 5.] g / cm3> | [
"Creates",
"a",
"new",
"AstroPy",
"quantity",
"with",
"the",
"same",
"unit",
"information",
"."
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1189-L1200 |
14,218 | yt-project/unyt | unyt/array.py | unyt_array.from_pint | def from_pint(cls, arr, unit_registry=None):
"""
Convert a Pint "Quantity" to a unyt_array or unyt_quantity.
Parameters
----------
arr : Pint Quantity
The Quantity to convert from.
unit_registry : yt UnitRegistry, optional
A yt unit registry to us... | python | def from_pint(cls, arr, unit_registry=None):
"""
Convert a Pint "Quantity" to a unyt_array or unyt_quantity.
Parameters
----------
arr : Pint Quantity
The Quantity to convert from.
unit_registry : yt UnitRegistry, optional
A yt unit registry to us... | [
"def",
"from_pint",
"(",
"cls",
",",
"arr",
",",
"unit_registry",
"=",
"None",
")",
":",
"p_units",
"=",
"[",
"]",
"for",
"base",
",",
"exponent",
"in",
"arr",
".",
"_units",
".",
"items",
"(",
")",
":",
"bs",
"=",
"convert_pint_units",
"(",
"base",
... | Convert a Pint "Quantity" to a unyt_array or unyt_quantity.
Parameters
----------
arr : Pint Quantity
The Quantity to convert from.
unit_registry : yt UnitRegistry, optional
A yt unit registry to use in the conversion. If one is not
supplied, the defa... | [
"Convert",
"a",
"Pint",
"Quantity",
"to",
"a",
"unyt_array",
"or",
"unyt_quantity",
"."
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1203-L1236 |
14,219 | yt-project/unyt | unyt/array.py | unyt_array.to_pint | def to_pint(self, unit_registry=None):
"""
Convert a unyt_array or unyt_quantity to a Pint Quantity.
Parameters
----------
arr : unyt_array or unyt_quantity
The unitful quantity to convert from.
unit_registry : Pint UnitRegistry, optional
The Pint... | python | def to_pint(self, unit_registry=None):
"""
Convert a unyt_array or unyt_quantity to a Pint Quantity.
Parameters
----------
arr : unyt_array or unyt_quantity
The unitful quantity to convert from.
unit_registry : Pint UnitRegistry, optional
The Pint... | [
"def",
"to_pint",
"(",
"self",
",",
"unit_registry",
"=",
"None",
")",
":",
"if",
"unit_registry",
"is",
"None",
":",
"unit_registry",
"=",
"_pint",
".",
"UnitRegistry",
"(",
")",
"powers_dict",
"=",
"self",
".",
"units",
".",
"expr",
".",
"as_powers_dict"... | Convert a unyt_array or unyt_quantity to a Pint Quantity.
Parameters
----------
arr : unyt_array or unyt_quantity
The unitful quantity to convert from.
unit_registry : Pint UnitRegistry, optional
The Pint UnitRegistry to use in the conversion. If one is not
... | [
"Convert",
"a",
"unyt_array",
"or",
"unyt_quantity",
"to",
"a",
"Pint",
"Quantity",
"."
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1238-L1271 |
14,220 | yt-project/unyt | unyt/array.py | unyt_array.write_hdf5 | def write_hdf5(self, filename, dataset_name=None, info=None, group_name=None):
r"""Writes a unyt_array to hdf5 file.
Parameters
----------
filename: string
The filename to create and write a dataset to
dataset_name: string
The name of the dataset to crea... | python | def write_hdf5(self, filename, dataset_name=None, info=None, group_name=None):
r"""Writes a unyt_array to hdf5 file.
Parameters
----------
filename: string
The filename to create and write a dataset to
dataset_name: string
The name of the dataset to crea... | [
"def",
"write_hdf5",
"(",
"self",
",",
"filename",
",",
"dataset_name",
"=",
"None",
",",
"info",
"=",
"None",
",",
"group_name",
"=",
"None",
")",
":",
"from",
"unyt",
".",
"_on_demand_imports",
"import",
"_h5py",
"as",
"h5py",
"import",
"pickle",
"if",
... | r"""Writes a unyt_array to hdf5 file.
Parameters
----------
filename: string
The filename to create and write a dataset to
dataset_name: string
The name of the dataset to create in the file.
info: dictionary
A dictionary of supplementary inf... | [
"r",
"Writes",
"a",
"unyt_array",
"to",
"hdf5",
"file",
"."
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1277-L1339 |
14,221 | yt-project/unyt | unyt/array.py | unyt_array.from_hdf5 | def from_hdf5(cls, filename, dataset_name=None, group_name=None):
r"""Attempts read in and convert a dataset in an hdf5 file into a
unyt_array.
Parameters
----------
filename: string
The filename to of the hdf5 file.
dataset_name: string
The name of ... | python | def from_hdf5(cls, filename, dataset_name=None, group_name=None):
r"""Attempts read in and convert a dataset in an hdf5 file into a
unyt_array.
Parameters
----------
filename: string
The filename to of the hdf5 file.
dataset_name: string
The name of ... | [
"def",
"from_hdf5",
"(",
"cls",
",",
"filename",
",",
"dataset_name",
"=",
"None",
",",
"group_name",
"=",
"None",
")",
":",
"from",
"unyt",
".",
"_on_demand_imports",
"import",
"_h5py",
"as",
"h5py",
"import",
"pickle",
"if",
"dataset_name",
"is",
"None",
... | r"""Attempts read in and convert a dataset in an hdf5 file into a
unyt_array.
Parameters
----------
filename: string
The filename to of the hdf5 file.
dataset_name: string
The name of the dataset to read from. If the dataset has a units
attribut... | [
"r",
"Attempts",
"read",
"in",
"and",
"convert",
"a",
"dataset",
"in",
"an",
"hdf5",
"file",
"into",
"a",
"unyt_array",
"."
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1342-L1377 |
14,222 | yt-project/unyt | unyt/array.py | unyt_array.copy | def copy(self, order="C"):
"""
Return a copy of the array.
Parameters
----------
order : {'C', 'F', 'A', 'K'}, optional
Controls the memory layout of the copy. 'C' means C-order,
'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
'... | python | def copy(self, order="C"):
"""
Return a copy of the array.
Parameters
----------
order : {'C', 'F', 'A', 'K'}, optional
Controls the memory layout of the copy. 'C' means C-order,
'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
'... | [
"def",
"copy",
"(",
"self",
",",
"order",
"=",
"\"C\"",
")",
":",
"return",
"type",
"(",
"self",
")",
"(",
"np",
".",
"copy",
"(",
"np",
".",
"asarray",
"(",
"self",
")",
")",
",",
"self",
".",
"units",
")"
] | Return a copy of the array.
Parameters
----------
order : {'C', 'F', 'A', 'K'}, optional
Controls the memory layout of the copy. 'C' means C-order,
'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
'C' otherwise. 'K' means match the layout of `a`... | [
"Return",
"a",
"copy",
"of",
"the",
"array",
"."
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1738-L1772 |
14,223 | yt-project/unyt | unyt/array.py | unyt_array.dot | def dot(self, b, out=None):
"""dot product of two arrays.
Refer to `numpy.dot` for full documentation.
See Also
--------
numpy.dot : equivalent function
Examples
--------
>>> from unyt import km, s
>>> a = np.eye(2)*km
>>> b = (np.ones((... | python | def dot(self, b, out=None):
"""dot product of two arrays.
Refer to `numpy.dot` for full documentation.
See Also
--------
numpy.dot : equivalent function
Examples
--------
>>> from unyt import km, s
>>> a = np.eye(2)*km
>>> b = (np.ones((... | [
"def",
"dot",
"(",
"self",
",",
"b",
",",
"out",
"=",
"None",
")",
":",
"res_units",
"=",
"self",
".",
"units",
"*",
"getattr",
"(",
"b",
",",
"\"units\"",
",",
"NULL_UNIT",
")",
"ret",
"=",
"self",
".",
"view",
"(",
"np",
".",
"ndarray",
")",
... | dot product of two arrays.
Refer to `numpy.dot` for full documentation.
See Also
--------
numpy.dot : equivalent function
Examples
--------
>>> from unyt import km, s
>>> a = np.eye(2)*km
>>> b = (np.ones((2, 2)) * 2)*s
>>> print(a.dot(b... | [
"dot",
"product",
"of",
"two",
"arrays",
"."
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/array.py#L1783-L1811 |
14,224 | yt-project/unyt | unyt/__init__.py | import_units | def import_units(module, namespace):
"""Import Unit objects from a module into a namespace"""
for key, value in module.__dict__.items():
if isinstance(value, (unyt_quantity, Unit)):
namespace[key] = value | python | def import_units(module, namespace):
"""Import Unit objects from a module into a namespace"""
for key, value in module.__dict__.items():
if isinstance(value, (unyt_quantity, Unit)):
namespace[key] = value | [
"def",
"import_units",
"(",
"module",
",",
"namespace",
")",
":",
"for",
"key",
",",
"value",
"in",
"module",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"unyt_quantity",
",",
"Unit",
")",
")",
":",
"name... | Import Unit objects from a module into a namespace | [
"Import",
"Unit",
"objects",
"from",
"a",
"module",
"into",
"a",
"namespace"
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/__init__.py#L98-L102 |
14,225 | yt-project/unyt | unyt/unit_registry.py | _lookup_unit_symbol | def _lookup_unit_symbol(symbol_str, unit_symbol_lut):
"""
Searches for the unit data tuple corresponding to the given symbol.
Parameters
----------
symbol_str : str
The unit symbol to look up.
unit_symbol_lut : dict
Dictionary with symbols as keys and unit data tuples as values.... | python | def _lookup_unit_symbol(symbol_str, unit_symbol_lut):
"""
Searches for the unit data tuple corresponding to the given symbol.
Parameters
----------
symbol_str : str
The unit symbol to look up.
unit_symbol_lut : dict
Dictionary with symbols as keys and unit data tuples as values.... | [
"def",
"_lookup_unit_symbol",
"(",
"symbol_str",
",",
"unit_symbol_lut",
")",
":",
"if",
"symbol_str",
"in",
"unit_symbol_lut",
":",
"# lookup successful, return the tuple directly",
"return",
"unit_symbol_lut",
"[",
"symbol_str",
"]",
"# could still be a known symbol with a pr... | Searches for the unit data tuple corresponding to the given symbol.
Parameters
----------
symbol_str : str
The unit symbol to look up.
unit_symbol_lut : dict
Dictionary with symbols as keys and unit data tuples as values. | [
"Searches",
"for",
"the",
"unit",
"data",
"tuple",
"corresponding",
"to",
"the",
"given",
"symbol",
"."
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_registry.py#L272-L326 |
14,226 | yt-project/unyt | unyt/unit_registry.py | UnitRegistry.unit_system_id | def unit_system_id(self):
"""
This is a unique identifier for the unit registry created
from a FNV hash. It is needed to register a dataset's code
unit system in the unit system registry.
"""
if self._unit_system_id is None:
hash_data = bytearray()
... | python | def unit_system_id(self):
"""
This is a unique identifier for the unit registry created
from a FNV hash. It is needed to register a dataset's code
unit system in the unit system registry.
"""
if self._unit_system_id is None:
hash_data = bytearray()
... | [
"def",
"unit_system_id",
"(",
"self",
")",
":",
"if",
"self",
".",
"_unit_system_id",
"is",
"None",
":",
"hash_data",
"=",
"bytearray",
"(",
")",
"for",
"k",
",",
"v",
"in",
"sorted",
"(",
"self",
".",
"lut",
".",
"items",
"(",
")",
")",
":",
"hash... | This is a unique identifier for the unit registry created
from a FNV hash. It is needed to register a dataset's code
unit system in the unit system registry. | [
"This",
"is",
"a",
"unique",
"identifier",
"for",
"the",
"unit",
"registry",
"created",
"from",
"a",
"FNV",
"hash",
".",
"It",
"is",
"needed",
"to",
"register",
"a",
"dataset",
"s",
"code",
"unit",
"system",
"in",
"the",
"unit",
"system",
"registry",
"."... | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_registry.py#L82-L96 |
14,227 | yt-project/unyt | unyt/unit_registry.py | UnitRegistry.add | def add(
self,
symbol,
base_value,
dimensions,
tex_repr=None,
offset=None,
prefixable=False,
):
"""
Add a symbol to this registry.
Parameters
----------
symbol : str
The name of the unit
base_value :... | python | def add(
self,
symbol,
base_value,
dimensions,
tex_repr=None,
offset=None,
prefixable=False,
):
"""
Add a symbol to this registry.
Parameters
----------
symbol : str
The name of the unit
base_value :... | [
"def",
"add",
"(",
"self",
",",
"symbol",
",",
"base_value",
",",
"dimensions",
",",
"tex_repr",
"=",
"None",
",",
"offset",
"=",
"None",
",",
"prefixable",
"=",
"False",
",",
")",
":",
"from",
"unyt",
".",
"unit_object",
"import",
"_validate_dimensions",
... | Add a symbol to this registry.
Parameters
----------
symbol : str
The name of the unit
base_value : float
The scaling from the units value to the equivalent SI unit
with the same dimensions
dimensions : expr
The dimensions of the unit... | [
"Add",
"a",
"symbol",
"to",
"this",
"registry",
"."
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_registry.py#L102-L164 |
14,228 | yt-project/unyt | unyt/unit_registry.py | UnitRegistry.remove | def remove(self, symbol):
"""
Remove the entry for the unit matching `symbol`.
Parameters
----------
symbol : str
The name of the unit symbol to remove from the registry.
"""
self._unit_system_id = None
if symbol not in self.lut:
... | python | def remove(self, symbol):
"""
Remove the entry for the unit matching `symbol`.
Parameters
----------
symbol : str
The name of the unit symbol to remove from the registry.
"""
self._unit_system_id = None
if symbol not in self.lut:
... | [
"def",
"remove",
"(",
"self",
",",
"symbol",
")",
":",
"self",
".",
"_unit_system_id",
"=",
"None",
"if",
"symbol",
"not",
"in",
"self",
".",
"lut",
":",
"raise",
"SymbolNotFoundError",
"(",
"\"Tried to remove the symbol '%s', but it does not exist \"",
"\"in this r... | Remove the entry for the unit matching `symbol`.
Parameters
----------
symbol : str
The name of the unit symbol to remove from the registry. | [
"Remove",
"the",
"entry",
"for",
"the",
"unit",
"matching",
"symbol",
"."
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_registry.py#L166-L185 |
14,229 | yt-project/unyt | unyt/unit_registry.py | UnitRegistry.modify | def modify(self, symbol, base_value):
"""
Change the base value of a unit symbol. Useful for adjusting code
units after parsing parameters.
Parameters
----------
symbol : str
The name of the symbol to modify
base_value : float
The new base... | python | def modify(self, symbol, base_value):
"""
Change the base value of a unit symbol. Useful for adjusting code
units after parsing parameters.
Parameters
----------
symbol : str
The name of the symbol to modify
base_value : float
The new base... | [
"def",
"modify",
"(",
"self",
",",
"symbol",
",",
"base_value",
")",
":",
"self",
".",
"_unit_system_id",
"=",
"None",
"if",
"symbol",
"not",
"in",
"self",
".",
"lut",
":",
"raise",
"SymbolNotFoundError",
"(",
"\"Tried to modify the symbol '%s', but it does not ex... | Change the base value of a unit symbol. Useful for adjusting code
units after parsing parameters.
Parameters
----------
symbol : str
The name of the symbol to modify
base_value : float
The new base_value for the symbol. | [
"Change",
"the",
"base",
"value",
"of",
"a",
"unit",
"symbol",
".",
"Useful",
"for",
"adjusting",
"code",
"units",
"after",
"parsing",
"parameters",
"."
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_registry.py#L187-L216 |
14,230 | yt-project/unyt | unyt/unit_registry.py | UnitRegistry.to_json | def to_json(self):
"""
Returns a json-serialized version of the unit registry
"""
sanitized_lut = {}
for k, v in self.lut.items():
san_v = list(v)
repr_dims = str(v[1])
san_v[1] = repr_dims
sanitized_lut[k] = tuple(san_v)
r... | python | def to_json(self):
"""
Returns a json-serialized version of the unit registry
"""
sanitized_lut = {}
for k, v in self.lut.items():
san_v = list(v)
repr_dims = str(v[1])
san_v[1] = repr_dims
sanitized_lut[k] = tuple(san_v)
r... | [
"def",
"to_json",
"(",
"self",
")",
":",
"sanitized_lut",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"self",
".",
"lut",
".",
"items",
"(",
")",
":",
"san_v",
"=",
"list",
"(",
"v",
")",
"repr_dims",
"=",
"str",
"(",
"v",
"[",
"1",
"]",
")",
... | Returns a json-serialized version of the unit registry | [
"Returns",
"a",
"json",
"-",
"serialized",
"version",
"of",
"the",
"unit",
"registry"
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_registry.py#L225-L236 |
14,231 | yt-project/unyt | unyt/unit_registry.py | UnitRegistry.from_json | def from_json(cls, json_text):
"""
Returns a UnitRegistry object from a json-serialized unit registry
Parameters
----------
json_text : str
A string containing a json represention of a UnitRegistry
"""
data = json.loads(json_text)
lut = {}
... | python | def from_json(cls, json_text):
"""
Returns a UnitRegistry object from a json-serialized unit registry
Parameters
----------
json_text : str
A string containing a json represention of a UnitRegistry
"""
data = json.loads(json_text)
lut = {}
... | [
"def",
"from_json",
"(",
"cls",
",",
"json_text",
")",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"json_text",
")",
"lut",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"data",
".",
"items",
"(",
")",
":",
"unsan_v",
"=",
"list",
"(",
"v",
")",
... | Returns a UnitRegistry object from a json-serialized unit registry
Parameters
----------
json_text : str
A string containing a json represention of a UnitRegistry | [
"Returns",
"a",
"UnitRegistry",
"object",
"from",
"a",
"json",
"-",
"serialized",
"unit",
"registry"
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_registry.py#L239-L256 |
14,232 | yt-project/unyt | unyt/unit_object.py | _em_conversion | def _em_conversion(orig_units, conv_data, to_units=None, unit_system=None):
"""Convert between E&M & MKS base units.
If orig_units is a CGS (or MKS) E&M unit, conv_data contains the
corresponding MKS (or CGS) unit and scale factor converting between them.
This must be done by replacing the expression o... | python | def _em_conversion(orig_units, conv_data, to_units=None, unit_system=None):
"""Convert between E&M & MKS base units.
If orig_units is a CGS (or MKS) E&M unit, conv_data contains the
corresponding MKS (or CGS) unit and scale factor converting between them.
This must be done by replacing the expression o... | [
"def",
"_em_conversion",
"(",
"orig_units",
",",
"conv_data",
",",
"to_units",
"=",
"None",
",",
"unit_system",
"=",
"None",
")",
":",
"conv_unit",
",",
"canonical_unit",
",",
"scale",
"=",
"conv_data",
"if",
"conv_unit",
"is",
"None",
":",
"conv_unit",
"=",... | Convert between E&M & MKS base units.
If orig_units is a CGS (or MKS) E&M unit, conv_data contains the
corresponding MKS (or CGS) unit and scale factor converting between them.
This must be done by replacing the expression of the original unit
with the new one in the unit expression and multiplying by ... | [
"Convert",
"between",
"E&M",
"&",
"MKS",
"base",
"units",
"."
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L786-L805 |
14,233 | yt-project/unyt | unyt/unit_object.py | _check_em_conversion | def _check_em_conversion(unit, to_unit=None, unit_system=None, registry=None):
"""Check to see if the units contain E&M units
This function supports unyt's ability to convert data to and from E&M
electromagnetic units. However, this support is limited and only very
simple unit expressions can be readil... | python | def _check_em_conversion(unit, to_unit=None, unit_system=None, registry=None):
"""Check to see if the units contain E&M units
This function supports unyt's ability to convert data to and from E&M
electromagnetic units. However, this support is limited and only very
simple unit expressions can be readil... | [
"def",
"_check_em_conversion",
"(",
"unit",
",",
"to_unit",
"=",
"None",
",",
"unit_system",
"=",
"None",
",",
"registry",
"=",
"None",
")",
":",
"em_map",
"=",
"(",
")",
"if",
"unit",
"==",
"to_unit",
"or",
"unit",
".",
"dimensions",
"not",
"in",
"em_... | Check to see if the units contain E&M units
This function supports unyt's ability to convert data to and from E&M
electromagnetic units. However, this support is limited and only very
simple unit expressions can be readily converted. This function tries
to see if the unit is an atomic base unit that is... | [
"Check",
"to",
"see",
"if",
"the",
"units",
"contain",
"E&M",
"units"
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L809-L858 |
14,234 | yt-project/unyt | unyt/unit_object.py | _get_conversion_factor | def _get_conversion_factor(old_units, new_units, dtype):
"""
Get the conversion factor between two units of equivalent dimensions. This
is the number you multiply data by to convert from values in `old_units` to
values in `new_units`.
Parameters
----------
old_units: str or Unit object
... | python | def _get_conversion_factor(old_units, new_units, dtype):
"""
Get the conversion factor between two units of equivalent dimensions. This
is the number you multiply data by to convert from values in `old_units` to
values in `new_units`.
Parameters
----------
old_units: str or Unit object
... | [
"def",
"_get_conversion_factor",
"(",
"old_units",
",",
"new_units",
",",
"dtype",
")",
":",
"if",
"old_units",
".",
"dimensions",
"!=",
"new_units",
".",
"dimensions",
":",
"raise",
"UnitConversionError",
"(",
"old_units",
",",
"old_units",
".",
"dimensions",
"... | Get the conversion factor between two units of equivalent dimensions. This
is the number you multiply data by to convert from values in `old_units` to
values in `new_units`.
Parameters
----------
old_units: str or Unit object
The current units.
new_units : str or Unit object
The... | [
"Get",
"the",
"conversion",
"factor",
"between",
"two",
"units",
"of",
"equivalent",
"dimensions",
".",
"This",
"is",
"the",
"number",
"you",
"multiply",
"data",
"by",
"to",
"convert",
"from",
"values",
"in",
"old_units",
"to",
"values",
"in",
"new_units",
"... | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L861-L894 |
14,235 | yt-project/unyt | unyt/unit_object.py | _get_unit_data_from_expr | def _get_unit_data_from_expr(unit_expr, unit_symbol_lut):
"""
Grabs the total base_value and dimensions from a valid unit expression.
Parameters
----------
unit_expr: Unit object, or sympy Expr object
The expression containing unit symbols.
unit_symbol_lut: dict
Provides the uni... | python | def _get_unit_data_from_expr(unit_expr, unit_symbol_lut):
"""
Grabs the total base_value and dimensions from a valid unit expression.
Parameters
----------
unit_expr: Unit object, or sympy Expr object
The expression containing unit symbols.
unit_symbol_lut: dict
Provides the uni... | [
"def",
"_get_unit_data_from_expr",
"(",
"unit_expr",
",",
"unit_symbol_lut",
")",
":",
"# Now for the sympy possibilities",
"if",
"isinstance",
"(",
"unit_expr",
",",
"Number",
")",
":",
"if",
"unit_expr",
"is",
"sympy_one",
":",
"return",
"(",
"1.0",
",",
"sympy_... | Grabs the total base_value and dimensions from a valid unit expression.
Parameters
----------
unit_expr: Unit object, or sympy Expr object
The expression containing unit symbols.
unit_symbol_lut: dict
Provides the unit data for each valid unit symbol. | [
"Grabs",
"the",
"total",
"base_value",
"and",
"dimensions",
"from",
"a",
"valid",
"unit",
"expression",
"."
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L902-L946 |
14,236 | yt-project/unyt | unyt/unit_object.py | define_unit | def define_unit(
symbol, value, tex_repr=None, offset=None, prefixable=False, registry=None
):
"""
Define a new unit and add it to the specified unit registry.
Parameters
----------
symbol : string
The symbol for the new unit.
value : tuple or :class:`unyt.array.unyt_quantity`
... | python | def define_unit(
symbol, value, tex_repr=None, offset=None, prefixable=False, registry=None
):
"""
Define a new unit and add it to the specified unit registry.
Parameters
----------
symbol : string
The symbol for the new unit.
value : tuple or :class:`unyt.array.unyt_quantity`
... | [
"def",
"define_unit",
"(",
"symbol",
",",
"value",
",",
"tex_repr",
"=",
"None",
",",
"offset",
"=",
"None",
",",
"prefixable",
"=",
"False",
",",
"registry",
"=",
"None",
")",
":",
"from",
"unyt",
".",
"array",
"import",
"unyt_quantity",
",",
"_iterable... | Define a new unit and add it to the specified unit registry.
Parameters
----------
symbol : string
The symbol for the new unit.
value : tuple or :class:`unyt.array.unyt_quantity`
The definition of the new unit in terms of some other units. For
example, one would define a new "mp... | [
"Define",
"a",
"new",
"unit",
"and",
"add",
"it",
"to",
"the",
"specified",
"unit",
"registry",
"."
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L976-L1042 |
14,237 | yt-project/unyt | unyt/unit_object.py | Unit.latex_repr | def latex_repr(self):
"""A LaTeX representation for the unit
Examples
--------
>>> from unyt import g, cm
>>> (g/cm**3).units.latex_repr
'\\\\frac{\\\\rm{g}}{\\\\rm{cm}^{3}}'
"""
if self._latex_repr is not None:
return self._latex_repr
... | python | def latex_repr(self):
"""A LaTeX representation for the unit
Examples
--------
>>> from unyt import g, cm
>>> (g/cm**3).units.latex_repr
'\\\\frac{\\\\rm{g}}{\\\\rm{cm}^{3}}'
"""
if self._latex_repr is not None:
return self._latex_repr
... | [
"def",
"latex_repr",
"(",
"self",
")",
":",
"if",
"self",
".",
"_latex_repr",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_latex_repr",
"if",
"self",
".",
"expr",
".",
"is_Atom",
":",
"expr",
"=",
"self",
".",
"expr",
"else",
":",
"expr",
"=",
... | A LaTeX representation for the unit
Examples
--------
>>> from unyt import g, cm
>>> (g/cm**3).units.latex_repr
'\\\\frac{\\\\rm{g}}{\\\\rm{cm}^{3}}' | [
"A",
"LaTeX",
"representation",
"for",
"the",
"unit"
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L261-L277 |
14,238 | yt-project/unyt | unyt/unit_object.py | Unit.is_code_unit | def is_code_unit(self):
"""Is this a "code" unit?
Returns
-------
True if the unit consists of atom units that being with "code".
False otherwise
"""
for atom in self.expr.atoms():
if not (str(atom).startswith("code") or atom.is_Number):
... | python | def is_code_unit(self):
"""Is this a "code" unit?
Returns
-------
True if the unit consists of atom units that being with "code".
False otherwise
"""
for atom in self.expr.atoms():
if not (str(atom).startswith("code") or atom.is_Number):
... | [
"def",
"is_code_unit",
"(",
"self",
")",
":",
"for",
"atom",
"in",
"self",
".",
"expr",
".",
"atoms",
"(",
")",
":",
"if",
"not",
"(",
"str",
"(",
"atom",
")",
".",
"startswith",
"(",
"\"code\"",
")",
"or",
"atom",
".",
"is_Number",
")",
":",
"re... | Is this a "code" unit?
Returns
-------
True if the unit consists of atom units that being with "code".
False otherwise | [
"Is",
"this",
"a",
"code",
"unit?"
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L514-L526 |
14,239 | yt-project/unyt | unyt/unit_object.py | Unit.list_equivalencies | def list_equivalencies(self):
"""Lists the possible equivalencies associated with this unit object
Examples
--------
>>> from unyt import km
>>> km.units.list_equivalencies()
spectral: length <-> spatial_frequency <-> frequency <-> energy
schwarzschild: mass <-> ... | python | def list_equivalencies(self):
"""Lists the possible equivalencies associated with this unit object
Examples
--------
>>> from unyt import km
>>> km.units.list_equivalencies()
spectral: length <-> spatial_frequency <-> frequency <-> energy
schwarzschild: mass <-> ... | [
"def",
"list_equivalencies",
"(",
"self",
")",
":",
"from",
"unyt",
".",
"equivalencies",
"import",
"equivalence_registry",
"for",
"k",
",",
"v",
"in",
"equivalence_registry",
".",
"items",
"(",
")",
":",
"if",
"self",
".",
"has_equivalent",
"(",
"k",
")",
... | Lists the possible equivalencies associated with this unit object
Examples
--------
>>> from unyt import km
>>> km.units.list_equivalencies()
spectral: length <-> spatial_frequency <-> frequency <-> energy
schwarzschild: mass <-> length
compton: mass <-> length | [
"Lists",
"the",
"possible",
"equivalencies",
"associated",
"with",
"this",
"unit",
"object"
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L528-L543 |
14,240 | yt-project/unyt | unyt/unit_object.py | Unit.get_base_equivalent | def get_base_equivalent(self, unit_system=None):
"""Create and return dimensionally-equivalent units in a specified base.
>>> from unyt import g, cm
>>> (g/cm**3).get_base_equivalent('mks')
kg/m**3
>>> (g/cm**3).get_base_equivalent('solar')
Mearth/AU**3
"""
... | python | def get_base_equivalent(self, unit_system=None):
"""Create and return dimensionally-equivalent units in a specified base.
>>> from unyt import g, cm
>>> (g/cm**3).get_base_equivalent('mks')
kg/m**3
>>> (g/cm**3).get_base_equivalent('solar')
Mearth/AU**3
"""
... | [
"def",
"get_base_equivalent",
"(",
"self",
",",
"unit_system",
"=",
"None",
")",
":",
"from",
"unyt",
".",
"unit_registry",
"import",
"_sanitize_unit_system",
"unit_system",
"=",
"_sanitize_unit_system",
"(",
"unit_system",
",",
"self",
")",
"try",
":",
"conv_data... | Create and return dimensionally-equivalent units in a specified base.
>>> from unyt import g, cm
>>> (g/cm**3).get_base_equivalent('mks')
kg/m**3
>>> (g/cm**3).get_base_equivalent('solar')
Mearth/AU**3 | [
"Create",
"and",
"return",
"dimensionally",
"-",
"equivalent",
"units",
"in",
"a",
"specified",
"base",
"."
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L564-L589 |
14,241 | yt-project/unyt | unyt/unit_object.py | Unit.as_coeff_unit | def as_coeff_unit(self):
"""Factor the coefficient multiplying a unit
For units that are multiplied by a constant dimensionless
coefficient, returns a tuple containing the coefficient and
a new unit object for the unmultiplied unit.
Example
-------
>>> import u... | python | def as_coeff_unit(self):
"""Factor the coefficient multiplying a unit
For units that are multiplied by a constant dimensionless
coefficient, returns a tuple containing the coefficient and
a new unit object for the unmultiplied unit.
Example
-------
>>> import u... | [
"def",
"as_coeff_unit",
"(",
"self",
")",
":",
"coeff",
",",
"mul",
"=",
"self",
".",
"expr",
".",
"as_coeff_Mul",
"(",
")",
"coeff",
"=",
"float",
"(",
"coeff",
")",
"ret",
"=",
"Unit",
"(",
"mul",
",",
"self",
".",
"base_value",
"/",
"coeff",
","... | Factor the coefficient multiplying a unit
For units that are multiplied by a constant dimensionless
coefficient, returns a tuple containing the coefficient and
a new unit object for the unmultiplied unit.
Example
-------
>>> import unyt as u
>>> unit = (u.m**2/... | [
"Factor",
"the",
"coefficient",
"multiplying",
"a",
"unit"
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L653-L679 |
14,242 | yt-project/unyt | unyt/unit_object.py | Unit.simplify | def simplify(self):
"""Return a new equivalent unit object with a simplified unit expression
>>> import unyt as u
>>> unit = (u.m**2/u.cm).simplify()
>>> unit
100*m
"""
expr = self.expr
self.expr = _cancel_mul(expr, self.registry)
return self | python | def simplify(self):
"""Return a new equivalent unit object with a simplified unit expression
>>> import unyt as u
>>> unit = (u.m**2/u.cm).simplify()
>>> unit
100*m
"""
expr = self.expr
self.expr = _cancel_mul(expr, self.registry)
return self | [
"def",
"simplify",
"(",
"self",
")",
":",
"expr",
"=",
"self",
".",
"expr",
"self",
".",
"expr",
"=",
"_cancel_mul",
"(",
"expr",
",",
"self",
".",
"registry",
")",
"return",
"self"
] | Return a new equivalent unit object with a simplified unit expression
>>> import unyt as u
>>> unit = (u.m**2/u.cm).simplify()
>>> unit
100*m | [
"Return",
"a",
"new",
"equivalent",
"unit",
"object",
"with",
"a",
"simplified",
"unit",
"expression"
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L681-L691 |
14,243 | yt-project/unyt | unyt/_parsing.py | _auto_positive_symbol | def _auto_positive_symbol(tokens, local_dict, global_dict):
"""
Inserts calls to ``Symbol`` for undefined variables.
Passes in positive=True as a keyword argument.
Adapted from sympy.sympy.parsing.sympy_parser.auto_symbol
"""
result = []
tokens.append((None, None)) # so zip traverses all t... | python | def _auto_positive_symbol(tokens, local_dict, global_dict):
"""
Inserts calls to ``Symbol`` for undefined variables.
Passes in positive=True as a keyword argument.
Adapted from sympy.sympy.parsing.sympy_parser.auto_symbol
"""
result = []
tokens.append((None, None)) # so zip traverses all t... | [
"def",
"_auto_positive_symbol",
"(",
"tokens",
",",
"local_dict",
",",
"global_dict",
")",
":",
"result",
"=",
"[",
"]",
"tokens",
".",
"append",
"(",
"(",
"None",
",",
"None",
")",
")",
"# so zip traverses all tokens",
"for",
"tok",
",",
"nextTok",
"in",
... | Inserts calls to ``Symbol`` for undefined variables.
Passes in positive=True as a keyword argument.
Adapted from sympy.sympy.parsing.sympy_parser.auto_symbol | [
"Inserts",
"calls",
"to",
"Symbol",
"for",
"undefined",
"variables",
".",
"Passes",
"in",
"positive",
"=",
"True",
"as",
"a",
"keyword",
"argument",
".",
"Adapted",
"from",
"sympy",
".",
"sympy",
".",
"parsing",
".",
"sympy_parser",
".",
"auto_symbol"
] | 7a4eafc229f83784f4c63d639aee554f9a6b1ca0 | https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/_parsing.py#L25-L68 |
14,244 | kz26/PyExcelerate | pyexcelerate/Range.py | Range.intersection | def intersection(self, range):
"""
Calculates the intersection with another range object
"""
if self.worksheet != range.worksheet:
# Different worksheet
return None
start = (max(self._start[0], range._start[0]),
max(self._start[1], range._start[1]))
... | python | def intersection(self, range):
"""
Calculates the intersection with another range object
"""
if self.worksheet != range.worksheet:
# Different worksheet
return None
start = (max(self._start[0], range._start[0]),
max(self._start[1], range._start[1]))
... | [
"def",
"intersection",
"(",
"self",
",",
"range",
")",
":",
"if",
"self",
".",
"worksheet",
"!=",
"range",
".",
"worksheet",
":",
"# Different worksheet",
"return",
"None",
"start",
"=",
"(",
"max",
"(",
"self",
".",
"_start",
"[",
"0",
"]",
",",
"rang... | Calculates the intersection with another range object | [
"Calculates",
"the",
"intersection",
"with",
"another",
"range",
"object"
] | 247406dc41adc7e94542bcbf04589f1e5fdf8c51 | https://github.com/kz26/PyExcelerate/blob/247406dc41adc7e94542bcbf04589f1e5fdf8c51/pyexcelerate/Range.py#L140-L153 |
14,245 | harlowja/fasteners | fasteners/process_lock.py | interprocess_locked | def interprocess_locked(path):
"""Acquires & releases a interprocess lock around call into
decorated function."""
lock = InterProcessLock(path)
def decorator(f):
@six.wraps(f)
def wrapper(*args, **kwargs):
with lock:
return f(*args, **kwargs)
re... | python | def interprocess_locked(path):
"""Acquires & releases a interprocess lock around call into
decorated function."""
lock = InterProcessLock(path)
def decorator(f):
@six.wraps(f)
def wrapper(*args, **kwargs):
with lock:
return f(*args, **kwargs)
re... | [
"def",
"interprocess_locked",
"(",
"path",
")",
":",
"lock",
"=",
"InterProcessLock",
"(",
"path",
")",
"def",
"decorator",
"(",
"f",
")",
":",
"@",
"six",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")... | Acquires & releases a interprocess lock around call into
decorated function. | [
"Acquires",
"&",
"releases",
"a",
"interprocess",
"lock",
"around",
"call",
"into",
"decorated",
"function",
"."
] | 8f3bbab0204a50037448a8fad7a6bf12eb1a2695 | https://github.com/harlowja/fasteners/blob/8f3bbab0204a50037448a8fad7a6bf12eb1a2695/fasteners/process_lock.py#L265-L280 |
14,246 | harlowja/fasteners | fasteners/process_lock.py | _InterProcessLock.acquire | def acquire(self, blocking=True,
delay=DELAY_INCREMENT, max_delay=MAX_DELAY,
timeout=None):
"""Attempt to acquire the given lock.
:param blocking: whether to wait forever to try to acquire the lock
:type blocking: bool
:param delay: when blocking this is ... | python | def acquire(self, blocking=True,
delay=DELAY_INCREMENT, max_delay=MAX_DELAY,
timeout=None):
"""Attempt to acquire the given lock.
:param blocking: whether to wait forever to try to acquire the lock
:type blocking: bool
:param delay: when blocking this is ... | [
"def",
"acquire",
"(",
"self",
",",
"blocking",
"=",
"True",
",",
"delay",
"=",
"DELAY_INCREMENT",
",",
"max_delay",
"=",
"MAX_DELAY",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"delay",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Delay must be greater... | Attempt to acquire the given lock.
:param blocking: whether to wait forever to try to acquire the lock
:type blocking: bool
:param delay: when blocking this is the delay time in seconds that
will be added after each failed acquisition
:type delay: int/float
... | [
"Attempt",
"to",
"acquire",
"the",
"given",
"lock",
"."
] | 8f3bbab0204a50037448a8fad7a6bf12eb1a2695 | https://github.com/harlowja/fasteners/blob/8f3bbab0204a50037448a8fad7a6bf12eb1a2695/fasteners/process_lock.py#L130-L171 |
14,247 | harlowja/fasteners | fasteners/process_lock.py | _InterProcessLock.release | def release(self):
"""Release the previously acquired lock."""
if not self.acquired:
raise threading.ThreadError("Unable to release an unacquired"
" lock")
try:
self.unlock()
except IOError:
self.logger.exception... | python | def release(self):
"""Release the previously acquired lock."""
if not self.acquired:
raise threading.ThreadError("Unable to release an unacquired"
" lock")
try:
self.unlock()
except IOError:
self.logger.exception... | [
"def",
"release",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"acquired",
":",
"raise",
"threading",
".",
"ThreadError",
"(",
"\"Unable to release an unacquired\"",
"\" lock\"",
")",
"try",
":",
"self",
".",
"unlock",
"(",
")",
"except",
"IOError",
":",... | Release the previously acquired lock. | [
"Release",
"the",
"previously",
"acquired",
"lock",
"."
] | 8f3bbab0204a50037448a8fad7a6bf12eb1a2695 | https://github.com/harlowja/fasteners/blob/8f3bbab0204a50037448a8fad7a6bf12eb1a2695/fasteners/process_lock.py#L187-L207 |
14,248 | harlowja/fasteners | fasteners/_utils.py | canonicalize_path | def canonicalize_path(path):
"""Canonicalizes a potential path.
Returns a binary string encoded into filesystem encoding.
"""
if isinstance(path, six.binary_type):
return path
if isinstance(path, six.text_type):
return _fsencode(path)
else:
return canonicalize_path(str(p... | python | def canonicalize_path(path):
"""Canonicalizes a potential path.
Returns a binary string encoded into filesystem encoding.
"""
if isinstance(path, six.binary_type):
return path
if isinstance(path, six.text_type):
return _fsencode(path)
else:
return canonicalize_path(str(p... | [
"def",
"canonicalize_path",
"(",
"path",
")",
":",
"if",
"isinstance",
"(",
"path",
",",
"six",
".",
"binary_type",
")",
":",
"return",
"path",
"if",
"isinstance",
"(",
"path",
",",
"six",
".",
"text_type",
")",
":",
"return",
"_fsencode",
"(",
"path",
... | Canonicalizes a potential path.
Returns a binary string encoded into filesystem encoding. | [
"Canonicalizes",
"a",
"potential",
"path",
"."
] | 8f3bbab0204a50037448a8fad7a6bf12eb1a2695 | https://github.com/harlowja/fasteners/blob/8f3bbab0204a50037448a8fad7a6bf12eb1a2695/fasteners/_utils.py#L47-L57 |
14,249 | harlowja/fasteners | fasteners/lock.py | read_locked | def read_locked(*args, **kwargs):
"""Acquires & releases a read lock around call into decorated method.
NOTE(harlowja): if no attribute name is provided then by default the
attribute named '_lock' is looked for (this attribute is expected to be
a :py:class:`.ReaderWriterLock`) in the instance object th... | python | def read_locked(*args, **kwargs):
"""Acquires & releases a read lock around call into decorated method.
NOTE(harlowja): if no attribute name is provided then by default the
attribute named '_lock' is looked for (this attribute is expected to be
a :py:class:`.ReaderWriterLock`) in the instance object th... | [
"def",
"read_locked",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"attr_name",
"=",
"kwargs",
".",
"get",
"(",
"'lock'",
",",
"'_lock'",
")",
"@",
"six",
".",
"wraps",
"(",
"f",
")",
"def",
"wrappe... | Acquires & releases a read lock around call into decorated method.
NOTE(harlowja): if no attribute name is provided then by default the
attribute named '_lock' is looked for (this attribute is expected to be
a :py:class:`.ReaderWriterLock`) in the instance object this decorator
is attached to. | [
"Acquires",
"&",
"releases",
"a",
"read",
"lock",
"around",
"call",
"into",
"decorated",
"method",
"."
] | 8f3bbab0204a50037448a8fad7a6bf12eb1a2695 | https://github.com/harlowja/fasteners/blob/8f3bbab0204a50037448a8fad7a6bf12eb1a2695/fasteners/lock.py#L38-L66 |
14,250 | harlowja/fasteners | fasteners/lock.py | write_locked | def write_locked(*args, **kwargs):
"""Acquires & releases a write lock around call into decorated method.
NOTE(harlowja): if no attribute name is provided then by default the
attribute named '_lock' is looked for (this attribute is expected to be
a :py:class:`.ReaderWriterLock` object) in the instance ... | python | def write_locked(*args, **kwargs):
"""Acquires & releases a write lock around call into decorated method.
NOTE(harlowja): if no attribute name is provided then by default the
attribute named '_lock' is looked for (this attribute is expected to be
a :py:class:`.ReaderWriterLock` object) in the instance ... | [
"def",
"write_locked",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"attr_name",
"=",
"kwargs",
".",
"get",
"(",
"'lock'",
",",
"'_lock'",
")",
"@",
"six",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapp... | Acquires & releases a write lock around call into decorated method.
NOTE(harlowja): if no attribute name is provided then by default the
attribute named '_lock' is looked for (this attribute is expected to be
a :py:class:`.ReaderWriterLock` object) in the instance object this
decorator is attached to. | [
"Acquires",
"&",
"releases",
"a",
"write",
"lock",
"around",
"call",
"into",
"decorated",
"method",
"."
] | 8f3bbab0204a50037448a8fad7a6bf12eb1a2695 | https://github.com/harlowja/fasteners/blob/8f3bbab0204a50037448a8fad7a6bf12eb1a2695/fasteners/lock.py#L69-L97 |
14,251 | harlowja/fasteners | fasteners/lock.py | ReaderWriterLock.is_writer | def is_writer(self, check_pending=True):
"""Returns if the caller is the active writer or a pending writer."""
me = self._current_thread()
if self._writer == me:
return True
if check_pending:
return me in self._pending_writers
else:
return Fals... | python | def is_writer(self, check_pending=True):
"""Returns if the caller is the active writer or a pending writer."""
me = self._current_thread()
if self._writer == me:
return True
if check_pending:
return me in self._pending_writers
else:
return Fals... | [
"def",
"is_writer",
"(",
"self",
",",
"check_pending",
"=",
"True",
")",
":",
"me",
"=",
"self",
".",
"_current_thread",
"(",
")",
"if",
"self",
".",
"_writer",
"==",
"me",
":",
"return",
"True",
"if",
"check_pending",
":",
"return",
"me",
"in",
"self"... | Returns if the caller is the active writer or a pending writer. | [
"Returns",
"if",
"the",
"caller",
"is",
"the",
"active",
"writer",
"or",
"a",
"pending",
"writer",
"."
] | 8f3bbab0204a50037448a8fad7a6bf12eb1a2695 | https://github.com/harlowja/fasteners/blob/8f3bbab0204a50037448a8fad7a6bf12eb1a2695/fasteners/lock.py#L136-L144 |
14,252 | harlowja/fasteners | fasteners/lock.py | ReaderWriterLock.owner | def owner(self):
"""Returns whether the lock is locked by a writer or reader."""
if self._writer is not None:
return self.WRITER
if self._readers:
return self.READER
return None | python | def owner(self):
"""Returns whether the lock is locked by a writer or reader."""
if self._writer is not None:
return self.WRITER
if self._readers:
return self.READER
return None | [
"def",
"owner",
"(",
"self",
")",
":",
"if",
"self",
".",
"_writer",
"is",
"not",
"None",
":",
"return",
"self",
".",
"WRITER",
"if",
"self",
".",
"_readers",
":",
"return",
"self",
".",
"READER",
"return",
"None"
] | Returns whether the lock is locked by a writer or reader. | [
"Returns",
"whether",
"the",
"lock",
"is",
"locked",
"by",
"a",
"writer",
"or",
"reader",
"."
] | 8f3bbab0204a50037448a8fad7a6bf12eb1a2695 | https://github.com/harlowja/fasteners/blob/8f3bbab0204a50037448a8fad7a6bf12eb1a2695/fasteners/lock.py#L147-L153 |
14,253 | harlowja/fasteners | fasteners/lock.py | ReaderWriterLock.read_lock | def read_lock(self):
"""Context manager that grants a read lock.
Will wait until no active or pending writers.
Raises a ``RuntimeError`` if a pending writer tries to acquire
a read lock.
"""
me = self._current_thread()
if me in self._pending_writers:
... | python | def read_lock(self):
"""Context manager that grants a read lock.
Will wait until no active or pending writers.
Raises a ``RuntimeError`` if a pending writer tries to acquire
a read lock.
"""
me = self._current_thread()
if me in self._pending_writers:
... | [
"def",
"read_lock",
"(",
"self",
")",
":",
"me",
"=",
"self",
".",
"_current_thread",
"(",
")",
"if",
"me",
"in",
"self",
".",
"_pending_writers",
":",
"raise",
"RuntimeError",
"(",
"\"Writer %s can not acquire a read lock\"",
"\" while waiting for the write lock\"",
... | Context manager that grants a read lock.
Will wait until no active or pending writers.
Raises a ``RuntimeError`` if a pending writer tries to acquire
a read lock. | [
"Context",
"manager",
"that",
"grants",
"a",
"read",
"lock",
"."
] | 8f3bbab0204a50037448a8fad7a6bf12eb1a2695 | https://github.com/harlowja/fasteners/blob/8f3bbab0204a50037448a8fad7a6bf12eb1a2695/fasteners/lock.py#L161-L202 |
14,254 | harlowja/fasteners | fasteners/lock.py | ReaderWriterLock.write_lock | def write_lock(self):
"""Context manager that grants a write lock.
Will wait until no active readers. Blocks readers after acquiring.
Guaranteed for locks to be processed in fair order (FIFO).
Raises a ``RuntimeError`` if an active reader attempts to acquire
a lock.
""... | python | def write_lock(self):
"""Context manager that grants a write lock.
Will wait until no active readers. Blocks readers after acquiring.
Guaranteed for locks to be processed in fair order (FIFO).
Raises a ``RuntimeError`` if an active reader attempts to acquire
a lock.
""... | [
"def",
"write_lock",
"(",
"self",
")",
":",
"me",
"=",
"self",
".",
"_current_thread",
"(",
")",
"i_am_writer",
"=",
"self",
".",
"is_writer",
"(",
"check_pending",
"=",
"False",
")",
"if",
"self",
".",
"is_reader",
"(",
")",
"and",
"not",
"i_am_writer",... | Context manager that grants a write lock.
Will wait until no active readers. Blocks readers after acquiring.
Guaranteed for locks to be processed in fair order (FIFO).
Raises a ``RuntimeError`` if an active reader attempts to acquire
a lock. | [
"Context",
"manager",
"that",
"grants",
"a",
"write",
"lock",
"."
] | 8f3bbab0204a50037448a8fad7a6bf12eb1a2695 | https://github.com/harlowja/fasteners/blob/8f3bbab0204a50037448a8fad7a6bf12eb1a2695/fasteners/lock.py#L205-L238 |
14,255 | bfontaine/freesms | freesms/__init__.py | FreeClient.send_sms | def send_sms(self, text, **kw):
"""
Send an SMS. Since Free only allows us to send SMSes to ourselves you
don't have to provide your phone number.
"""
params = {
'user': self._user,
'pass': self._passwd,
'msg': text
}
kw.setde... | python | def send_sms(self, text, **kw):
"""
Send an SMS. Since Free only allows us to send SMSes to ourselves you
don't have to provide your phone number.
"""
params = {
'user': self._user,
'pass': self._passwd,
'msg': text
}
kw.setde... | [
"def",
"send_sms",
"(",
"self",
",",
"text",
",",
"*",
"*",
"kw",
")",
":",
"params",
"=",
"{",
"'user'",
":",
"self",
".",
"_user",
",",
"'pass'",
":",
"self",
".",
"_passwd",
",",
"'msg'",
":",
"text",
"}",
"kw",
".",
"setdefault",
"(",
"\"veri... | Send an SMS. Since Free only allows us to send SMSes to ourselves you
don't have to provide your phone number. | [
"Send",
"an",
"SMS",
".",
"Since",
"Free",
"only",
"allows",
"us",
"to",
"send",
"SMSes",
"to",
"ourselves",
"you",
"don",
"t",
"have",
"to",
"provide",
"your",
"phone",
"number",
"."
] | 64b3df222a852f313bd80afd9a7280b584fe31e1 | https://github.com/bfontaine/freesms/blob/64b3df222a852f313bd80afd9a7280b584fe31e1/freesms/__init__.py#L63-L82 |
14,256 | scrapinghub/exporters | exporters/writers/filebase_base_writer.py | FilebaseBaseWriter.create_filebase_name | def create_filebase_name(self, group_info, extension='gz', file_name=None):
"""
Return tuple of resolved destination folder name and file name
"""
dirname = self.filebase.formatted_dirname(groups=group_info)
if not file_name:
file_name = self.filebase.prefix_template ... | python | def create_filebase_name(self, group_info, extension='gz', file_name=None):
"""
Return tuple of resolved destination folder name and file name
"""
dirname = self.filebase.formatted_dirname(groups=group_info)
if not file_name:
file_name = self.filebase.prefix_template ... | [
"def",
"create_filebase_name",
"(",
"self",
",",
"group_info",
",",
"extension",
"=",
"'gz'",
",",
"file_name",
"=",
"None",
")",
":",
"dirname",
"=",
"self",
".",
"filebase",
".",
"formatted_dirname",
"(",
"groups",
"=",
"group_info",
")",
"if",
"not",
"f... | Return tuple of resolved destination folder name and file name | [
"Return",
"tuple",
"of",
"resolved",
"destination",
"folder",
"name",
"and",
"file",
"name"
] | c9fb01db1771ada4672bbffd67cb46e1f7802ab9 | https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/writers/filebase_base_writer.py#L145-L152 |
14,257 | scrapinghub/exporters | exporters/writers/aggregation_stats_writer.py | AggregationStatsWriter.write_batch | def write_batch(self, batch):
"""
Receives the batch and writes it. This method is usually called from a manager.
"""
for item in batch:
for key in item:
self.aggregated_info['occurrences'][key] += 1
self.increment_written_items()
if se... | python | def write_batch(self, batch):
"""
Receives the batch and writes it. This method is usually called from a manager.
"""
for item in batch:
for key in item:
self.aggregated_info['occurrences'][key] += 1
self.increment_written_items()
if se... | [
"def",
"write_batch",
"(",
"self",
",",
"batch",
")",
":",
"for",
"item",
"in",
"batch",
":",
"for",
"key",
"in",
"item",
":",
"self",
".",
"aggregated_info",
"[",
"'occurrences'",
"]",
"[",
"key",
"]",
"+=",
"1",
"self",
".",
"increment_written_items",
... | Receives the batch and writes it. This method is usually called from a manager. | [
"Receives",
"the",
"batch",
"and",
"writes",
"it",
".",
"This",
"method",
"is",
"usually",
"called",
"from",
"a",
"manager",
"."
] | c9fb01db1771ada4672bbffd67cb46e1f7802ab9 | https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/writers/aggregation_stats_writer.py#L18-L29 |
14,258 | scrapinghub/exporters | exporters/writers/aggregation_stats_writer.py | AggregationStatsWriter._get_aggregated_info | def _get_aggregated_info(self):
"""
Keeps track of aggregated info in a dictionary called self.aggregated_info
"""
agg_results = {}
for key in self.aggregated_info['occurrences']:
agg_results[key] = {
'occurrences': self.aggregated_info['occurrences'].... | python | def _get_aggregated_info(self):
"""
Keeps track of aggregated info in a dictionary called self.aggregated_info
"""
agg_results = {}
for key in self.aggregated_info['occurrences']:
agg_results[key] = {
'occurrences': self.aggregated_info['occurrences'].... | [
"def",
"_get_aggregated_info",
"(",
"self",
")",
":",
"agg_results",
"=",
"{",
"}",
"for",
"key",
"in",
"self",
".",
"aggregated_info",
"[",
"'occurrences'",
"]",
":",
"agg_results",
"[",
"key",
"]",
"=",
"{",
"'occurrences'",
":",
"self",
".",
"aggregated... | Keeps track of aggregated info in a dictionary called self.aggregated_info | [
"Keeps",
"track",
"of",
"aggregated",
"info",
"in",
"a",
"dictionary",
"called",
"self",
".",
"aggregated_info"
] | c9fb01db1771ada4672bbffd67cb46e1f7802ab9 | https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/writers/aggregation_stats_writer.py#L31-L42 |
14,259 | scrapinghub/exporters | exporters/writers/cloudsearch_writer.py | create_document_batches | def create_document_batches(jsonlines, id_field, max_batch_size=CLOUDSEARCH_MAX_BATCH_SIZE):
"""Create batches in expected AWS Cloudsearch format, limiting the
byte size per batch according to given max_batch_size
See: http://docs.aws.amazon.com/cloudsearch/latest/developerguide/preparing-data.html
"""... | python | def create_document_batches(jsonlines, id_field, max_batch_size=CLOUDSEARCH_MAX_BATCH_SIZE):
"""Create batches in expected AWS Cloudsearch format, limiting the
byte size per batch according to given max_batch_size
See: http://docs.aws.amazon.com/cloudsearch/latest/developerguide/preparing-data.html
"""... | [
"def",
"create_document_batches",
"(",
"jsonlines",
",",
"id_field",
",",
"max_batch_size",
"=",
"CLOUDSEARCH_MAX_BATCH_SIZE",
")",
":",
"batch",
"=",
"[",
"]",
"fixed_initial_size",
"=",
"2",
"def",
"create_entry",
"(",
"line",
")",
":",
"try",
":",
"record",
... | Create batches in expected AWS Cloudsearch format, limiting the
byte size per batch according to given max_batch_size
See: http://docs.aws.amazon.com/cloudsearch/latest/developerguide/preparing-data.html | [
"Create",
"batches",
"in",
"expected",
"AWS",
"Cloudsearch",
"format",
"limiting",
"the",
"byte",
"size",
"per",
"batch",
"according",
"to",
"given",
"max_batch_size"
] | c9fb01db1771ada4672bbffd67cb46e1f7802ab9 | https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/writers/cloudsearch_writer.py#L14-L45 |
14,260 | scrapinghub/exporters | exporters/writers/cloudsearch_writer.py | CloudSearchWriter._post_document_batch | def _post_document_batch(self, batch):
"""
Send a batch to Cloudsearch endpoint
See: http://docs.aws.amazon.com/cloudsearch/latest/developerguide/submitting-doc-requests.html
""" # noqa
target_batch = '/2013-01-01/documents/batch'
url = self.endpoint_url + target_batch
... | python | def _post_document_batch(self, batch):
"""
Send a batch to Cloudsearch endpoint
See: http://docs.aws.amazon.com/cloudsearch/latest/developerguide/submitting-doc-requests.html
""" # noqa
target_batch = '/2013-01-01/documents/batch'
url = self.endpoint_url + target_batch
... | [
"def",
"_post_document_batch",
"(",
"self",
",",
"batch",
")",
":",
"# noqa",
"target_batch",
"=",
"'/2013-01-01/documents/batch'",
"url",
"=",
"self",
".",
"endpoint_url",
"+",
"target_batch",
"return",
"requests",
".",
"post",
"(",
"url",
",",
"data",
"=",
"... | Send a batch to Cloudsearch endpoint
See: http://docs.aws.amazon.com/cloudsearch/latest/developerguide/submitting-doc-requests.html | [
"Send",
"a",
"batch",
"to",
"Cloudsearch",
"endpoint"
] | c9fb01db1771ada4672bbffd67cb46e1f7802ab9 | https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/writers/cloudsearch_writer.py#L97-L105 |
14,261 | scrapinghub/exporters | exporters/writers/fs_writer.py | FSWriter._create_path_if_not_exist | def _create_path_if_not_exist(self, path):
"""
Creates a folders path if it doesn't exist
"""
if path and not os.path.exists(path):
os.makedirs(path) | python | def _create_path_if_not_exist(self, path):
"""
Creates a folders path if it doesn't exist
"""
if path and not os.path.exists(path):
os.makedirs(path) | [
"def",
"_create_path_if_not_exist",
"(",
"self",
",",
"path",
")",
":",
"if",
"path",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"os",
".",
"makedirs",
"(",
"path",
")"
] | Creates a folders path if it doesn't exist | [
"Creates",
"a",
"folders",
"path",
"if",
"it",
"doesn",
"t",
"exist"
] | c9fb01db1771ada4672bbffd67cb46e1f7802ab9 | https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/writers/fs_writer.py#L26-L31 |
14,262 | scrapinghub/exporters | exporters/writers/s3_writer.py | S3Writer.close | def close(self):
"""
Called to clean all possible tmp files created during the process.
"""
if self.read_option('save_pointer'):
self._update_last_pointer()
super(S3Writer, self).close() | python | def close(self):
"""
Called to clean all possible tmp files created during the process.
"""
if self.read_option('save_pointer'):
self._update_last_pointer()
super(S3Writer, self).close() | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"read_option",
"(",
"'save_pointer'",
")",
":",
"self",
".",
"_update_last_pointer",
"(",
")",
"super",
"(",
"S3Writer",
",",
"self",
")",
".",
"close",
"(",
")"
] | Called to clean all possible tmp files created during the process. | [
"Called",
"to",
"clean",
"all",
"possible",
"tmp",
"files",
"created",
"during",
"the",
"process",
"."
] | c9fb01db1771ada4672bbffd67cb46e1f7802ab9 | https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/writers/s3_writer.py#L207-L213 |
14,263 | scrapinghub/exporters | exporters/utils.py | get_boto_connection | def get_boto_connection(aws_access_key_id, aws_secret_access_key, region=None, bucketname=None,
host=None):
"""
Conection parameters must be different only if bucket name has a period
"""
m = _AWS_ACCESS_KEY_ID_RE.match(aws_access_key_id)
if m is None or m.group() != aws_acce... | python | def get_boto_connection(aws_access_key_id, aws_secret_access_key, region=None, bucketname=None,
host=None):
"""
Conection parameters must be different only if bucket name has a period
"""
m = _AWS_ACCESS_KEY_ID_RE.match(aws_access_key_id)
if m is None or m.group() != aws_acce... | [
"def",
"get_boto_connection",
"(",
"aws_access_key_id",
",",
"aws_secret_access_key",
",",
"region",
"=",
"None",
",",
"bucketname",
"=",
"None",
",",
"host",
"=",
"None",
")",
":",
"m",
"=",
"_AWS_ACCESS_KEY_ID_RE",
".",
"match",
"(",
"aws_access_key_id",
")",
... | Conection parameters must be different only if bucket name has a period | [
"Conection",
"parameters",
"must",
"be",
"different",
"only",
"if",
"bucket",
"name",
"has",
"a",
"period"
] | c9fb01db1771ada4672bbffd67cb46e1f7802ab9 | https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/utils.py#L115-L140 |
14,264 | scrapinghub/exporters | exporters/utils.py | maybe_cast_list | def maybe_cast_list(value, types):
"""
Try to coerce list values into more specific list subclasses in types.
"""
if not isinstance(value, list):
return value
if type(types) not in (list, tuple):
types = (types,)
for list_type in types:
if issubclass(list_type, list):
... | python | def maybe_cast_list(value, types):
"""
Try to coerce list values into more specific list subclasses in types.
"""
if not isinstance(value, list):
return value
if type(types) not in (list, tuple):
types = (types,)
for list_type in types:
if issubclass(list_type, list):
... | [
"def",
"maybe_cast_list",
"(",
"value",
",",
"types",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"return",
"value",
"if",
"type",
"(",
"types",
")",
"not",
"in",
"(",
"list",
",",
"tuple",
")",
":",
"types",
"=",
"(",... | Try to coerce list values into more specific list subclasses in types. | [
"Try",
"to",
"coerce",
"list",
"values",
"into",
"more",
"specific",
"list",
"subclasses",
"in",
"types",
"."
] | c9fb01db1771ada4672bbffd67cb46e1f7802ab9 | https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/utils.py#L143-L159 |
14,265 | scrapinghub/exporters | exporters/iterio.py | iterate_chunks | def iterate_chunks(file, chunk_size):
"""
Iterate chunks of size chunk_size from a file-like object
"""
chunk = file.read(chunk_size)
while chunk:
yield chunk
chunk = file.read(chunk_size) | python | def iterate_chunks(file, chunk_size):
"""
Iterate chunks of size chunk_size from a file-like object
"""
chunk = file.read(chunk_size)
while chunk:
yield chunk
chunk = file.read(chunk_size) | [
"def",
"iterate_chunks",
"(",
"file",
",",
"chunk_size",
")",
":",
"chunk",
"=",
"file",
".",
"read",
"(",
"chunk_size",
")",
"while",
"chunk",
":",
"yield",
"chunk",
"chunk",
"=",
"file",
".",
"read",
"(",
"chunk_size",
")"
] | Iterate chunks of size chunk_size from a file-like object | [
"Iterate",
"chunks",
"of",
"size",
"chunk_size",
"from",
"a",
"file",
"-",
"like",
"object"
] | c9fb01db1771ada4672bbffd67cb46e1f7802ab9 | https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/iterio.py#L15-L22 |
14,266 | scrapinghub/exporters | exporters/iterio.py | IterIO.unshift | def unshift(self, chunk):
"""
Pushes a chunk of data back into the internal buffer. This is useful
in certain situations where a stream is being consumed by code that
needs to "un-consume" some amount of data that it has optimistically
pulled out of the source, so that the data c... | python | def unshift(self, chunk):
"""
Pushes a chunk of data back into the internal buffer. This is useful
in certain situations where a stream is being consumed by code that
needs to "un-consume" some amount of data that it has optimistically
pulled out of the source, so that the data c... | [
"def",
"unshift",
"(",
"self",
",",
"chunk",
")",
":",
"if",
"chunk",
":",
"self",
".",
"_pos",
"-=",
"len",
"(",
"chunk",
")",
"self",
".",
"_unconsumed",
".",
"append",
"(",
"chunk",
")"
] | Pushes a chunk of data back into the internal buffer. This is useful
in certain situations where a stream is being consumed by code that
needs to "un-consume" some amount of data that it has optimistically
pulled out of the source, so that the data can be passed on to some
other party. | [
"Pushes",
"a",
"chunk",
"of",
"data",
"back",
"into",
"the",
"internal",
"buffer",
".",
"This",
"is",
"useful",
"in",
"certain",
"situations",
"where",
"a",
"stream",
"is",
"being",
"consumed",
"by",
"code",
"that",
"needs",
"to",
"un",
"-",
"consume",
"... | c9fb01db1771ada4672bbffd67cb46e1f7802ab9 | https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/iterio.py#L46-L56 |
14,267 | scrapinghub/exporters | exporters/iterio.py | IterIO.readline | def readline(self):
"""
Read until a new-line character is encountered
"""
line = ""
n_pos = -1
try:
while n_pos < 0:
line += self.next_chunk()
n_pos = line.find('\n')
except StopIteration:
pass
if n... | python | def readline(self):
"""
Read until a new-line character is encountered
"""
line = ""
n_pos = -1
try:
while n_pos < 0:
line += self.next_chunk()
n_pos = line.find('\n')
except StopIteration:
pass
if n... | [
"def",
"readline",
"(",
"self",
")",
":",
"line",
"=",
"\"\"",
"n_pos",
"=",
"-",
"1",
"try",
":",
"while",
"n_pos",
"<",
"0",
":",
"line",
"+=",
"self",
".",
"next_chunk",
"(",
")",
"n_pos",
"=",
"line",
".",
"find",
"(",
"'\\n'",
")",
"except",... | Read until a new-line character is encountered | [
"Read",
"until",
"a",
"new",
"-",
"line",
"character",
"is",
"encountered"
] | c9fb01db1771ada4672bbffd67cb46e1f7802ab9 | https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/iterio.py#L110-L126 |
14,268 | scrapinghub/exporters | exporters/iterio.py | IterIO.close | def close(self):
"""
Disable al operations and close the underlying file-like object, if any
"""
if callable(getattr(self._file, 'close', None)):
self._iterator.close()
self._iterator = None
self._unconsumed = None
self.closed = True | python | def close(self):
"""
Disable al operations and close the underlying file-like object, if any
"""
if callable(getattr(self._file, 'close', None)):
self._iterator.close()
self._iterator = None
self._unconsumed = None
self.closed = True | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"callable",
"(",
"getattr",
"(",
"self",
".",
"_file",
",",
"'close'",
",",
"None",
")",
")",
":",
"self",
".",
"_iterator",
".",
"close",
"(",
")",
"self",
".",
"_iterator",
"=",
"None",
"self",
".",
... | Disable al operations and close the underlying file-like object, if any | [
"Disable",
"al",
"operations",
"and",
"close",
"the",
"underlying",
"file",
"-",
"like",
"object",
"if",
"any"
] | c9fb01db1771ada4672bbffd67cb46e1f7802ab9 | https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/iterio.py#L148-L156 |
14,269 | scrapinghub/exporters | exporters/persistence/pickle_persistence.py | PicklePersistence.configuration_from_uri | def configuration_from_uri(uri, uri_regex):
"""
returns a configuration object.
"""
file_path = re.match(uri_regex, uri).groups()[0]
with open(file_path) as f:
configuration = pickle.load(f)['configuration']
configuration = yaml.safe_load(configuration)
... | python | def configuration_from_uri(uri, uri_regex):
"""
returns a configuration object.
"""
file_path = re.match(uri_regex, uri).groups()[0]
with open(file_path) as f:
configuration = pickle.load(f)['configuration']
configuration = yaml.safe_load(configuration)
... | [
"def",
"configuration_from_uri",
"(",
"uri",
",",
"uri_regex",
")",
":",
"file_path",
"=",
"re",
".",
"match",
"(",
"uri_regex",
",",
"uri",
")",
".",
"groups",
"(",
")",
"[",
"0",
"]",
"with",
"open",
"(",
"file_path",
")",
"as",
"f",
":",
"configur... | returns a configuration object. | [
"returns",
"a",
"configuration",
"object",
"."
] | c9fb01db1771ada4672bbffd67cb46e1f7802ab9 | https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/persistence/pickle_persistence.py#L77-L88 |
14,270 | scrapinghub/exporters | exporters/write_buffers/base.py | WriteBuffer.buffer | def buffer(self, item):
"""
Receive an item and write it.
"""
key = self.get_key_from_item(item)
if not self.grouping_info.is_first_file_item(key):
self.items_group_files.add_item_separator_to_file(key)
self.grouping_info.ensure_group_info(key)
self.it... | python | def buffer(self, item):
"""
Receive an item and write it.
"""
key = self.get_key_from_item(item)
if not self.grouping_info.is_first_file_item(key):
self.items_group_files.add_item_separator_to_file(key)
self.grouping_info.ensure_group_info(key)
self.it... | [
"def",
"buffer",
"(",
"self",
",",
"item",
")",
":",
"key",
"=",
"self",
".",
"get_key_from_item",
"(",
"item",
")",
"if",
"not",
"self",
".",
"grouping_info",
".",
"is_first_file_item",
"(",
"key",
")",
":",
"self",
".",
"items_group_files",
".",
"add_i... | Receive an item and write it. | [
"Receive",
"an",
"item",
"and",
"write",
"it",
"."
] | c9fb01db1771ada4672bbffd67cb46e1f7802ab9 | https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/write_buffers/base.py#L29-L37 |
14,271 | scrapinghub/exporters | exporters/persistence/alchemy_persistence.py | BaseAlchemyPersistence.parse_persistence_uri | def parse_persistence_uri(cls, persistence_uri):
"""Parse a database URI and the persistence state ID from
the given persistence URI
"""
regex = cls.persistence_uri_re
match = re.match(regex, persistence_uri)
if not match:
raise ValueError("Couldn't parse pers... | python | def parse_persistence_uri(cls, persistence_uri):
"""Parse a database URI and the persistence state ID from
the given persistence URI
"""
regex = cls.persistence_uri_re
match = re.match(regex, persistence_uri)
if not match:
raise ValueError("Couldn't parse pers... | [
"def",
"parse_persistence_uri",
"(",
"cls",
",",
"persistence_uri",
")",
":",
"regex",
"=",
"cls",
".",
"persistence_uri_re",
"match",
"=",
"re",
".",
"match",
"(",
"regex",
",",
"persistence_uri",
")",
"if",
"not",
"match",
":",
"raise",
"ValueError",
"(",
... | Parse a database URI and the persistence state ID from
the given persistence URI | [
"Parse",
"a",
"database",
"URI",
"and",
"the",
"persistence",
"state",
"ID",
"from",
"the",
"given",
"persistence",
"URI"
] | c9fb01db1771ada4672bbffd67cb46e1f7802ab9 | https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/persistence/alchemy_persistence.py#L104-L122 |
14,272 | scrapinghub/exporters | exporters/persistence/alchemy_persistence.py | BaseAlchemyPersistence.configuration_from_uri | def configuration_from_uri(cls, persistence_uri):
"""
Return a configuration object.
"""
db_uri, persistence_state_id = cls.parse_persistence_uri(persistence_uri)
engine = create_engine(db_uri)
Base.metadata.create_all(engine)
Base.metadata.bind = engine
D... | python | def configuration_from_uri(cls, persistence_uri):
"""
Return a configuration object.
"""
db_uri, persistence_state_id = cls.parse_persistence_uri(persistence_uri)
engine = create_engine(db_uri)
Base.metadata.create_all(engine)
Base.metadata.bind = engine
D... | [
"def",
"configuration_from_uri",
"(",
"cls",
",",
"persistence_uri",
")",
":",
"db_uri",
",",
"persistence_state_id",
"=",
"cls",
".",
"parse_persistence_uri",
"(",
"persistence_uri",
")",
"engine",
"=",
"create_engine",
"(",
"db_uri",
")",
"Base",
".",
"metadata"... | Return a configuration object. | [
"Return",
"a",
"configuration",
"object",
"."
] | c9fb01db1771ada4672bbffd67cb46e1f7802ab9 | https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/persistence/alchemy_persistence.py#L125-L140 |
14,273 | scrapinghub/exporters | exporters/readers/fs_reader.py | FSReader._get_input_files | def _get_input_files(cls, input_specification):
"""Get list of input files according to input definition.
Input definition can be:
- str: specifying a filename
- list of str: specifying list a of filenames
- dict with "dir" and optional "pattern" parameters: specifying the
... | python | def _get_input_files(cls, input_specification):
"""Get list of input files according to input definition.
Input definition can be:
- str: specifying a filename
- list of str: specifying list a of filenames
- dict with "dir" and optional "pattern" parameters: specifying the
... | [
"def",
"_get_input_files",
"(",
"cls",
",",
"input_specification",
")",
":",
"if",
"isinstance",
"(",
"input_specification",
",",
"(",
"basestring",
",",
"dict",
")",
")",
":",
"input_specification",
"=",
"[",
"input_specification",
"]",
"elif",
"not",
"isinstan... | Get list of input files according to input definition.
Input definition can be:
- str: specifying a filename
- list of str: specifying list a of filenames
- dict with "dir" and optional "pattern" parameters: specifying the
toplevel directory under which input files will be so... | [
"Get",
"list",
"of",
"input",
"files",
"according",
"to",
"input",
"definition",
"."
] | c9fb01db1771ada4672bbffd67cb46e1f7802ab9 | https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/readers/fs_reader.py#L59-L103 |
14,274 | scrapinghub/exporters | exporters/readers/kafka_random_reader.py | KafkaRandomReader.consume_messages | def consume_messages(self, batchsize):
""" Get messages batch from the reservoir """
if not self._reservoir:
self.finished = True
return
for msg in self._reservoir[:batchsize]:
yield msg
self._reservoir = self._reservoir[batchsize:] | python | def consume_messages(self, batchsize):
""" Get messages batch from the reservoir """
if not self._reservoir:
self.finished = True
return
for msg in self._reservoir[:batchsize]:
yield msg
self._reservoir = self._reservoir[batchsize:] | [
"def",
"consume_messages",
"(",
"self",
",",
"batchsize",
")",
":",
"if",
"not",
"self",
".",
"_reservoir",
":",
"self",
".",
"finished",
"=",
"True",
"return",
"for",
"msg",
"in",
"self",
".",
"_reservoir",
"[",
":",
"batchsize",
"]",
":",
"yield",
"m... | Get messages batch from the reservoir | [
"Get",
"messages",
"batch",
"from",
"the",
"reservoir"
] | c9fb01db1771ada4672bbffd67cb46e1f7802ab9 | https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/readers/kafka_random_reader.py#L127-L134 |
14,275 | scrapinghub/exporters | exporters/readers/kafka_random_reader.py | KafkaRandomReader.decompress_messages | def decompress_messages(self, offmsgs):
""" Decompress pre-defined compressed fields for each message.
Msgs should be unpacked before this step. """
for offmsg in offmsgs:
yield offmsg.message.key, self.decompress_fun(offmsg.message.value) | python | def decompress_messages(self, offmsgs):
""" Decompress pre-defined compressed fields for each message.
Msgs should be unpacked before this step. """
for offmsg in offmsgs:
yield offmsg.message.key, self.decompress_fun(offmsg.message.value) | [
"def",
"decompress_messages",
"(",
"self",
",",
"offmsgs",
")",
":",
"for",
"offmsg",
"in",
"offmsgs",
":",
"yield",
"offmsg",
".",
"message",
".",
"key",
",",
"self",
".",
"decompress_fun",
"(",
"offmsg",
".",
"message",
".",
"value",
")"
] | Decompress pre-defined compressed fields for each message.
Msgs should be unpacked before this step. | [
"Decompress",
"pre",
"-",
"defined",
"compressed",
"fields",
"for",
"each",
"message",
".",
"Msgs",
"should",
"be",
"unpacked",
"before",
"this",
"step",
"."
] | c9fb01db1771ada4672bbffd67cb46e1f7802ab9 | https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/readers/kafka_random_reader.py#L136-L141 |
14,276 | scrapinghub/exporters | exporters/filters/base_filter.py | BaseFilter.filter_batch | def filter_batch(self, batch):
"""
Receives the batch, filters it, and returns it.
"""
for item in batch:
if self.filter(item):
yield item
else:
self.set_metadata('filtered_out',
self.get_metadata('... | python | def filter_batch(self, batch):
"""
Receives the batch, filters it, and returns it.
"""
for item in batch:
if self.filter(item):
yield item
else:
self.set_metadata('filtered_out',
self.get_metadata('... | [
"def",
"filter_batch",
"(",
"self",
",",
"batch",
")",
":",
"for",
"item",
"in",
"batch",
":",
"if",
"self",
".",
"filter",
"(",
"item",
")",
":",
"yield",
"item",
"else",
":",
"self",
".",
"set_metadata",
"(",
"'filtered_out'",
",",
"self",
".",
"ge... | Receives the batch, filters it, and returns it. | [
"Receives",
"the",
"batch",
"filters",
"it",
"and",
"returns",
"it",
"."
] | c9fb01db1771ada4672bbffd67cb46e1f7802ab9 | https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/filters/base_filter.py#L24-L36 |
14,277 | scrapinghub/exporters | exporters/writers/base_writer.py | BaseWriter.write_batch | def write_batch(self, batch):
"""
Buffer a batch of items to be written and update internal counters.
Calling this method doesn't guarantee that all items have been written.
To ensure everything has been written you need to call flush().
"""
for item in batch:
... | python | def write_batch(self, batch):
"""
Buffer a batch of items to be written and update internal counters.
Calling this method doesn't guarantee that all items have been written.
To ensure everything has been written you need to call flush().
"""
for item in batch:
... | [
"def",
"write_batch",
"(",
"self",
",",
"batch",
")",
":",
"for",
"item",
"in",
"batch",
":",
"self",
".",
"write_buffer",
".",
"buffer",
"(",
"item",
")",
"key",
"=",
"self",
".",
"write_buffer",
".",
"get_key_from_item",
"(",
"item",
")",
"if",
"self... | Buffer a batch of items to be written and update internal counters.
Calling this method doesn't guarantee that all items have been written.
To ensure everything has been written you need to call flush(). | [
"Buffer",
"a",
"batch",
"of",
"items",
"to",
"be",
"written",
"and",
"update",
"internal",
"counters",
"."
] | c9fb01db1771ada4672bbffd67cb46e1f7802ab9 | https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/writers/base_writer.py#L103-L116 |
14,278 | scrapinghub/exporters | exporters/writers/base_writer.py | BaseWriter._check_items_limit | def _check_items_limit(self):
"""
Raise ItemsLimitReached if the writer reached the configured items limit.
"""
if self.items_limit and self.items_limit == self.get_metadata('items_count'):
raise ItemsLimitReached('Finishing job after items_limit reached:'
... | python | def _check_items_limit(self):
"""
Raise ItemsLimitReached if the writer reached the configured items limit.
"""
if self.items_limit and self.items_limit == self.get_metadata('items_count'):
raise ItemsLimitReached('Finishing job after items_limit reached:'
... | [
"def",
"_check_items_limit",
"(",
"self",
")",
":",
"if",
"self",
".",
"items_limit",
"and",
"self",
".",
"items_limit",
"==",
"self",
".",
"get_metadata",
"(",
"'items_count'",
")",
":",
"raise",
"ItemsLimitReached",
"(",
"'Finishing job after items_limit reached:'... | Raise ItemsLimitReached if the writer reached the configured items limit. | [
"Raise",
"ItemsLimitReached",
"if",
"the",
"writer",
"reached",
"the",
"configured",
"items",
"limit",
"."
] | c9fb01db1771ada4672bbffd67cb46e1f7802ab9 | https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/writers/base_writer.py#L118-L124 |
14,279 | scrapinghub/exporters | exporters/writers/base_writer.py | BaseWriter.flush | def flush(self):
"""
Ensure all remaining buffers are written.
"""
for key in self.grouping_info.keys():
if self._should_flush(key):
self._write_current_buffer_for_group_key(key) | python | def flush(self):
"""
Ensure all remaining buffers are written.
"""
for key in self.grouping_info.keys():
if self._should_flush(key):
self._write_current_buffer_for_group_key(key) | [
"def",
"flush",
"(",
"self",
")",
":",
"for",
"key",
"in",
"self",
".",
"grouping_info",
".",
"keys",
"(",
")",
":",
"if",
"self",
".",
"_should_flush",
"(",
"key",
")",
":",
"self",
".",
"_write_current_buffer_for_group_key",
"(",
"key",
")"
] | Ensure all remaining buffers are written. | [
"Ensure",
"all",
"remaining",
"buffers",
"are",
"written",
"."
] | c9fb01db1771ada4672bbffd67cb46e1f7802ab9 | https://github.com/scrapinghub/exporters/blob/c9fb01db1771ada4672bbffd67cb46e1f7802ab9/exporters/writers/base_writer.py#L129-L135 |
14,280 | opendatateam/udata | udata/assets.py | has_manifest | def has_manifest(app, filename='manifest.json'):
'''Verify the existance of a JSON assets manifest'''
try:
return pkg_resources.resource_exists(app, filename)
except ImportError:
return os.path.isabs(filename) and os.path.exists(filename) | python | def has_manifest(app, filename='manifest.json'):
'''Verify the existance of a JSON assets manifest'''
try:
return pkg_resources.resource_exists(app, filename)
except ImportError:
return os.path.isabs(filename) and os.path.exists(filename) | [
"def",
"has_manifest",
"(",
"app",
",",
"filename",
"=",
"'manifest.json'",
")",
":",
"try",
":",
"return",
"pkg_resources",
".",
"resource_exists",
"(",
"app",
",",
"filename",
")",
"except",
"ImportError",
":",
"return",
"os",
".",
"path",
".",
"isabs",
... | Verify the existance of a JSON assets manifest | [
"Verify",
"the",
"existance",
"of",
"a",
"JSON",
"assets",
"manifest"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/assets.py#L19-L24 |
14,281 | opendatateam/udata | udata/assets.py | register_manifest | def register_manifest(app, filename='manifest.json'):
'''Register an assets json manifest'''
if current_app.config.get('TESTING'):
return # Do not spend time here when testing
if not has_manifest(app, filename):
msg = '{filename} not found for {app}'.format(**locals())
raise ValueEr... | python | def register_manifest(app, filename='manifest.json'):
'''Register an assets json manifest'''
if current_app.config.get('TESTING'):
return # Do not spend time here when testing
if not has_manifest(app, filename):
msg = '{filename} not found for {app}'.format(**locals())
raise ValueEr... | [
"def",
"register_manifest",
"(",
"app",
",",
"filename",
"=",
"'manifest.json'",
")",
":",
"if",
"current_app",
".",
"config",
".",
"get",
"(",
"'TESTING'",
")",
":",
"return",
"# Do not spend time here when testing",
"if",
"not",
"has_manifest",
"(",
"app",
","... | Register an assets json manifest | [
"Register",
"an",
"assets",
"json",
"manifest"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/assets.py#L27-L36 |
14,282 | opendatateam/udata | udata/assets.py | load_manifest | def load_manifest(app, filename='manifest.json'):
'''Load an assets json manifest'''
if os.path.isabs(filename):
path = filename
else:
path = pkg_resources.resource_filename(app, filename)
with io.open(path, mode='r', encoding='utf8') as stream:
data = json.load(stream)
_regi... | python | def load_manifest(app, filename='manifest.json'):
'''Load an assets json manifest'''
if os.path.isabs(filename):
path = filename
else:
path = pkg_resources.resource_filename(app, filename)
with io.open(path, mode='r', encoding='utf8') as stream:
data = json.load(stream)
_regi... | [
"def",
"load_manifest",
"(",
"app",
",",
"filename",
"=",
"'manifest.json'",
")",
":",
"if",
"os",
".",
"path",
".",
"isabs",
"(",
"filename",
")",
":",
"path",
"=",
"filename",
"else",
":",
"path",
"=",
"pkg_resources",
".",
"resource_filename",
"(",
"a... | Load an assets json manifest | [
"Load",
"an",
"assets",
"json",
"manifest"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/assets.py#L39-L48 |
14,283 | opendatateam/udata | udata/assets.py | from_manifest | def from_manifest(app, filename, raw=False, **kwargs):
'''
Get the path to a static file for a given app entry of a given type.
:param str app: The application key to which is tied this manifest
:param str filename: the original filename (without hash)
:param bool raw: if True, doesn't add prefix t... | python | def from_manifest(app, filename, raw=False, **kwargs):
'''
Get the path to a static file for a given app entry of a given type.
:param str app: The application key to which is tied this manifest
:param str filename: the original filename (without hash)
:param bool raw: if True, doesn't add prefix t... | [
"def",
"from_manifest",
"(",
"app",
",",
"filename",
",",
"raw",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"cfg",
"=",
"current_app",
".",
"config",
"if",
"current_app",
".",
"config",
".",
"get",
"(",
"'TESTING'",
")",
":",
"return",
"# Do not ... | Get the path to a static file for a given app entry of a given type.
:param str app: The application key to which is tied this manifest
:param str filename: the original filename (without hash)
:param bool raw: if True, doesn't add prefix to the manifest
:return: the resolved file path from manifest
... | [
"Get",
"the",
"path",
"to",
"a",
"static",
"file",
"for",
"a",
"given",
"app",
"entry",
"of",
"a",
"given",
"type",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/assets.py#L58-L85 |
14,284 | opendatateam/udata | udata/assets.py | cdn_for | def cdn_for(endpoint, **kwargs):
'''
Get a CDN URL for a static assets.
Do not use a replacement for all flask.url_for calls
as it is only meant for CDN assets URLS.
(There is some extra round trip which cost is justified
by the CDN assets prformance improvements)
'''
if current_app.con... | python | def cdn_for(endpoint, **kwargs):
'''
Get a CDN URL for a static assets.
Do not use a replacement for all flask.url_for calls
as it is only meant for CDN assets URLS.
(There is some extra round trip which cost is justified
by the CDN assets prformance improvements)
'''
if current_app.con... | [
"def",
"cdn_for",
"(",
"endpoint",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"current_app",
".",
"config",
"[",
"'CDN_DOMAIN'",
"]",
":",
"if",
"not",
"current_app",
".",
"config",
".",
"get",
"(",
"'CDN_DEBUG'",
")",
":",
"kwargs",
".",
"pop",
"(",
"... | Get a CDN URL for a static assets.
Do not use a replacement for all flask.url_for calls
as it is only meant for CDN assets URLS.
(There is some extra round trip which cost is justified
by the CDN assets prformance improvements) | [
"Get",
"a",
"CDN",
"URL",
"for",
"a",
"static",
"assets",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/assets.py#L92-L105 |
14,285 | opendatateam/udata | udata/models/queryset.py | UDataQuerySet.get_or_create | def get_or_create(self, write_concern=None, auto_save=True,
*q_objs, **query):
"""Retrieve unique object or create, if it doesn't exist.
Returns a tuple of ``(object, created)``, where ``object`` is
the retrieved or created object and ``created`` is a boolean
speci... | python | def get_or_create(self, write_concern=None, auto_save=True,
*q_objs, **query):
"""Retrieve unique object or create, if it doesn't exist.
Returns a tuple of ``(object, created)``, where ``object`` is
the retrieved or created object and ``created`` is a boolean
speci... | [
"def",
"get_or_create",
"(",
"self",
",",
"write_concern",
"=",
"None",
",",
"auto_save",
"=",
"True",
",",
"*",
"q_objs",
",",
"*",
"*",
"query",
")",
":",
"defaults",
"=",
"query",
".",
"pop",
"(",
"'defaults'",
",",
"{",
"}",
")",
"try",
":",
"d... | Retrieve unique object or create, if it doesn't exist.
Returns a tuple of ``(object, created)``, where ``object`` is
the retrieved or created object and ``created`` is a boolean
specifying whether a new object was created.
Taken back from:
https://github.com/MongoEngine/mongoe... | [
"Retrieve",
"unique",
"object",
"or",
"create",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/models/queryset.py#L50-L73 |
14,286 | opendatateam/udata | udata/models/queryset.py | UDataQuerySet.generic_in | def generic_in(self, **kwargs):
'''Bypass buggy GenericReferenceField querying issue'''
query = {}
for key, value in kwargs.items():
if not value:
continue
# Optimize query for when there is only one value
if isinstance(value, (list, tuple)) an... | python | def generic_in(self, **kwargs):
'''Bypass buggy GenericReferenceField querying issue'''
query = {}
for key, value in kwargs.items():
if not value:
continue
# Optimize query for when there is only one value
if isinstance(value, (list, tuple)) an... | [
"def",
"generic_in",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"query",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"not",
"value",
":",
"continue",
"# Optimize query for when there is only one value"... | Bypass buggy GenericReferenceField querying issue | [
"Bypass",
"buggy",
"GenericReferenceField",
"querying",
"issue"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/models/queryset.py#L75-L98 |
14,287 | opendatateam/udata | udata/core/issues/notifications.py | issues_notifications | def issues_notifications(user):
'''Notify user about open issues'''
notifications = []
# Only fetch required fields for notification serialization
# Greatly improve performances and memory usage
qs = issues_for(user).only('id', 'title', 'created', 'subject')
# Do not dereference subject (so it... | python | def issues_notifications(user):
'''Notify user about open issues'''
notifications = []
# Only fetch required fields for notification serialization
# Greatly improve performances and memory usage
qs = issues_for(user).only('id', 'title', 'created', 'subject')
# Do not dereference subject (so it... | [
"def",
"issues_notifications",
"(",
"user",
")",
":",
"notifications",
"=",
"[",
"]",
"# Only fetch required fields for notification serialization",
"# Greatly improve performances and memory usage",
"qs",
"=",
"issues_for",
"(",
"user",
")",
".",
"only",
"(",
"'id'",
","... | Notify user about open issues | [
"Notify",
"user",
"about",
"open",
"issues"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/issues/notifications.py#L15-L35 |
14,288 | opendatateam/udata | udata/features/identicon/backends.py | get_config | def get_config(key):
'''
Get an identicon configuration parameter.
Precedance order is:
- application config (`udata.cfg`)
- theme config
- default
'''
key = 'AVATAR_{0}'.format(key.upper())
local_config = current_app.config.get(key)
return local_config or getattr(th... | python | def get_config(key):
'''
Get an identicon configuration parameter.
Precedance order is:
- application config (`udata.cfg`)
- theme config
- default
'''
key = 'AVATAR_{0}'.format(key.upper())
local_config = current_app.config.get(key)
return local_config or getattr(th... | [
"def",
"get_config",
"(",
"key",
")",
":",
"key",
"=",
"'AVATAR_{0}'",
".",
"format",
"(",
"key",
".",
"upper",
"(",
")",
")",
"local_config",
"=",
"current_app",
".",
"config",
".",
"get",
"(",
"key",
")",
"return",
"local_config",
"or",
"getattr",
"(... | Get an identicon configuration parameter.
Precedance order is:
- application config (`udata.cfg`)
- theme config
- default | [
"Get",
"an",
"identicon",
"configuration",
"parameter",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/features/identicon/backends.py#L41-L52 |
14,289 | opendatateam/udata | udata/features/identicon/backends.py | get_provider | def get_provider():
'''Get the current provider from config'''
name = get_config('provider')
available = entrypoints.get_all('udata.avatars')
if name not in available:
raise ValueError('Unknown avatar provider: {0}'.format(name))
return available[name] | python | def get_provider():
'''Get the current provider from config'''
name = get_config('provider')
available = entrypoints.get_all('udata.avatars')
if name not in available:
raise ValueError('Unknown avatar provider: {0}'.format(name))
return available[name] | [
"def",
"get_provider",
"(",
")",
":",
"name",
"=",
"get_config",
"(",
"'provider'",
")",
"available",
"=",
"entrypoints",
".",
"get_all",
"(",
"'udata.avatars'",
")",
"if",
"name",
"not",
"in",
"available",
":",
"raise",
"ValueError",
"(",
"'Unknown avatar pro... | Get the current provider from config | [
"Get",
"the",
"current",
"provider",
"from",
"config"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/features/identicon/backends.py#L59-L65 |
14,290 | opendatateam/udata | udata/features/identicon/backends.py | generate_pydenticon | def generate_pydenticon(identifier, size):
'''
Use pydenticon to generate an identicon image.
All parameters are extracted from configuration.
'''
blocks_size = get_internal_config('size')
foreground = get_internal_config('foreground')
background = get_internal_config('background')
gener... | python | def generate_pydenticon(identifier, size):
'''
Use pydenticon to generate an identicon image.
All parameters are extracted from configuration.
'''
blocks_size = get_internal_config('size')
foreground = get_internal_config('foreground')
background = get_internal_config('background')
gener... | [
"def",
"generate_pydenticon",
"(",
"identifier",
",",
"size",
")",
":",
"blocks_size",
"=",
"get_internal_config",
"(",
"'size'",
")",
"foreground",
"=",
"get_internal_config",
"(",
"'foreground'",
")",
"background",
"=",
"get_internal_config",
"(",
"'background'",
... | Use pydenticon to generate an identicon image.
All parameters are extracted from configuration. | [
"Use",
"pydenticon",
"to",
"generate",
"an",
"identicon",
"image",
".",
"All",
"parameters",
"are",
"extracted",
"from",
"configuration",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/features/identicon/backends.py#L80-L100 |
14,291 | opendatateam/udata | udata/features/identicon/backends.py | adorable | def adorable(identifier, size):
'''
Adorable Avatars provider
Simply redirect to the external API.
See: http://avatars.adorable.io/
'''
url = ADORABLE_AVATARS_URL.format(identifier=identifier, size=size)
return redirect(url) | python | def adorable(identifier, size):
'''
Adorable Avatars provider
Simply redirect to the external API.
See: http://avatars.adorable.io/
'''
url = ADORABLE_AVATARS_URL.format(identifier=identifier, size=size)
return redirect(url) | [
"def",
"adorable",
"(",
"identifier",
",",
"size",
")",
":",
"url",
"=",
"ADORABLE_AVATARS_URL",
".",
"format",
"(",
"identifier",
"=",
"identifier",
",",
"size",
"=",
"size",
")",
"return",
"redirect",
"(",
"url",
")"
] | Adorable Avatars provider
Simply redirect to the external API.
See: http://avatars.adorable.io/ | [
"Adorable",
"Avatars",
"provider"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/features/identicon/backends.py#L116-L125 |
14,292 | opendatateam/udata | udata/core/dataset/commands.py | licenses | def licenses(source=DEFAULT_LICENSE_FILE):
'''Feed the licenses from a JSON file'''
if source.startswith('http'):
json_licenses = requests.get(source).json()
else:
with open(source) as fp:
json_licenses = json.load(fp)
if len(json_licenses):
log.info('Dropping existi... | python | def licenses(source=DEFAULT_LICENSE_FILE):
'''Feed the licenses from a JSON file'''
if source.startswith('http'):
json_licenses = requests.get(source).json()
else:
with open(source) as fp:
json_licenses = json.load(fp)
if len(json_licenses):
log.info('Dropping existi... | [
"def",
"licenses",
"(",
"source",
"=",
"DEFAULT_LICENSE_FILE",
")",
":",
"if",
"source",
".",
"startswith",
"(",
"'http'",
")",
":",
"json_licenses",
"=",
"requests",
".",
"get",
"(",
"source",
")",
".",
"json",
"(",
")",
"else",
":",
"with",
"open",
"... | Feed the licenses from a JSON file | [
"Feed",
"the",
"licenses",
"from",
"a",
"JSON",
"file"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/dataset/commands.py#L30-L64 |
14,293 | opendatateam/udata | udata/core/spatial/forms.py | ZonesField.fetch_objects | def fetch_objects(self, geoids):
'''
Custom object retrieval.
Zones are resolved from their identifier
instead of the default bulk fetch by ID.
'''
zones = []
no_match = []
for geoid in geoids:
zone = GeoZone.objects.resolve(geoid)
... | python | def fetch_objects(self, geoids):
'''
Custom object retrieval.
Zones are resolved from their identifier
instead of the default bulk fetch by ID.
'''
zones = []
no_match = []
for geoid in geoids:
zone = GeoZone.objects.resolve(geoid)
... | [
"def",
"fetch_objects",
"(",
"self",
",",
"geoids",
")",
":",
"zones",
"=",
"[",
"]",
"no_match",
"=",
"[",
"]",
"for",
"geoid",
"in",
"geoids",
":",
"zone",
"=",
"GeoZone",
".",
"objects",
".",
"resolve",
"(",
"geoid",
")",
"if",
"zone",
":",
"zon... | Custom object retrieval.
Zones are resolved from their identifier
instead of the default bulk fetch by ID. | [
"Custom",
"object",
"retrieval",
"."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/spatial/forms.py#L34-L55 |
14,294 | opendatateam/udata | tasks_helpers.py | lrun | def lrun(command, *args, **kwargs):
'''Run a local command from project root'''
return run('cd {0} && {1}'.format(ROOT, command), *args, **kwargs) | python | def lrun(command, *args, **kwargs):
'''Run a local command from project root'''
return run('cd {0} && {1}'.format(ROOT, command), *args, **kwargs) | [
"def",
"lrun",
"(",
"command",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"run",
"(",
"'cd {0} && {1}'",
".",
"format",
"(",
"ROOT",
",",
"command",
")",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Run a local command from project root | [
"Run",
"a",
"local",
"command",
"from",
"project",
"root"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/tasks_helpers.py#L37-L39 |
14,295 | opendatateam/udata | udata/harvest/backends/dcat.py | DcatBackend.initialize | def initialize(self):
'''List all datasets for a given ...'''
fmt = guess_format(self.source.url)
# if format can't be guessed from the url
# we fallback on the declared Content-Type
if not fmt:
response = requests.head(self.source.url)
mime_type = respons... | python | def initialize(self):
'''List all datasets for a given ...'''
fmt = guess_format(self.source.url)
# if format can't be guessed from the url
# we fallback on the declared Content-Type
if not fmt:
response = requests.head(self.source.url)
mime_type = respons... | [
"def",
"initialize",
"(",
"self",
")",
":",
"fmt",
"=",
"guess_format",
"(",
"self",
".",
"source",
".",
"url",
")",
"# if format can't be guessed from the url",
"# we fallback on the declared Content-Type",
"if",
"not",
"fmt",
":",
"response",
"=",
"requests",
".",... | List all datasets for a given ... | [
"List",
"all",
"datasets",
"for",
"a",
"given",
"..."
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/backends/dcat.py#L51-L67 |
14,296 | opendatateam/udata | udata/commands/worker.py | get_tasks | def get_tasks():
'''Get a list of known tasks with their routing queue'''
return {
name: get_task_queue(name, cls)
for name, cls in celery.tasks.items()
# Exclude celery internal tasks
if not name.startswith('celery.')
# Exclude udata test tasks
and not name.start... | python | def get_tasks():
'''Get a list of known tasks with their routing queue'''
return {
name: get_task_queue(name, cls)
for name, cls in celery.tasks.items()
# Exclude celery internal tasks
if not name.startswith('celery.')
# Exclude udata test tasks
and not name.start... | [
"def",
"get_tasks",
"(",
")",
":",
"return",
"{",
"name",
":",
"get_task_queue",
"(",
"name",
",",
"cls",
")",
"for",
"name",
",",
"cls",
"in",
"celery",
".",
"tasks",
".",
"items",
"(",
")",
"# Exclude celery internal tasks",
"if",
"not",
"name",
".",
... | Get a list of known tasks with their routing queue | [
"Get",
"a",
"list",
"of",
"known",
"tasks",
"with",
"their",
"routing",
"queue"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/commands/worker.py#L97-L106 |
14,297 | opendatateam/udata | udata/commands/worker.py | tasks | def tasks():
'''Display registered tasks with their queue'''
tasks = get_tasks()
longest = max(tasks.keys(), key=len)
size = len(longest)
for name, queue in sorted(tasks.items()):
print('* {0}: {1}'.format(name.ljust(size), queue)) | python | def tasks():
'''Display registered tasks with their queue'''
tasks = get_tasks()
longest = max(tasks.keys(), key=len)
size = len(longest)
for name, queue in sorted(tasks.items()):
print('* {0}: {1}'.format(name.ljust(size), queue)) | [
"def",
"tasks",
"(",
")",
":",
"tasks",
"=",
"get_tasks",
"(",
")",
"longest",
"=",
"max",
"(",
"tasks",
".",
"keys",
"(",
")",
",",
"key",
"=",
"len",
")",
"size",
"=",
"len",
"(",
"longest",
")",
"for",
"name",
",",
"queue",
"in",
"sorted",
"... | Display registered tasks with their queue | [
"Display",
"registered",
"tasks",
"with",
"their",
"queue"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/commands/worker.py#L110-L116 |
14,298 | opendatateam/udata | udata/commands/worker.py | status | def status(queue, munin, munin_config):
"""List queued tasks aggregated by name"""
if munin_config:
return status_print_config(queue)
queues = get_queues(queue)
for queue in queues:
status_print_queue(queue, munin=munin)
if not munin:
print('-' * 40) | python | def status(queue, munin, munin_config):
"""List queued tasks aggregated by name"""
if munin_config:
return status_print_config(queue)
queues = get_queues(queue)
for queue in queues:
status_print_queue(queue, munin=munin)
if not munin:
print('-' * 40) | [
"def",
"status",
"(",
"queue",
",",
"munin",
",",
"munin_config",
")",
":",
"if",
"munin_config",
":",
"return",
"status_print_config",
"(",
"queue",
")",
"queues",
"=",
"get_queues",
"(",
"queue",
")",
"for",
"queue",
"in",
"queues",
":",
"status_print_queu... | List queued tasks aggregated by name | [
"List",
"queued",
"tasks",
"aggregated",
"by",
"name"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/commands/worker.py#L125-L133 |
14,299 | opendatateam/udata | udata/forms/fields.py | FieldHelper.pre_validate | def pre_validate(self, form):
'''Calls preprocessors before pre_validation'''
for preprocessor in self._preprocessors:
preprocessor(form, self)
super(FieldHelper, self).pre_validate(form) | python | def pre_validate(self, form):
'''Calls preprocessors before pre_validation'''
for preprocessor in self._preprocessors:
preprocessor(form, self)
super(FieldHelper, self).pre_validate(form) | [
"def",
"pre_validate",
"(",
"self",
",",
"form",
")",
":",
"for",
"preprocessor",
"in",
"self",
".",
"_preprocessors",
":",
"preprocessor",
"(",
"form",
",",
"self",
")",
"super",
"(",
"FieldHelper",
",",
"self",
")",
".",
"pre_validate",
"(",
"form",
")... | Calls preprocessors before pre_validation | [
"Calls",
"preprocessors",
"before",
"pre_validation"
] | f016585af94b0ff6bd73738c700324adc8ba7f8f | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/forms/fields.py#L55-L59 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.