uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
26349c2a49e7d9e59279431d | train | function | def unapplyLinearProperty(term):
for idx, arg in enumerate(term.args):
if hasSubclass(arg, Multiplication):
for mArg in arg.args:
if hasSubclass(mArg, Function) and mArg.linear:
function = mArg.__class__
variables = [mmArg for mmArg in arg.args if not hasSubclass(mmArg, Constant) and mmArg != mArg]... | def unapplyLinearProperty(term):
| for idx, arg in enumerate(term.args):
if hasSubclass(arg, Multiplication):
for mArg in arg.args:
if hasSubclass(mArg, Function) and mArg.linear:
function = mArg.__class__
variables = [mmArg for mmArg in arg.args if not hasSubclass(mmArg, Constant) and mmArg != mArg]
constants = [mmArg for mmAr... |
term.args[idx] = operator( *[function(arg) for arg in args] )
if hasSubclass(arg, Operator):
applyLinearProperty(arg, flag+1)
if flag > 0:
applyLinearProperty(term, flag-1)
def unapplyLinearProperty(term):
| 64 | 64 | 180 | 7 | 57 | GustavoExel/bellbird | bellbird/equation.py | Python | unapplyLinearProperty | unapplyLinearProperty | 241 | 258 | 241 | 241 | 832f00a30859aa5930b885934347828e1396cbf3 | bigcode/the-stack | train |
cf498ae62e013174ef407411 | train | function | def updateVariables(term, variableNames):
for idx, arg in enumerate(term.args):
if hasSubclass(arg, Variable):
if arg.name in variableNames:
term.args[idx] = ScalarField(arg.name)
elif arg.name in [varName.replace("_x","") for varName in variableNames if "_x" in varName]:
term.args[idx] = VectorField(a... | def updateVariables(term, variableNames):
| for idx, arg in enumerate(term.args):
if hasSubclass(arg, Variable):
if arg.name in variableNames:
term.args[idx] = ScalarField(arg.name)
elif arg.name in [varName.replace("_x","") for varName in variableNames if "_x" in varName]:
term.args[idx] = VectorField(arg.name)
# elif arg.__class__ == Variab... | propertyVars):
for idx, arg in enumerate(term.args):
if hasSubclass(arg, Variable):
if arg.name in propertyVars:
term.args[idx] = Constant(arg.name)
if hasSubclass(arg, Operator):
updatePropertyVars(arg, propertyVars)
def updateVariables(term, variableNames):
| 64 | 64 | 131 | 8 | 56 | GustavoExel/bellbird | bellbird/equation.py | Python | updateVariables | updateVariables | 189 | 200 | 189 | 189 | 636650e13eeb47b2e66c83dee23faea93e87bf1d | bigcode/the-stack | train |
5ec10599ea6cf1b1109ab058 | train | function | def hasSubclass(obj, subclass):
return subclass in obj.__class__.__mro__
| def hasSubclass(obj, subclass):
| return subclass in obj.__class__.__mro__
| _order = None
@property
def order(self):
if not self._order:
self._order = self.getOrder()
return self._order
def getOrder(self):
return getOrder(self.term)
def isTransient(self):
return isTransient(self.term)
def hasSubclass(obj, subclass):
| 64 | 64 | 17 | 7 | 57 | GustavoExel/bellbird | bellbird/equation.py | Python | hasSubclass | hasSubclass | 105 | 106 | 105 | 105 | 009fb7b8077994c15276a943967eb7c92e4eeb9e | bigcode/the-stack | train |
bcf41506e0684d4289dd8a05 | train | class | class ClientAddressForm(ModelForm):
address_type = ModelChoiceField(queryset=AddressType.objects.order_by('id'))
# used_on = ModelChoiceField(queryset=AddressUsage.objects.order_by('id'))
client = ModelChoiceField(queryset=Client.objects.order_by('client_name'))
class Meta:
model = Address
... | class ClientAddressForm(ModelForm):
| address_type = ModelChoiceField(queryset=AddressType.objects.order_by('id'))
# used_on = ModelChoiceField(queryset=AddressUsage.objects.order_by('id'))
client = ModelChoiceField(queryset=Client.objects.order_by('client_name'))
class Meta:
model = Address
fields = [
'client',... | client_name',
'engagement',
'parent',
'service_start',
'service_end',
'client_status',
'imp_fee_status',
'production_support_number',
'upload_address',
'iq_support_address',
'approved',
]
clas... | 63 | 64 | 124 | 7 | 56 | wedwardbeck/ibase | itembase/core/forms/client_forms.py | Python | ClientAddressForm | ClientAddressForm | 28 | 39 | 28 | 28 | 7c38637af6d75ac231576ab7c97195c8dcb2f906 | bigcode/the-stack | train |
4059238581e2f146d3c1fe6a | train | class | class ClientForm(ModelForm):
# service_start = forms.DateField(widget=forms.SelectDateWidget)
engagement = ModelChoiceField(queryset=EngagementType.objects, empty_label="Select Engagement")
parent = ModelChoiceField(queryset=Client.objects.filter(client_status__lt=5), required=False)
class Meta:
... | class ClientForm(ModelForm):
# service_start = forms.DateField(widget=forms.SelectDateWidget)
| engagement = ModelChoiceField(queryset=EngagementType.objects, empty_label="Select Engagement")
parent = ModelChoiceField(queryset=Client.objects.filter(client_status__lt=5), required=False)
class Meta:
model = Client
fields = [
'client_code',
'client_name',
... | from django.forms import ModelForm, ModelChoiceField
from itembase.core.models import Address, AddressType, AddressUsage, Client, EngagementType # , Modules
class ClientForm(ModelForm):
# service_start = forms.DateField(widget=forms.SelectDateWidget)
| 55 | 64 | 138 | 20 | 34 | wedwardbeck/ibase | itembase/core/forms/client_forms.py | Python | ClientForm | ClientForm | 5 | 25 | 5 | 6 | c4051cb12b1f540356ec316f9c88746f037a47fa | bigcode/the-stack | train |
4f9ac1ab006a423a0c712020 | train | function | @requires_scipy_or_netCDF4
@pytest.mark.parametrize("calendar", _STANDARD_CALENDARS)
@pytest.mark.parametrize("units_year", [1500, 2500])
def test_use_cftime_false_standard_calendar_out_of_range(calendar, units_year):
x = [0, 1]
time = [0, 720]
units = f"days since {units_year}-01-01"
original = DataArr... | @requires_scipy_or_netCDF4
@pytest.mark.parametrize("calendar", _STANDARD_CALENDARS)
@pytest.mark.parametrize("units_year", [1500, 2500])
def test_use_cftime_false_standard_calendar_out_of_range(calendar, units_year):
| x = [0, 1]
time = [0, 720]
units = f"days since {units_year}-01-01"
original = DataArray(x, [("time", time)], name="x")
original = original.to_dataset()
for v in ["x", "time"]:
original[v].attrs["units"] = units
original[v].attrs["calendar"] = calendar
with create_tmp_file()... | (expected_time, ds.time)
assert not record
@requires_scipy_or_netCDF4
@pytest.mark.parametrize("calendar", _STANDARD_CALENDARS)
@pytest.mark.parametrize("units_year", [1500, 2500])
def test_use_cftime_false_standard_calendar_out_of_range(calendar, units_year):
| 64 | 64 | 185 | 53 | 10 | qwhelan/xarray | xarray/tests/test_backends.py | Python | test_use_cftime_false_standard_calendar_out_of_range | test_use_cftime_false_standard_calendar_out_of_range | 4,356 | 4,372 | 4,356 | 4,359 | e6aa7ea04bdb5d7da3f24403fe89f3b049f7683b | bigcode/the-stack | train |
33c6ec606801b3cab4368cc8 | train | class | class MiscObject:
pass
| class MiscObject:
| pass
| h5netcdf (yet)
var = xr.Variable(("x",), [1, 2, 3], {}, {"least_sigificant_digit": 2})
with raises_regex(ValueError, "unexpected encoding"):
_extract_nc4_variable_encoding(var, raise_on_invalid=True)
class MiscObject:
| 64 | 64 | 7 | 4 | 60 | qwhelan/xarray | xarray/tests/test_backends.py | Python | MiscObject | MiscObject | 4,061 | 4,062 | 4,061 | 4,061 | 9f375d6a9394d6360758926e2c5b0177a947925a | bigcode/the-stack | train |
d4c678a1c222ec0f69827ff2 | train | function | def create_bad_unsigned_masked_scaled_data():
encoding = {
"_FillValue": 255,
"_Unsigned": True,
"dtype": "i1",
"add_offset": 10,
"scale_factor": np.float32(0.1),
}
x = np.array([10.0, 10.1, 22.7, 22.8, np.nan], dtype=np.float32)
return Dataset({"x": ("t", x, {}, ... | def create_bad_unsigned_masked_scaled_data():
| encoding = {
"_FillValue": 255,
"_Unsigned": True,
"dtype": "i1",
"add_offset": 10,
"scale_factor": np.float32(0.1),
}
x = np.array([10.0, 10.1, 22.7, 22.8, np.nan], dtype=np.float32)
return Dataset({"x": ("t", x, {}, encoding)})
| 0, 1, 127, 128, 255] unsigned
sb = np.asarray([0, 1, 127, -128, -1], dtype="i1")
return Dataset({"x": ("t", sb, attributes)})
def create_bad_unsigned_masked_scaled_data():
| 63 | 64 | 105 | 9 | 55 | qwhelan/xarray | xarray/tests/test_backends.py | Python | create_bad_unsigned_masked_scaled_data | create_bad_unsigned_masked_scaled_data | 141 | 150 | 141 | 141 | 179ed9c54c4615c4d287f75cda46d14928ddd949 | bigcode/the-stack | train |
28a163b543f65a25b1211cda | train | class | class TestEncodingInvalid:
def test_extract_nc4_variable_encoding(self):
var = xr.Variable(("x",), [1, 2, 3], {}, {"foo": "bar"})
with raises_regex(ValueError, "unexpected encoding"):
_extract_nc4_variable_encoding(var, raise_on_invalid=True)
var = xr.Variable(("x",), [1, 2, 3],... | class TestEncodingInvalid:
| def test_extract_nc4_variable_encoding(self):
var = xr.Variable(("x",), [1, 2, 3], {}, {"foo": "bar"})
with raises_regex(ValueError, "unexpected encoding"):
_extract_nc4_variable_encoding(var, raise_on_invalid=True)
var = xr.Variable(("x",), [1, 2, 3], {}, {"chunking": (2, 1)})
... | , lat)]))
with xr.open_rasterio(vrt) as da:
actual_shape = da.sizes["x"], da.sizes["y"]
actual_res = da.res
actual_val = da.sel(dict(x=lon, y=lat), method="nearest").data
assert actual_shape == expected_... | 90 | 90 | 303 | 5 | 84 | qwhelan/xarray | xarray/tests/test_backends.py | Python | TestEncodingInvalid | TestEncodingInvalid | 4,034 | 4,058 | 4,034 | 4,034 | 6cd22b4becf2789275b5236f94ea60f6a8d2802b | bigcode/the-stack | train |
4f25ad60d471baae39e41777 | train | class | @requires_scipy
class TestScipyInMemoryData(ScipyWriteBase):
engine = "scipy"
@contextlib.contextmanager
def create_store(self):
fobj = BytesIO()
yield backends.ScipyDataStore(fobj, "w")
def test_to_netcdf_explicit_engine(self):
# regression test for GH1321
Dataset({"fo... | @requires_scipy
class TestScipyInMemoryData(ScipyWriteBase):
| engine = "scipy"
@contextlib.contextmanager
def create_store(self):
fobj = BytesIO()
yield backends.ScipyDataStore(fobj, "w")
def test_to_netcdf_explicit_engine(self):
# regression test for GH1321
Dataset({"foo": 42}).to_netcdf(engine="scipy")
def test_bytes_pickle... | import scipy
if scipy.__version__ == "1.0.1":
pytest.xfail("https://github.com/scipy/scipy/issues/8625")
super().test_append_overwrite_values()
@requires_scipy
class TestScipyInMemoryData(ScipyWriteBase):
| 64 | 64 | 168 | 19 | 45 | qwhelan/xarray | xarray/tests/test_backends.py | Python | TestScipyInMemoryData | TestScipyInMemoryData | 1,944 | 1,962 | 1,944 | 1,945 | dae0dc1eb0162775fe8704eac3530ada01014250 | bigcode/the-stack | train |
e0b9ef205def26e5a1cad2b3 | train | class | @requires_scipy
class TestScipyFilePath(ScipyWriteBase):
engine = "scipy"
@contextlib.contextmanager
def create_store(self):
with create_tmp_file() as tmp_file:
with backends.ScipyDataStore(tmp_file, mode="w") as store:
yield store
def test_array_attrs(self):
... | @requires_scipy
class TestScipyFilePath(ScipyWriteBase):
| engine = "scipy"
@contextlib.contextmanager
def create_store(self):
with create_tmp_file() as tmp_file:
with backends.ScipyDataStore(tmp_file, mode="w") as store:
yield store
def test_array_attrs(self):
ds = Dataset(attrs={"foo": [[1, 2], [3, 4]]})
w... | save_kwargs)
with open(tmp_file, "rb") as f:
with self.open(f, **open_kwargs) as ds:
yield ds
@pytest.mark.skip(reason="cannot pickle file objects")
def test_pickle(self):
pass
@pytest.mark.skip(reason="cannot pickle file objects")
def test_pickl... | 94 | 94 | 314 | 18 | 75 | qwhelan/xarray | xarray/tests/test_backends.py | Python | TestScipyFilePath | TestScipyFilePath | 1,998 | 2,032 | 1,998 | 1,999 | 5d294b55a1bf4ab13ac1f84daa00511992bc9eac | bigcode/the-stack | train |
52d5240c9f4f9a64a2aa36f7 | train | function | @requires_scipy_or_netCDF4
def test_no_warning_from_dask_effective_get():
with create_tmp_file() as tmpfile:
with pytest.warns(None) as record:
ds = Dataset()
ds.to_netcdf(tmpfile)
assert len(record) == 0
| @requires_scipy_or_netCDF4
def test_no_warning_from_dask_effective_get():
| with create_tmp_file() as tmpfile:
with pytest.warns(None) as record:
ds = Dataset()
ds.to_netcdf(tmpfile)
assert len(record) == 0
| create_tmp_file() as tmp:
tmp = Path(tmp)
original_da.to_netcdf(tmp)
with open_dataarray(tmp) as loaded_da:
assert_identical(original_da, loaded_da)
@requires_scipy_or_netCDF4
def test_no_warning_from_dask_effective_get():
| 64 | 64 | 64 | 21 | 43 | qwhelan/xarray | xarray/tests/test_backends.py | Python | test_no_warning_from_dask_effective_get | test_no_warning_from_dask_effective_get | 4,215 | 4,221 | 4,215 | 4,216 | ff102c64f9d0bffb89df896bc0e76ab964d39faa | bigcode/the-stack | train |
ca2febbd517c5db2eed60532 | train | function | @contextlib.contextmanager
def create_tmp_files(nfiles, suffix=".nc", allow_cleanup_failure=False):
with ExitStack() as stack:
files = [
stack.enter_context(create_tmp_file(suffix, allow_cleanup_failure))
for apath in np.arange(nfiles)
]
yield files
| @contextlib.contextmanager
def create_tmp_files(nfiles, suffix=".nc", allow_cleanup_failure=False):
| with ExitStack() as stack:
files = [
stack.enter_context(create_tmp_file(suffix, allow_cleanup_failure))
for apath in np.arange(nfiles)
]
yield files
| format(next(_counter), suffix))
try:
yield path
finally:
try:
shutil.rmtree(temp_dir)
except OSError:
if not allow_cleanup_failure:
raise
@contextlib.contextmanager
def create_tmp_files(nfiles, suffix=".nc", allow_cleanup_failure=False):
| 64 | 64 | 64 | 22 | 41 | qwhelan/xarray | xarray/tests/test_backends.py | Python | create_tmp_files | create_tmp_files | 1,000 | 1,007 | 1,000 | 1,001 | 3a4569978c485f8effaf410dddb87011896d38fd | bigcode/the-stack | train |
d4aad0c6e0f80e5de2c65fbf | train | class | @requires_rasterio
class TestRasterio:
@requires_scipy_or_netCDF4
def test_serialization(self):
with create_tmp_geotiff(additional_attrs={}) as (tmp_file, expected):
# Write it to a netcdf and read again (roundtrip)
with xr.open_rasterio(tmp_file) as rioda:
with c... | @requires_rasterio
class TestRasterio:
@requires_scipy_or_netCDF4
| def test_serialization(self):
with create_tmp_geotiff(additional_attrs={}) as (tmp_file, expected):
# Write it to a netcdf and read again (roundtrip)
with xr.open_rasterio(tmp_file) as rioda:
with create_tmp_file(suffix=".nc") as tmp_nc_file:
rioda... | 1) for n in range(nz)),
}
with rasterio.open(
tmp_file,
"w",
driver="GTiff",
height=ny,
width=nx,
count=nz,
crs=crs,
transform=transform,
dtype=rasterio.float32,
**open_kwargs,
... | 256 | 256 | 5,225 | 22 | 233 | qwhelan/xarray | xarray/tests/test_backends.py | Python | TestRasterio | TestRasterio | 3,552 | 4,031 | 3,552 | 3,554 | b1fc04eee3fc419e2f089f2be20b0bd59416fd7e | bigcode/the-stack | train |
1bf5e083ebbf061ed2073d53 | train | function | @pytest.fixture(params=[True, False])
def parallel(request):
return request.param
| @pytest.fixture(params=[True, False])
def parallel(request):
| return request.param
| (params=[5, None])
def file_cache_maxsize(request):
maxsize = request.param
if maxsize is not None:
with set_options(file_cache_maxsize=maxsize):
yield maxsize
else:
yield maxsize
@pytest.fixture(params=[True, False])
def parallel(request):
| 64 | 64 | 17 | 12 | 51 | qwhelan/xarray | xarray/tests/test_backends.py | Python | parallel | parallel | 2,422 | 2,424 | 2,422 | 2,423 | 24d071034f793558efa23ed3eab940445507155f | bigcode/the-stack | train |
8b866b54f74b196680811845 | train | class | @requires_pseudonetcdf
@pytest.mark.filterwarnings("ignore:IOAPI_ISPH is assumed to be 6370000")
class TestPseudoNetCDFFormat:
def open(self, path, **kwargs):
return open_dataset(path, engine="pseudonetcdf", **kwargs)
@contextlib.contextmanager
def roundtrip(
self, data, save_kwargs=None, o... | @requires_pseudonetcdf
@pytest.mark.filterwarnings("ignore:IOAPI_ISPH is assumed to be 6370000")
class TestPseudoNetCDFFormat:
| def open(self, path, **kwargs):
return open_dataset(path, engine="pseudonetcdf", **kwargs)
@contextlib.contextmanager
def roundtrip(
self, data, save_kwargs=None, open_kwargs=None, allow_cleanup_failure=False
):
if save_kwargs is None:
save_kwargs = {}
if ope... | time": 3,
"isobaricInhPa": 2,
"latitude": 3,
"longitude": 4,
}
with open_example_dataset("example.grib", engine="cfgrib") as ds:
assert ds.dims == expected
assert list(ds.data_vars) == ["z", "t"]
assert ds["z"].min() == 12660.0
... | 256 | 256 | 1,935 | 35 | 220 | qwhelan/xarray | xarray/tests/test_backends.py | Python | TestPseudoNetCDFFormat | TestPseudoNetCDFFormat | 3,271 | 3,483 | 3,271 | 3,273 | d6264f09d481d65814ea56969d1922a482e81c32 | bigcode/the-stack | train |
7ae8be0f88f08b978c52b886 | train | class | class NetCDF3Only:
pass
| class NetCDF3Only:
| pass
| 0])
with pytest.raises(UnreliableArrayFailure):
array[0]
assert array[0] == 0
actual = robust_getitem(array, 0, catch=UnreliableArrayFailure, initial_delay=0)
assert actual == 0
class NetCDF3Only:
| 64 | 64 | 9 | 6 | 57 | qwhelan/xarray | xarray/tests/test_backends.py | Python | NetCDF3Only | NetCDF3Only | 223 | 224 | 223 | 223 | 83533de62416502063cb761e13149a938d129360 | bigcode/the-stack | train |
bf2f95cdd076e1bf3023c684 | train | function | @requires_scipy_or_netCDF4
@pytest.mark.parametrize("calendar", _STANDARD_CALENDARS)
def test_use_cftime_false_standard_calendar_in_range(calendar):
x = [0, 1]
time = [0, 720]
units_date = "2000-01-01"
units = "days since 2000-01-01"
original = DataArray(x, [("time", time)], name="x")
original =... | @requires_scipy_or_netCDF4
@pytest.mark.parametrize("calendar", _STANDARD_CALENDARS)
def test_use_cftime_false_standard_calendar_in_range(calendar):
| x = [0, 1]
time = [0, 720]
units_date = "2000-01-01"
units = "days since 2000-01-01"
original = DataArray(x, [("time", time)], name="x")
original = original.to_dataset()
for v in ["x", "time"]:
original[v].attrs["units"] = units
original[v].attrs["calendar"] = calendar
x... | _file:
original.to_netcdf(tmp_file)
with pytest.warns(None) as record:
with open_dataset(tmp_file, use_cftime=True) as ds:
assert_identical(expected_x, ds.x)
assert_identical(expected_time, ds.time)
assert not record
@requires_scipy_or_netCDF4
@pyt... | 95 | 95 | 319 | 34 | 60 | qwhelan/xarray | xarray/tests/test_backends.py | Python | test_use_cftime_false_standard_calendar_in_range | test_use_cftime_false_standard_calendar_in_range | 4,327 | 4,353 | 4,327 | 4,329 | 51e0b46741e85f4834d3d533b5fe7cadbb2016d5 | bigcode/the-stack | train |
8aaebb15abbc8982490bba07 | train | class | @requires_h5netcdf
class TestH5NetCDFFileObject(TestH5NetCDFData):
engine = "h5netcdf"
def test_open_badbytes(self):
with raises_regex(ValueError, "HDF5 as bytes"):
with open_dataset(b"\211HDF\r\n\032\n", engine="h5netcdf"):
pass
with raises_regex(ValueError, "not a ... | @requires_h5netcdf
class TestH5NetCDFFileObject(TestH5NetCDFData):
| engine = "h5netcdf"
def test_open_badbytes(self):
with raises_regex(ValueError, "HDF5 as bytes"):
with open_dataset(b"\211HDF\r\n\032\n", engine="h5netcdf"):
pass
with raises_regex(ValueError, "not a valid netCDF"):
with open_dataset(b"garbage"):
... | 9}}}
with self.roundtrip(ds, save_kwargs=kwargs) as actual:
assert actual.x.encoding["zlib"]
assert actual.x.encoding["complevel"] == 9
kwargs = {"encoding": {"x": {"compression": "lzf", "compression_opts": None}}}
with self.roundtrip(ds, save_kwargs=kwargs) as actual:
... | 126 | 126 | 423 | 22 | 103 | qwhelan/xarray | xarray/tests/test_backends.py | Python | TestH5NetCDFFileObject | TestH5NetCDFFileObject | 2,316 | 2,359 | 2,316 | 2,317 | ec3d76db0e6817f36c0b4600a12161cd7e6c0751 | bigcode/the-stack | train |
5d99c1fa9c22adb9fa2f2d0a | train | class | @requires_netCDF4
class TestNetCDF3ViaNetCDF4Data(CFEncodedBase, NetCDF3Only):
engine = "netcdf4"
file_format = "NETCDF3_CLASSIC"
@contextlib.contextmanager
def create_store(self):
with create_tmp_file() as tmp_file:
with backends.NetCDF4DataStore.open(
tmp_file, mod... | @requires_netCDF4
class TestNetCDF3ViaNetCDF4Data(CFEncodedBase, NetCDF3Only):
| engine = "netcdf4"
file_format = "NETCDF3_CLASSIC"
@contextlib.contextmanager
def create_store(self):
with create_tmp_file() as tmp_file:
with backends.NetCDF4DataStore.open(
tmp_file, mode="w", format="NETCDF3_CLASSIC"
) as store:
yield s... | ") as rootgrp:
rootgrp.createGroup("foo")
with raises_regex(TypeError, "pip install netcdf4"):
open_dataset(tmp_file, engine="scipy")
@requires_netCDF4
class TestNetCDF3ViaNetCDF4Data(CFEncodedBase, NetCDF3Only):
| 64 | 64 | 176 | 26 | 38 | qwhelan/xarray | xarray/tests/test_backends.py | Python | TestNetCDF3ViaNetCDF4Data | TestNetCDF3ViaNetCDF4Data | 2,035 | 2,053 | 2,035 | 2,036 | 7a6654fd684dc674104629c8cdbf75367d987536 | bigcode/the-stack | train |
0ddd8d3b73a455a8891ea332 | train | class | @requires_zarr
class ZarrBase(CFEncodedBase):
DIMENSION_KEY = "_ARRAY_DIMENSIONS"
@contextlib.contextmanager
def create_store(self):
with self.create_zarr_target() as store_target:
yield backends.ZarrStore.open_group(store_target, mode="w")
def save(self, dataset, store_target, **... | @requires_zarr
class ZarrBase(CFEncodedBase):
| DIMENSION_KEY = "_ARRAY_DIMENSIONS"
@contextlib.contextmanager
def create_store(self):
with self.create_zarr_target() as store_target:
yield backends.ZarrStore.open_group(store_target, mode="w")
def save(self, dataset, store_target, **kwargs):
return dataset.to_zarr(store=s... | ask
pass
def test_write_inconsistent_chunks(self):
# Construct two variables with the same dimensions, but different
# chunk sizes.
x = da.zeros((100, 100), dtype="f4", chunks=(50, 100))
x = DataArray(data=x, dims=("lat", "lon"), name="x")
x.encoding["chunksizes"] = ... | 256 | 256 | 4,081 | 14 | 242 | qwhelan/xarray | xarray/tests/test_backends.py | Python | ZarrBase | ZarrBase | 1,456 | 1,910 | 1,456 | 1,458 | 172428fe4d1907c58402938ce83a387d99408b0d | bigcode/the-stack | train |
5d6834eab281a434afe750e6 | train | function | @pytest.mark.parametrize("engine", ["netcdf4", "scipy"])
def test_invalid_netcdf_raises(engine):
data = create_test_data()
with raises_regex(ValueError, "unrecognized option 'invalid_netcdf'"):
data.to_netcdf("foo.nc", engine=engine, invalid_netcdf=True)
| @pytest.mark.parametrize("engine", ["netcdf4", "scipy"])
def test_invalid_netcdf_raises(engine):
| data = create_test_data()
with raises_regex(ValueError, "unrecognized option 'invalid_netcdf'"):
data.to_netcdf("foo.nc", engine=engine, invalid_netcdf=True)
| _file() as tmp_file:
original.to_netcdf(tmp_file)
with pytest.raises((OutOfBoundsDatetime, ValueError)):
open_dataset(tmp_file, use_cftime=False)
@pytest.mark.parametrize("engine", ["netcdf4", "scipy"])
def test_invalid_netcdf_raises(engine):
| 64 | 64 | 70 | 25 | 39 | qwhelan/xarray | xarray/tests/test_backends.py | Python | test_invalid_netcdf_raises | test_invalid_netcdf_raises | 4,394 | 4,398 | 4,394 | 4,395 | b2e2464a955bd1b041d3fbd9ffa708da15a2b264 | bigcode/the-stack | train |
25b620d157526ff9af872b6e | train | function | @pytest.fixture(params=["scipy", "netcdf4", "h5netcdf", "pynio"])
def readengine(request):
return request.param
| @pytest.fixture(params=["scipy", "netcdf4", "h5netcdf", "pynio"])
def readengine(request):
| return request.param
| assert actual["x"].encoding["chunksizes"] == (50, 100)
assert actual["y"].encoding["chunksizes"] == (100, 50)
@pytest.fixture(params=["scipy", "netcdf4", "h5netcdf", "pynio"])
def readengine(request):
| 64 | 64 | 33 | 28 | 36 | qwhelan/xarray | xarray/tests/test_backends.py | Python | readengine | readengine | 2,402 | 2,404 | 2,402 | 2,403 | 6a8dbff69895e54cad9194f0a0270b4d4648371b | bigcode/the-stack | train |
ce4f1895210dcbc0bbd7c177 | train | class | class ScipyWriteBase(CFEncodedBase, NetCDF3Only):
def test_append_write(self):
import scipy
if scipy.__version__ == "1.0.1":
pytest.xfail("https://github.com/scipy/scipy/issues/8625")
super().test_append_write()
def test_append_overwrite_values(self):
import scipy
... | class ScipyWriteBase(CFEncodedBase, NetCDF3Only):
| def test_append_write(self):
import scipy
if scipy.__version__ == "1.0.1":
pytest.xfail("https://github.com/scipy/scipy/issues/8625")
super().test_append_write()
def test_append_overwrite_values(self):
import scipy
if scipy.__version__ == "1.0.1":
... | }
@requires_zarr
class TestZarrDirectoryStore(ZarrBase):
@contextlib.contextmanager
def create_zarr_target(self):
with create_tmp_file(suffix=".zarr") as tmp:
yield tmp
class ScipyWriteBase(CFEncodedBase, NetCDF3Only):
| 64 | 64 | 119 | 15 | 48 | qwhelan/xarray | xarray/tests/test_backends.py | Python | ScipyWriteBase | ScipyWriteBase | 1,928 | 1,941 | 1,928 | 1,928 | aa5bb91f026104c3f2ff0180df56a082c95b0c96 | bigcode/the-stack | train |
bb2d681a3769ddc3243e07ff | train | class | @requires_zarr
class TestZarrDictStore(ZarrBase):
@contextlib.contextmanager
def create_zarr_target(self):
yield {}
| @requires_zarr
class TestZarrDictStore(ZarrBase):
@contextlib.contextmanager
| def create_zarr_target(self):
yield {}
| as ds1:
assert_equal(ds1, original)
with self.roundtrip(ds1.isel(t=0)) as ds2:
assert_equal(ds2, original.isel(t=0))
@requires_zarr
class TestZarrDictStore(ZarrBase):
@contextlib.contextmanager
| 64 | 64 | 33 | 22 | 42 | qwhelan/xarray | xarray/tests/test_backends.py | Python | TestZarrDictStore | TestZarrDictStore | 1,913 | 1,917 | 1,913 | 1,915 | 40a4c24037e931d0fbcedf0752ce19441a332eec | bigcode/the-stack | train |
4d15ecb7fee8586f885bb19b | train | class | @requires_h5netcdf
@requires_dask
@pytest.mark.filterwarnings("ignore:deallocating CachingFileManager")
class TestH5NetCDFViaDaskData(TestH5NetCDFData):
@contextlib.contextmanager
def roundtrip(
self, data, save_kwargs=None, open_kwargs=None, allow_cleanup_failure=False
):
if save_kwargs is ... | @requires_h5netcdf
@requires_dask
@pytest.mark.filterwarnings("ignore:deallocating CachingFileManager")
class TestH5NetCDFViaDaskData(TestH5NetCDFData):
@contextlib.contextmanager
| def roundtrip(
self, data, save_kwargs=None, open_kwargs=None, allow_cleanup_failure=False
):
if save_kwargs is None:
save_kwargs = {}
if open_kwargs is None:
open_kwargs = {}
open_kwargs.setdefault("chunks", -1)
with TestH5NetCDFData.roundtrip(
... | ") as f:
with open_dataset(f, engine="h5netcdf") as actual:
assert_identical(expected, actual)
f.seek(0)
with BytesIO(f.read()) as bio:
with open_dataset(bio, engine="h5netcdf") as actual:
assert_identical(e... | 120 | 120 | 402 | 51 | 69 | qwhelan/xarray | xarray/tests/test_backends.py | Python | TestH5NetCDFViaDaskData | TestH5NetCDFViaDaskData | 2,362 | 2,399 | 2,362 | 2,366 | 4c148384713c671f318c149168fbc61f09eafae2 | bigcode/the-stack | train |
56052b8eaa6bf26fbd1ea542 | train | class | @network
@requires_scipy_or_netCDF4
@requires_pydap
class TestPydapOnline(TestPydap):
@contextlib.contextmanager
def create_datasets(self, **kwargs):
url = "http://test.opendap.org/opendap/hyrax/data/nc/bears.nc"
actual = open_dataset(url, engine="pydap", **kwargs)
with open_example_data... | @network
@requires_scipy_or_netCDF4
@requires_pydap
class TestPydapOnline(TestPydap):
@contextlib.contextmanager
| def create_datasets(self, **kwargs):
url = "http://test.opendap.org/opendap/hyrax/data/nc/bears.nc"
actual = open_dataset(url, engine="pydap", **kwargs)
with open_example_dataset("bears.nc") as expected:
# workaround to restore string which is converted to byte
expect... | with self.create_datasets(chunks={"j": 2}) as (actual, expected):
assert_equal(actual, expected)
@network
@requires_scipy_or_netCDF4
@requires_pydap
class TestPydapOnline(TestPydap):
@contextlib.contextmanager
| 64 | 64 | 216 | 37 | 27 | qwhelan/xarray | xarray/tests/test_backends.py | Python | TestPydapOnline | TestPydapOnline | 3,184 | 3,203 | 3,184 | 3,188 | 5578fed9636f76160d2e0f69c568fd783314aec3 | bigcode/the-stack | train |
c7b5b8f7f44cca51be13acdc | train | function | @pytest.fixture(params=[5, None])
def file_cache_maxsize(request):
maxsize = request.param
if maxsize is not None:
with set_options(file_cache_maxsize=maxsize):
yield maxsize
else:
yield maxsize
| @pytest.fixture(params=[5, None])
def file_cache_maxsize(request):
| maxsize = request.param
if maxsize is not None:
with set_options(file_cache_maxsize=maxsize):
yield maxsize
else:
yield maxsize
| =["scipy", "netcdf4", "h5netcdf", "pynio"])
def readengine(request):
return request.param
@pytest.fixture(params=[1, 20])
def nfiles(request):
return request.param
@pytest.fixture(params=[5, None])
def file_cache_maxsize(request):
| 64 | 64 | 54 | 15 | 48 | qwhelan/xarray | xarray/tests/test_backends.py | Python | file_cache_maxsize | file_cache_maxsize | 2,412 | 2,419 | 2,412 | 2,413 | 5465f0e613fb26c40183a962702a84147f37c060 | bigcode/the-stack | train |
4691515258b42b21588651d3 | train | class | @requires_netCDF4
class TestNetCDF4Data(NetCDF4Base):
@contextlib.contextmanager
def create_store(self):
with create_tmp_file() as tmp_file:
with backends.NetCDF4DataStore.open(tmp_file, mode="w") as store:
yield store
def test_variable_order(self):
# doesn't wor... | @requires_netCDF4
class TestNetCDF4Data(NetCDF4Base):
@contextlib.contextmanager
| def create_store(self):
with create_tmp_file() as tmp_file:
with backends.NetCDF4DataStore.open(tmp_file, mode="w") as store:
yield store
def test_variable_order(self):
# doesn't work with scipy or h5py :(
ds = Dataset()
ds["a"] = 1
ds["z"] = ... | (self):
with create_tmp_file() as tmp_file:
values = np.array(["foo", "bar", "baz"], dtype=object)
with nc4.Dataset(tmp_file, mode="w") as nc:
nc.createDimension("x", 3)
v = nc.createVariable("x", str, ("x",))
v[:] = values
ex... | 256 | 256 | 949 | 24 | 232 | qwhelan/xarray | xarray/tests/test_backends.py | Python | TestNetCDF4Data | TestNetCDF4Data | 1,308 | 1,408 | 1,308 | 1,310 | 8fc12934e31a42806d5e67fa47b88d3c0e55e987 | bigcode/the-stack | train |
be5038cf1f08bf14fe070181 | train | class | @requires_scipy_or_netCDF4
@requires_pydap
@pytest.mark.filterwarnings("ignore:The binary mode of fromstring is deprecated")
class TestPydap:
def convert_to_pydap_dataset(self, original):
from pydap.model import GridType, BaseType, DatasetType
ds = DatasetType("bears", **original.attrs)
for... | @requires_scipy_or_netCDF4
@requires_pydap
@pytest.mark.filterwarnings("ignore:The binary mode of fromstring is deprecated")
class TestPydap:
| def convert_to_pydap_dataset(self, original):
from pydap.model import GridType, BaseType, DatasetType
ds = DatasetType("bears", **original.attrs)
for key, var in original.data_vars.items():
v = GridType(key)
v[key] = BaseType(key, var.values, dimensions=var.dims, **v... | foo": ("x", [1])}, coords={"x": ("x", [1])})
with create_tmp_file() as tmp1:
with create_tmp_file() as tmp2:
ds1.to_netcdf(tmp1)
ds2.to_netcdf(tmp2)
with pytest.warns(FutureWarning, match="supplied have global"):
open_mfdataset([tm... | 234 | 234 | 783 | 37 | 197 | qwhelan/xarray | xarray/tests/test_backends.py | Python | TestPydap | TestPydap | 3,105 | 3,181 | 3,105 | 3,108 | f22dd0b25f05ea19289e7b045b091a5ceb3d08e7 | bigcode/the-stack | train |
de1d66bfd94591d38bb18d10 | train | class | class DatasetIOBase:
engine: Optional[str] = None
file_format: Optional[str] = None
def create_store(self):
raise NotImplementedError()
@contextlib.contextmanager
def roundtrip(
self, data, save_kwargs=None, open_kwargs=None, allow_cleanup_failure=False
):
if save_kwarg... | class DatasetIOBase:
| engine: Optional[str] = None
file_format: Optional[str] = None
def create_store(self):
raise NotImplementedError()
@contextlib.contextmanager
def roundtrip(
self, data, save_kwargs=None, open_kwargs=None, allow_cleanup_failure=False
):
if save_kwargs is None:
... | 128, 255] unsigned
sb = np.asarray([-110, 1, 127, -127], dtype="i1")
return Dataset({"x": ("t", sb, attributes)})
def create_boolean_data():
attributes = {"units": "-"}
return Dataset({"x": ("t", [True, False, False, True], attributes)})
class TestCommon:
def test_robust_getitem(self):
c... | 256 | 256 | 4,675 | 5 | 250 | qwhelan/xarray | xarray/tests/test_backends.py | Python | DatasetIOBase | DatasetIOBase | 227 | 708 | 227 | 227 | 4190399274df60b8e639ac32e25138664c965a01 | bigcode/the-stack | train |
7bef3b4f950f806695b49e25 | train | function | def create_encoded_signed_masked_scaled_data():
# These are values as written to the file: the _FillValue will
# be represented in the signed form.
attributes = {
"_FillValue": -127,
"_Unsigned": "false",
"add_offset": 10,
"scale_factor": np.float32(0.1),
}
# Create s... | def create_encoded_signed_masked_scaled_data():
# These are values as written to the file: the _FillValue will
# be represented in the signed form.
| attributes = {
"_FillValue": -127,
"_Unsigned": "false",
"add_offset": 10,
"scale_factor": np.float32(0.1),
}
# Create signed data corresponding to [0, 1, 127, 128, 255] unsigned
sb = np.asarray([-110, 1, 127, -127], dtype="i1")
return Dataset({"x": ("t", sb, attribut... | , 22.7, np.nan], dtype=np.float32)
return Dataset({"x": ("t", x, {}, encoding)})
def create_encoded_signed_masked_scaled_data():
# These are values as written to the file: the _FillValue will
# be represented in the signed form.
| 63 | 64 | 136 | 35 | 29 | qwhelan/xarray | xarray/tests/test_backends.py | Python | create_encoded_signed_masked_scaled_data | create_encoded_signed_masked_scaled_data | 179 | 190 | 179 | 181 | 0112b16e872d0f05138700ef2ba910f431ca020a | bigcode/the-stack | train |
4805699fa413a6665f602998 | train | function | def create_signed_masked_scaled_data():
encoding = {
"_FillValue": -127,
"_Unsigned": "false",
"dtype": "i1",
"add_offset": 10,
"scale_factor": np.float32(0.1),
}
x = np.array([-1.0, 10.1, 22.7, np.nan], dtype=np.float32)
return Dataset({"x": ("t", x, {}, encoding... | def create_signed_masked_scaled_data():
| encoding = {
"_FillValue": -127,
"_Unsigned": "false",
"dtype": "i1",
"add_offset": 10,
"scale_factor": np.float32(0.1),
}
x = np.array([-1.0, 10.1, 22.7, np.nan], dtype=np.float32)
return Dataset({"x": ("t", x, {}, encoding)})
| [0, 1, 127, 128, 255] unsigned
sb = np.asarray([0, 1, 127, -128, -1], dtype="i1")
return Dataset({"x": ("t", sb, attributes)})
def create_signed_masked_scaled_data():
| 63 | 64 | 100 | 8 | 56 | qwhelan/xarray | xarray/tests/test_backends.py | Python | create_signed_masked_scaled_data | create_signed_masked_scaled_data | 167 | 176 | 167 | 167 | b243ee7cd564ed770d0d2d77268df0239432adec | bigcode/the-stack | train |
cc1f4b7c4c13c8fac590f53d | train | class | @requires_dask
@requires_scipy
@requires_netCDF4
class TestDask(DatasetIOBase):
@contextlib.contextmanager
def create_store(self):
yield Dataset()
@contextlib.contextmanager
def roundtrip(
self, data, save_kwargs=None, open_kwargs=None, allow_cleanup_failure=False
):
yield d... | @requires_dask
@requires_scipy
@requires_netCDF4
class TestDask(DatasetIOBase):
@contextlib.contextmanager
| def create_store(self):
yield Dataset()
@contextlib.contextmanager
def roundtrip(
self, data, save_kwargs=None, open_kwargs=None, allow_cleanup_failure=False
):
yield data.chunk()
# Override methods in DatasetIOBase - not applicable to dask
def test_roundtrip_string_enc... | minimal"
with self.setup_files_and_datasets() as (files, [ds1, ds2]):
# open the files using data_vars option
with open_mfdataset(
files, data_vars=opt, combine="nested", concat_dim="t"
) as ds:
coord_shape = ds[self.coord_name].shape
... | 256 | 256 | 4,346 | 33 | 222 | qwhelan/xarray | xarray/tests/test_backends.py | Python | TestDask | TestDask | 2,625 | 3,035 | 2,625 | 2,629 | 1404ff9da7d2679ccfcc93e2de61918826a8ecd5 | bigcode/the-stack | train |
99fe8140d7f7ee752173c013 | train | function | @requires_scipy_or_netCDF4
@pytest.mark.parametrize("calendar", _NON_STANDARD_CALENDARS)
@pytest.mark.parametrize("units_year", [1500, 2000, 2500])
def test_use_cftime_false_nonstandard_calendar(calendar, units_year):
x = [0, 1]
time = [0, 720]
units = f"days since {units_year}"
original = DataArray(x, ... | @requires_scipy_or_netCDF4
@pytest.mark.parametrize("calendar", _NON_STANDARD_CALENDARS)
@pytest.mark.parametrize("units_year", [1500, 2000, 2500])
def test_use_cftime_false_nonstandard_calendar(calendar, units_year):
| x = [0, 1]
time = [0, 720]
units = f"days since {units_year}"
original = DataArray(x, [("time", time)], name="x")
original = original.to_dataset()
for v in ["x", "time"]:
original[v].attrs["units"] = units
original[v].attrs["calendar"] = calendar
with create_tmp_file() as tm... | (tmp_file, use_cftime=False)
@requires_scipy_or_netCDF4
@pytest.mark.parametrize("calendar", _NON_STANDARD_CALENDARS)
@pytest.mark.parametrize("units_year", [1500, 2000, 2500])
def test_use_cftime_false_nonstandard_calendar(calendar, units_year):
| 64 | 64 | 184 | 56 | 8 | qwhelan/xarray | xarray/tests/test_backends.py | Python | test_use_cftime_false_nonstandard_calendar | test_use_cftime_false_nonstandard_calendar | 4,375 | 4,391 | 4,375 | 4,378 | b992b36f02954eef5df195773047cf663bca1fb9 | bigcode/the-stack | train |
b052ef16c78cc7864be8179c | train | class | class TestCommon:
def test_robust_getitem(self):
class UnreliableArrayFailure(Exception):
pass
class UnreliableArray:
def __init__(self, array, failures=1):
self.array = array
self.failures = failures
def __getitem__(self, key):
... | class TestCommon:
| def test_robust_getitem(self):
class UnreliableArrayFailure(Exception):
pass
class UnreliableArray:
def __init__(self, array, failures=1):
self.array = array
self.failures = failures
def __getitem__(self, key):
if ... | , 127, -127], dtype="i1")
return Dataset({"x": ("t", sb, attributes)})
def create_boolean_data():
attributes = {"units": "-"}
return Dataset({"x": ("t", [True, False, False, True], attributes)})
class TestCommon:
| 63 | 64 | 165 | 4 | 60 | qwhelan/xarray | xarray/tests/test_backends.py | Python | TestCommon | TestCommon | 198 | 220 | 198 | 198 | 2e55d4e3a60b747e52a454d9c47d338c1988f3ee | bigcode/the-stack | train |
b729602b9ad01872e0a8d93a | train | class | class NetCDF4Base(CFEncodedBase):
"""Tests for both netCDF4-python and h5netcdf."""
engine = "netcdf4"
def test_open_group(self):
# Create a netCDF file with a dataset stored within a group
with create_tmp_file() as tmp_file:
with nc4.Dataset(tmp_file, "w") as rootgrp:
... | class NetCDF4Base(CFEncodedBase):
| """Tests for both netCDF4-python and h5netcdf."""
engine = "netcdf4"
def test_open_group(self):
# Create a netCDF file with a dataset stored within a group
with create_tmp_file() as tmp_file:
with nc4.Dataset(tmp_file, "w") as rootgrp:
foogrp = rootgrp.createGro... | dimension"
):
self.save(data, tmp_file, mode="a")
def test_multiindex_not_implemented(self):
ds = Dataset(coords={"y": ("x", [1, 2]), "z": ("x", ["a", "b"])}).set_index(
x=["y", "z"]
)
with raises_regex(NotImplementedError, "MultiIndex"):
... | 256 | 256 | 2,858 | 10 | 245 | qwhelan/xarray | xarray/tests/test_backends.py | Python | NetCDF4Base | NetCDF4Base | 1,010 | 1,305 | 1,010 | 1,010 | 4ceca7f25e7152369ced72ac523269a1a1f038d7 | bigcode/the-stack | train |
d784f6a231a3197c00d59832 | train | function | def create_encoded_unsigned_masked_scaled_data():
# These are values as written to the file: the _FillValue will
# be represented in the signed form.
attributes = {
"_FillValue": -1,
"_Unsigned": "true",
"add_offset": 10,
"scale_factor": np.float32(0.1),
}
# Create un... | def create_encoded_unsigned_masked_scaled_data():
# These are values as written to the file: the _FillValue will
# be represented in the signed form.
| attributes = {
"_FillValue": -1,
"_Unsigned": "true",
"add_offset": 10,
"scale_factor": np.float32(0.1),
}
# Create unsigned data corresponding to [0, 1, 127, 128, 255] unsigned
sb = np.asarray([0, 1, 127, -128, -1], dtype="i1")
return Dataset({"x": ("t", sb, attribut... | , 22.8, np.nan], dtype=np.float32)
return Dataset({"x": ("t", x, {}, encoding)})
def create_encoded_unsigned_masked_scaled_data():
# These are values as written to the file: the _FillValue will
# be represented in the signed form.
| 63 | 64 | 139 | 35 | 29 | qwhelan/xarray | xarray/tests/test_backends.py | Python | create_encoded_unsigned_masked_scaled_data | create_encoded_unsigned_masked_scaled_data | 127 | 138 | 127 | 129 | 2fe78d7302ec368a71dd1e2e18ed2159ad4d6f5a | bigcode/the-stack | train |
aec90bf2b2c8f4ee898e9f7f | train | function | @requires_cftime
@requires_scipy_or_netCDF4
@pytest.mark.parametrize("calendar", _STANDARD_CALENDARS)
@pytest.mark.parametrize("units_year", [1500, 2500])
def test_use_cftime_standard_calendar_default_out_of_range(calendar, units_year):
import cftime
x = [0, 1]
time = [0, 720]
units = f"days since {uni... | @requires_cftime
@requires_scipy_or_netCDF4
@pytest.mark.parametrize("calendar", _STANDARD_CALENDARS)
@pytest.mark.parametrize("units_year", [1500, 2500])
def test_use_cftime_standard_calendar_default_out_of_range(calendar, units_year):
| import cftime
x = [0, 1]
time = [0, 720]
units = f"days since {units_year}-01-01"
original = DataArray(x, [("time", time)], name="x")
original = original.to_dataset()
for v in ["x", "time"]:
original[v].attrs["units"] = units
original[v].attrs["calendar"] = calendar
dec... | _dataset(tmp_file) as ds:
assert_identical(expected_x, ds.x)
assert_identical(expected_time, ds.time)
assert not record
@requires_cftime
@requires_scipy_or_netCDF4
@pytest.mark.parametrize("calendar", _STANDARD_CALENDARS)
@pytest.mark.parametrize("units_year", [1500, 2500])
d... | 90 | 90 | 300 | 58 | 31 | qwhelan/xarray | xarray/tests/test_backends.py | Python | test_use_cftime_standard_calendar_default_out_of_range | test_use_cftime_standard_calendar_default_out_of_range | 4,264 | 4,292 | 4,264 | 4,268 | e8c49a4aee18f65ff0b4b1d1c3e19a8cad1ee3a5 | bigcode/the-stack | train |
e3cf1d762abdd90e55189d3f | train | function | @contextlib.contextmanager
def create_tmp_file(suffix=".nc", allow_cleanup_failure=False):
temp_dir = tempfile.mkdtemp()
path = os.path.join(temp_dir, "temp-{}{}".format(next(_counter), suffix))
try:
yield path
finally:
try:
shutil.rmtree(temp_dir)
except OSError:
... | @contextlib.contextmanager
def create_tmp_file(suffix=".nc", allow_cleanup_failure=False):
| temp_dir = tempfile.mkdtemp()
path = os.path.join(temp_dir, "temp-{}{}".format(next(_counter), suffix))
try:
yield path
finally:
try:
shutil.rmtree(temp_dir)
except OSError:
if not allow_cleanup_failure:
raise
| b"])}).set_index(
x=["y", "z"]
)
with raises_regex(NotImplementedError, "MultiIndex"):
with self.roundtrip(ds):
pass
_counter = itertools.count()
@contextlib.contextmanager
def create_tmp_file(suffix=".nc", allow_cleanup_failure=False):
| 64 | 64 | 85 | 20 | 44 | qwhelan/xarray | xarray/tests/test_backends.py | Python | create_tmp_file | create_tmp_file | 986 | 997 | 986 | 987 | 99f72b9c00da343d83fa28a8a3b4ababf8da24dd | bigcode/the-stack | train |
0b3d482e6a0c63a0c51d5590 | train | function | def create_bad_encoded_unsigned_masked_scaled_data():
# These are values as written to the file: the _FillValue will
# be represented in the signed form.
attributes = {
"_FillValue": -1,
"_Unsigned": True,
"add_offset": 10,
"scale_factor": np.float32(0.1),
}
# Create ... | def create_bad_encoded_unsigned_masked_scaled_data():
# These are values as written to the file: the _FillValue will
# be represented in the signed form.
| attributes = {
"_FillValue": -1,
"_Unsigned": True,
"add_offset": 10,
"scale_factor": np.float32(0.1),
}
# Create signed data corresponding to [0, 1, 127, 128, 255] unsigned
sb = np.asarray([0, 1, 127, -128, -1], dtype="i1")
return Dataset({"x": ("t", sb, attributes)}... | 22.8, np.nan], dtype=np.float32)
return Dataset({"x": ("t", x, {}, encoding)})
def create_bad_encoded_unsigned_masked_scaled_data():
# These are values as written to the file: the _FillValue will
# be represented in the signed form.
| 63 | 64 | 139 | 36 | 28 | qwhelan/xarray | xarray/tests/test_backends.py | Python | create_bad_encoded_unsigned_masked_scaled_data | create_bad_encoded_unsigned_masked_scaled_data | 153 | 164 | 153 | 155 | 8d33a127e0cb798758194cbd167ace092f0425cd | bigcode/the-stack | train |
dd0fabf89c2e72f5681b5233 | train | class | @requires_h5netcdf
@requires_netCDF4
@pytest.mark.filterwarnings("ignore:use make_scale(name) instead")
class TestH5NetCDFData(NetCDF4Base):
engine = "h5netcdf"
@contextlib.contextmanager
def create_store(self):
with create_tmp_file() as tmp_file:
yield backends.H5NetCDFStore(tmp_file, ... | @requires_h5netcdf
@requires_netCDF4
@pytest.mark.filterwarnings("ignore:use make_scale(name) instead")
class TestH5NetCDFData(NetCDF4Base):
| engine = "h5netcdf"
@contextlib.contextmanager
def create_store(self):
with create_tmp_file() as tmp_file:
yield backends.H5NetCDFStore(tmp_file, "w")
@pytest.mark.filterwarnings("ignore:complex dtypes are supported by h5py")
@pytest.mark.parametrize(
"invalid_netcdf, w... | x": ("y", np.arange(10.0))})
with self.roundtrip(ds, save_kwargs=dict(unlimited_dims=["y"])) as actual:
assert actual.encoding["unlimited_dims"] == set("y")
assert_equal(ds, actual)
# Regression test for https://github.com/pydata/xarray/issues/2134
with self.roundtrip(ds... | 256 | 256 | 1,548 | 39 | 217 | qwhelan/xarray | xarray/tests/test_backends.py | Python | TestH5NetCDFData | TestH5NetCDFData | 2,143 | 2,313 | 2,143 | 2,146 | 0f8fb40c95d6491ef6713b5dae5caa280d7e0388 | bigcode/the-stack | train |
8f8631d369fa0b1cb9b54732 | train | function | @requires_rasterio
@contextlib.contextmanager
def create_tmp_geotiff(
nx=4,
ny=3,
nz=3,
transform=None,
transform_args=[5000, 80000, 1000, 2000.0],
crs={"units": "m", "no_defs": True, "ellps": "WGS84", "proj": "utm", "zone": 18},
open_kwargs=None,
additional_attrs=None,
):
# yields a... | @requires_rasterio
@contextlib.contextmanager
def create_tmp_geotiff(
nx=4,
ny=3,
nz=3,
transform=None,
transform_args=[5000, 80000, 1000, 2000.0],
crs={"units": "m", "no_defs": True, "ellps": "WGS84", "proj": "utm", "zone": 18},
open_kwargs=None,
additional_attrs=None,
):
# yields a... | import rasterio
from rasterio.transform import from_origin
if open_kwargs is None:
open_kwargs = {}
with create_tmp_file(suffix=".tif", allow_cleanup_failure=ON_WINDOWS) as tmp_file:
# allow 2d or 3d shapes
if nz == 1:
data_shape = ny, nx
write_kwargs = ... | .variables.items()
}
for pk, pv in dataset.attrs.items():
setattr(pncf, pk, pv)
pnc.pncwrite(pncf, path, **save_kwargs)
@requires_rasterio
@contextlib.contextmanager
def create_tmp_geotiff(
nx=4,
ny=3,
nz=3,
transform=None,
transform_args=[5000, 80000, 1000, 2000... | 163 | 163 | 544 | 122 | 41 | qwhelan/xarray | xarray/tests/test_backends.py | Python | create_tmp_geotiff | create_tmp_geotiff | 3,486 | 3,549 | 3,486 | 3,498 | c10cd682cc04ca7956f6cf0e48c28d087391cab2 | bigcode/the-stack | train |
88f96211dd359dd08e649449 | train | function | def open_example_mfdataset(names, *args, **kwargs):
return open_mfdataset(
[os.path.join(os.path.dirname(__file__), "data", name) for name in names],
*args,
**kwargs,
)
| def open_example_mfdataset(names, *args, **kwargs):
| return open_mfdataset(
[os.path.join(os.path.dirname(__file__), "data", name) for name in names],
*args,
**kwargs,
)
| ON_WINDOWS = sys.platform == "win32"
def open_example_dataset(name, *args, **kwargs):
return open_dataset(
os.path.join(os.path.dirname(__file__), "data", name), *args, **kwargs
)
def open_example_mfdataset(names, *args, **kwargs):
| 64 | 64 | 52 | 14 | 50 | qwhelan/xarray | xarray/tests/test_backends.py | Python | open_example_mfdataset | open_example_mfdataset | 91 | 96 | 91 | 91 | b6f5577befce323792e9970190857cf288d3379f | bigcode/the-stack | train |
3220863ea4f929ed51db1a95 | train | class | @requires_netCDF4
@requires_dask
@pytest.mark.filterwarnings("ignore:deallocating CachingFileManager")
class TestNetCDF4ViaDaskData(TestNetCDF4Data):
@contextlib.contextmanager
def roundtrip(
self, data, save_kwargs=None, open_kwargs=None, allow_cleanup_failure=False
):
if open_kwargs is Non... | @requires_netCDF4
@requires_dask
@pytest.mark.filterwarnings("ignore:deallocating CachingFileManager")
class TestNetCDF4ViaDaskData(TestNetCDF4Data):
@contextlib.contextmanager
| def roundtrip(
self, data, save_kwargs=None, open_kwargs=None, allow_cleanup_failure=False
):
if open_kwargs is None:
open_kwargs = {}
if save_kwargs is None:
save_kwargs = {}
open_kwargs.setdefault("chunks", -1)
with TestNetCDF4Data.roundtrip(
... | (nc, group="g")
with open_dataset(store) as ds:
expected = Dataset({"x": ((), 42)})
assert_identical(expected, ds)
with nc4.Dataset(tmp_file, mode="r") as nc:
with pytest.raises(ValueError, match="must supply a root"):
backends... | 131 | 131 | 439 | 48 | 83 | qwhelan/xarray | xarray/tests/test_backends.py | Python | TestNetCDF4ViaDaskData | TestNetCDF4ViaDaskData | 1,411 | 1,453 | 1,411 | 1,415 | 668f87b998b3a1bc489598c75a0803fd5f1ea9e1 | bigcode/the-stack | train |
1434364cfc96d9f504846520 | train | function | def create_boolean_data():
attributes = {"units": "-"}
return Dataset({"x": ("t", [True, False, False, True], attributes)})
| def create_boolean_data():
| attributes = {"units": "-"}
return Dataset({"x": ("t", [True, False, False, True], attributes)})
| # Create signed data corresponding to [0, 1, 127, 128, 255] unsigned
sb = np.asarray([-110, 1, 127, -127], dtype="i1")
return Dataset({"x": ("t", sb, attributes)})
def create_boolean_data():
| 63 | 64 | 33 | 5 | 59 | qwhelan/xarray | xarray/tests/test_backends.py | Python | create_boolean_data | create_boolean_data | 193 | 195 | 193 | 193 | 861f710f1efca73ce45622807731a7bf0da84d71 | bigcode/the-stack | train |
fa5a25f23bfdb0a9006040a0 | train | function | @pytest.fixture(params=[1, 20])
def nfiles(request):
return request.param
| @pytest.fixture(params=[1, 20])
def nfiles(request):
| return request.param
| assert actual["y"].encoding["chunksizes"] == (100, 50)
@pytest.fixture(params=["scipy", "netcdf4", "h5netcdf", "pynio"])
def readengine(request):
return request.param
@pytest.fixture(params=[1, 20])
def nfiles(request):
| 64 | 64 | 19 | 14 | 49 | qwhelan/xarray | xarray/tests/test_backends.py | Python | nfiles | nfiles | 2,407 | 2,409 | 2,407 | 2,408 | 64937e6e876a95db4f0a0d7752aef2505426ba85 | bigcode/the-stack | train |
cda448a342c5d8e68e4af71e | train | function | def create_encoded_masked_and_scaled_data():
attributes = {"_FillValue": -1, "add_offset": 10, "scale_factor": np.float32(0.1)}
return Dataset({"x": ("t", np.int16([-1, -1, 0, 1, 2]), attributes)})
| def create_encoded_masked_and_scaled_data():
| attributes = {"_FillValue": -1, "add_offset": 10, "scale_factor": np.float32(0.1)}
return Dataset({"x": ("t", np.int16([-1, -1, 0, 1, 2]), attributes)})
| {
"_FillValue": -1,
"add_offset": 10,
"scale_factor": np.float32(0.1),
"dtype": "i2",
}
return Dataset({"x": ("t", x, {}, encoding)})
def create_encoded_masked_and_scaled_data():
| 63 | 64 | 68 | 9 | 55 | qwhelan/xarray | xarray/tests/test_backends.py | Python | create_encoded_masked_and_scaled_data | create_encoded_masked_and_scaled_data | 110 | 112 | 110 | 110 | c8bfb1ac67735503ba8b1fe2b82df0cee7a93d49 | bigcode/the-stack | train |
4338d0424df41cd6fc339c56 | train | class | @requires_scipy_or_netCDF4
class TestDataArrayToNetCDF:
def test_dataarray_to_netcdf_no_name(self):
original_da = DataArray(np.arange(12).reshape((3, 4)))
with create_tmp_file() as tmp:
original_da.to_netcdf(tmp)
with open_dataarray(tmp) as loaded_da:
assert... | @requires_scipy_or_netCDF4
class TestDataArrayToNetCDF:
| def test_dataarray_to_netcdf_no_name(self):
original_da = DataArray(np.arange(12).reshape((3, 4)))
with create_tmp_file() as tmp:
original_da.to_netcdf(tmp)
with open_dataarray(tmp) as loaded_da:
assert_identical(original_da, loaded_da)
def test_dataarr... | _netcdf(tmp_file)
ds, attrs = new_dataset_and_attrs()
attrs["test"] = np.arange(5)
with create_tmp_file() as tmp_file:
ds.to_netcdf(tmp_file)
ds, attrs = new_dataset_and_attrs()
attrs["test"] = "This is a string"
with create_tmp_f... | 141 | 141 | 471 | 18 | 123 | qwhelan/xarray | xarray/tests/test_backends.py | Python | TestDataArrayToNetCDF | TestDataArrayToNetCDF | 4,156 | 4,212 | 4,156 | 4,157 | ced301f47cdaebf8d2ba8b43d2868f8a0e38c869 | bigcode/the-stack | train |
7f2101472476b2c73dbdcb52 | train | function | @requires_cftime
@requires_scipy_or_netCDF4
@pytest.mark.parametrize("calendar", _ALL_CALENDARS)
@pytest.mark.parametrize("units_year", [1500, 2000, 2500])
def test_use_cftime_true(calendar, units_year):
import cftime
x = [0, 1]
time = [0, 720]
units = f"days since {units_year}-01-01"
original = Da... | @requires_cftime
@requires_scipy_or_netCDF4
@pytest.mark.parametrize("calendar", _ALL_CALENDARS)
@pytest.mark.parametrize("units_year", [1500, 2000, 2500])
def test_use_cftime_true(calendar, units_year):
| import cftime
x = [0, 1]
time = [0, 720]
units = f"days since {units_year}-01-01"
original = DataArray(x, [("time", time)], name="x")
original = original.to_dataset()
for v in ["x", "time"]:
original[v].attrs["units"] = units
original[v].attrs["calendar"] = calendar
dec... | .warns(SerializationWarning):
with open_dataset(tmp_file) as ds:
assert_identical(expected_x, ds.x)
assert_identical(expected_time, ds.time)
@requires_cftime
@requires_scipy_or_netCDF4
@pytest.mark.parametrize("calendar", _ALL_CALENDARS)
@pytest.mark.parametrize("units_year",... | 93 | 93 | 310 | 57 | 36 | qwhelan/xarray | xarray/tests/test_backends.py | Python | test_use_cftime_true | test_use_cftime_true | 4,295 | 4,324 | 4,295 | 4,299 | c556a4d912ee41fa52c15f3d5e131b95b565db02 | bigcode/the-stack | train |
97fb9327878b17fac9871530 | train | class | @requires_scipy_or_netCDF4
class TestGenericNetCDFData(CFEncodedBase, NetCDF3Only):
# verify that we can read and write netCDF3 files as long as we have scipy
# or netCDF4-python installed
file_format = "netcdf3_64bit"
def test_write_store(self):
# there's no specific store to test here
... | @requires_scipy_or_netCDF4
class TestGenericNetCDFData(CFEncodedBase, NetCDF3Only):
# verify that we can read and write netCDF3 files as long as we have scipy
# or netCDF4-python installed
| file_format = "netcdf3_64bit"
def test_write_store(self):
# there's no specific store to test here
pass
@requires_scipy
def test_engine(self):
data = create_test_data()
with raises_regex(ValueError, "unrecognized engine"):
data.to_netcdf("foo.nc", engine="fo... | = dict(encoding={"x": {"dtype": str}})
with raises_regex(ValueError, "encoding dtype=str for vlen"):
with self.roundtrip(original, save_kwargs=kwargs):
pass
@requires_netCDF4
class TestNetCDF4ClassicViaNetCDF4Data(CFEncodedBase, NetCDF3Only):
engine = "netcdf4"
file_format... | 202 | 202 | 674 | 55 | 146 | qwhelan/xarray | xarray/tests/test_backends.py | Python | TestGenericNetCDFData | TestGenericNetCDFData | 2,070 | 2,140 | 2,070 | 2,073 | ceb1eba551d9b27235047f2a7cd87818830b6bb5 | bigcode/the-stack | train |
592783ac804af6a34b80ac7c | train | function | @requires_netCDF4
def test_open_mfdataset_list_attr():
"""
Case when an attribute of type list differs across the multiple files
"""
from netCDF4 import Dataset
with create_tmp_files(2) as nfiles:
for i in range(2):
f = Dataset(nfiles[i], "w")
f.createDimension("x", ... | @requires_netCDF4
def test_open_mfdataset_list_attr():
| """
Case when an attribute of type list differs across the multiple files
"""
from netCDF4 import Dataset
with create_tmp_files(2) as nfiles:
for i in range(2):
f = Dataset(nfiles[i], "w")
f.createDimension("x", 3)
vlvar = f.createVariable("test_var", np.... | parallel=parallel,
chunks=chunks,
) as actual:
# check that using open_mfdataset returns dask arrays for variables
assert isinstance(actual["foo"].data, dask_array_type)
assert_identical(original, actual)
@requires_netCDF4
def test_open_mfdataset_list_attr():
| 67 | 67 | 226 | 15 | 52 | qwhelan/xarray | xarray/tests/test_backends.py | Python | test_open_mfdataset_list_attr | test_open_mfdataset_list_attr | 2,480 | 2,502 | 2,480 | 2,481 | 52848cddca34b92f072ce1b1aebf0f569ba8cb50 | bigcode/the-stack | train |
f1a071d92a042862b300b319 | train | function | def create_masked_and_scaled_data():
x = np.array([np.nan, np.nan, 10, 10.1, 10.2], dtype=np.float32)
encoding = {
"_FillValue": -1,
"add_offset": 10,
"scale_factor": np.float32(0.1),
"dtype": "i2",
}
return Dataset({"x": ("t", x, {}, encoding)})
| def create_masked_and_scaled_data():
| x = np.array([np.nan, np.nan, 10, 10.1, 10.2], dtype=np.float32)
encoding = {
"_FillValue": -1,
"add_offset": 10,
"scale_factor": np.float32(0.1),
"dtype": "i2",
}
return Dataset({"x": ("t", x, {}, encoding)})
| kwargs
)
def open_example_mfdataset(names, *args, **kwargs):
return open_mfdataset(
[os.path.join(os.path.dirname(__file__), "data", name) for name in names],
*args,
**kwargs,
)
def create_masked_and_scaled_data():
| 64 | 64 | 95 | 8 | 56 | qwhelan/xarray | xarray/tests/test_backends.py | Python | create_masked_and_scaled_data | create_masked_and_scaled_data | 99 | 107 | 99 | 99 | 3405cd73cf80911919d0525dd9a791be70e923a9 | bigcode/the-stack | train |
cc86cd74aa57d03cc9bd7b95 | train | class | @requires_scipy
class TestScipyFileObject(ScipyWriteBase):
engine = "scipy"
@contextlib.contextmanager
def create_store(self):
fobj = BytesIO()
yield backends.ScipyDataStore(fobj, "w")
@contextlib.contextmanager
def roundtrip(
self, data, save_kwargs=None, open_kwargs=None,... | @requires_scipy
class TestScipyFileObject(ScipyWriteBase):
| engine = "scipy"
@contextlib.contextmanager
def create_store(self):
fobj = BytesIO()
yield backends.ScipyDataStore(fobj, "w")
@contextlib.contextmanager
def roundtrip(
self, data, save_kwargs=None, open_kwargs=None, allow_cleanup_failure=False
):
if save_kwargs ... | 2, 3])})
fobj = data.to_netcdf()
with self.open(fobj) as ds:
unpickled = pickle.loads(pickle.dumps(ds))
assert_identical(unpickled, data)
@requires_scipy
class TestScipyFileObject(ScipyWriteBase):
| 66 | 66 | 222 | 18 | 48 | qwhelan/xarray | xarray/tests/test_backends.py | Python | TestScipyFileObject | TestScipyFileObject | 1,965 | 1,995 | 1,965 | 1,966 | 71714f9244d7cbff22d2b7d7109b57d87b16f137 | bigcode/the-stack | train |
c6f8e9bac9b2e0ea59daaacd | train | function | @requires_scipy_or_netCDF4
@pytest.mark.parametrize("calendar", _STANDARD_CALENDARS)
def test_use_cftime_standard_calendar_default_in_range(calendar):
x = [0, 1]
time = [0, 720]
units_date = "2000-01-01"
units = "days since 2000-01-01"
original = DataArray(x, [("time", time)], name="x")
original... | @requires_scipy_or_netCDF4
@pytest.mark.parametrize("calendar", _STANDARD_CALENDARS)
def test_use_cftime_standard_calendar_default_in_range(calendar):
| x = [0, 1]
time = [0, 720]
units_date = "2000-01-01"
units = "days since 2000-01-01"
original = DataArray(x, [("time", time)], name="x")
original = original.to_dataset()
for v in ["x", "time"]:
original[v].attrs["units"] = units
original[v].attrs["calendar"] = calendar
x... | .
rnddata = np.random.randn(10)
original = Dataset({"foo": ("x", rnddata)})
with create_tmp_file() as tmp:
original.to_netcdf(tmp)
with open_dataset(tmp) as ds:
assert ds.encoding["source"] == tmp
@requires_scipy_or_netCDF4
@pytest.mark.parametrize("calendar", _STANDARD_CALENDARS... | 94 | 94 | 314 | 34 | 59 | qwhelan/xarray | xarray/tests/test_backends.py | Python | test_use_cftime_standard_calendar_default_in_range | test_use_cftime_standard_calendar_default_in_range | 4,235 | 4,261 | 4,235 | 4,237 | f41f82d503e59b33b6b63d272bb925d151ac7f20 | bigcode/the-stack | train |
e155d3dc7738af8e53ab5116 | train | function | @requires_dask
@pytest.mark.filterwarnings("ignore:use make_scale(name) instead")
def test_open_mfdataset_manyfiles(
readengine, nfiles, parallel, chunks, file_cache_maxsize
):
# skip certain combinations
skip_if_not_engine(readengine)
if ON_WINDOWS:
pytest.skip("Skipping on Windows")
ran... | @requires_dask
@pytest.mark.filterwarnings("ignore:use make_scale(name) instead")
def test_open_mfdataset_manyfiles(
readengine, nfiles, parallel, chunks, file_cache_maxsize
):
# skip certain combinations
| skip_if_not_engine(readengine)
if ON_WINDOWS:
pytest.skip("Skipping on Windows")
randdata = np.random.randn(nfiles)
original = Dataset({"foo": ("x", randdata)})
# test standard open_mfdataset approach with too many files
with create_tmp_files(nfiles) as tmpfiles:
writeengine = ... | kip("netCDF4")
elif engine == "pynio":
pytest.importorskip("Nio")
else:
pytest.importorskip(engine)
@requires_dask
@pytest.mark.filterwarnings("ignore:use make_scale(name) instead")
def test_open_mfdataset_manyfiles(
readengine, nfiles, parallel, chunks, file_cache_maxsize
):
# skip cer... | 85 | 85 | 285 | 51 | 34 | qwhelan/xarray | xarray/tests/test_backends.py | Python | test_open_mfdataset_manyfiles | test_open_mfdataset_manyfiles | 2,442 | 2,477 | 2,442 | 2,448 | dbbe9f6e5007043f1fb83b48e005684d3ab0fcf7 | bigcode/the-stack | train |
be0dce0e7c5a2715b24ff1df | train | function | @requires_scipy_or_netCDF4
def test_source_encoding_always_present():
# Test for GH issue #2550.
rnddata = np.random.randn(10)
original = Dataset({"foo": ("x", rnddata)})
with create_tmp_file() as tmp:
original.to_netcdf(tmp)
with open_dataset(tmp) as ds:
assert ds.encoding["... | @requires_scipy_or_netCDF4
def test_source_encoding_always_present():
# Test for GH issue #2550.
| rnddata = np.random.randn(10)
original = Dataset({"foo": ("x", rnddata)})
with create_tmp_file() as tmp:
original.to_netcdf(tmp)
with open_dataset(tmp) as ds:
assert ds.encoding["source"] == tmp
| tmpfile:
with pytest.warns(None) as record:
ds = Dataset()
ds.to_netcdf(tmpfile)
assert len(record) == 0
@requires_scipy_or_netCDF4
def test_source_encoding_always_present():
# Test for GH issue #2550.
| 64 | 64 | 87 | 28 | 35 | qwhelan/xarray | xarray/tests/test_backends.py | Python | test_source_encoding_always_present | test_source_encoding_always_present | 4,224 | 4,232 | 4,224 | 4,226 | 279341612fe8a917f7993cb3f9e44203457ea027 | bigcode/the-stack | train |
edfda02c27e865978253f619 | train | function | def create_unsigned_masked_scaled_data():
encoding = {
"_FillValue": 255,
"_Unsigned": "true",
"dtype": "i1",
"add_offset": 10,
"scale_factor": np.float32(0.1),
}
x = np.array([10.0, 10.1, 22.7, 22.8, np.nan], dtype=np.float32)
return Dataset({"x": ("t", x, {}, en... | def create_unsigned_masked_scaled_data():
| encoding = {
"_FillValue": 255,
"_Unsigned": "true",
"dtype": "i1",
"add_offset": 10,
"scale_factor": np.float32(0.1),
}
x = np.array([10.0, 10.1, 22.7, 22.8, np.nan], dtype=np.float32)
return Dataset({"x": ("t", x, {}, encoding)})
| _FillValue": -1, "add_offset": 10, "scale_factor": np.float32(0.1)}
return Dataset({"x": ("t", np.int16([-1, -1, 0, 1, 2]), attributes)})
def create_unsigned_masked_scaled_data():
| 63 | 64 | 105 | 8 | 56 | qwhelan/xarray | xarray/tests/test_backends.py | Python | create_unsigned_masked_scaled_data | create_unsigned_masked_scaled_data | 115 | 124 | 115 | 115 | d95fd72d7af747925bd5f156e70d60ecc0813a40 | bigcode/the-stack | train |
93e261dea5bec95b895a2415 | train | class | @requires_scipy
@requires_pynio
class TestPyNio(ScipyWriteBase):
def test_write_store(self):
# pynio is read-only for now
pass
@contextlib.contextmanager
def open(self, path, **kwargs):
with open_dataset(path, engine="pynio", **kwargs) as ds:
yield ds
def test_kwarg... | @requires_scipy
@requires_pynio
class TestPyNio(ScipyWriteBase):
| def test_write_store(self):
# pynio is read-only for now
pass
@contextlib.contextmanager
def open(self, path, **kwargs):
with open_dataset(path, engine="pynio", **kwargs) as ds:
yield ds
def test_kwargs(self):
kwargs = {"format": "grib"}
path = os.pa... | session = setup_session("XarrayTestUser", "Xarray2017")
with mock.patch("pydap.client.open_url") as mock_func:
xr.backends.PydapDataStore.open("http://test.url", session=session)
mock_func.assert_called_with("http://test.url", session=session)
@requires_scipy
@requires_pynio
class TestPyNio... | 88 | 88 | 295 | 23 | 65 | qwhelan/xarray | xarray/tests/test_backends.py | Python | TestPyNio | TestPyNio | 3,206 | 3,236 | 3,206 | 3,208 | 19f808e690ca7ed693b9469d35a960164e613765 | bigcode/the-stack | train |
22aacfc0befc5b2524a3de4d | train | function | def open_example_dataset(name, *args, **kwargs):
return open_dataset(
os.path.join(os.path.dirname(__file__), "data", name), *args, **kwargs
)
| def open_example_dataset(name, *args, **kwargs):
| return open_dataset(
os.path.join(os.path.dirname(__file__), "data", name), *args, **kwargs
)
| _test_data, create_test_data
try:
import netCDF4 as nc4
except ImportError:
pass
try:
import dask.array as da
except ImportError:
pass
ON_WINDOWS = sys.platform == "win32"
def open_example_dataset(name, *args, **kwargs):
| 64 | 64 | 40 | 12 | 52 | qwhelan/xarray | xarray/tests/test_backends.py | Python | open_example_dataset | open_example_dataset | 85 | 88 | 85 | 85 | 72aeeb987353eeecd8c599e9b42fe7c59a939d02 | bigcode/the-stack | train |
fd1e49a4fbcd8c3307d579a2 | train | class | @requires_zarr
class TestZarrDirectoryStore(ZarrBase):
@contextlib.contextmanager
def create_zarr_target(self):
with create_tmp_file(suffix=".zarr") as tmp:
yield tmp
| @requires_zarr
class TestZarrDirectoryStore(ZarrBase):
@contextlib.contextmanager
| def create_zarr_target(self):
with create_tmp_file(suffix=".zarr") as tmp:
yield tmp
| , original.isel(t=0))
@requires_zarr
class TestZarrDictStore(ZarrBase):
@contextlib.contextmanager
def create_zarr_target(self):
yield {}
@requires_zarr
class TestZarrDirectoryStore(ZarrBase):
@contextlib.contextmanager
| 63 | 64 | 48 | 22 | 41 | qwhelan/xarray | xarray/tests/test_backends.py | Python | TestZarrDirectoryStore | TestZarrDirectoryStore | 1,920 | 1,925 | 1,920 | 1,922 | 40031f0452a5e7794f36914606e9088d9c6938b0 | bigcode/the-stack | train |
55163c5a4e314a85481a38fa | train | function | @pytest.fixture(params=[None, 5])
def chunks(request):
return request.param
| @pytest.fixture(params=[None, 5])
def chunks(request):
| return request.param
| .param
if maxsize is not None:
with set_options(file_cache_maxsize=maxsize):
yield maxsize
else:
yield maxsize
@pytest.fixture(params=[True, False])
def parallel(request):
return request.param
@pytest.fixture(params=[None, 5])
def chunks(request):
| 64 | 64 | 18 | 13 | 50 | qwhelan/xarray | xarray/tests/test_backends.py | Python | chunks | chunks | 2,427 | 2,429 | 2,427 | 2,428 | 19ec5cb3dec3c103c2747beaad5236861f973ccb | bigcode/the-stack | train |
1a5c12e8c7681626dabd17c9 | train | class | @requires_netCDF4
class TestValidateAttrs:
def test_validating_attrs(self):
def new_dataset():
return Dataset({"data": ("y", np.arange(10.0))}, {"y": np.arange(10)})
def new_dataset_and_dataset_attrs():
ds = new_dataset()
return ds, ds.attrs
def new_data... | @requires_netCDF4
class TestValidateAttrs:
| def test_validating_attrs(self):
def new_dataset():
return Dataset({"data": ("y", np.arange(10.0))}, {"y": np.arange(10)})
def new_dataset_and_dataset_attrs():
ds = new_dataset()
return ds, ds.attrs
def new_dataset_and_data_attrs():
ds = new_... | regression test
var = xr.Variable(("x",), [1, 2, 3], {}, {"shuffle": True})
encoding = _extract_nc4_variable_encoding(var, raise_on_invalid=True)
assert {"shuffle": True} == encoding
# Variables with unlim dims must be chunked on output.
var = xr.Variable(("x",), [1, 2, 3], {},... | 208 | 208 | 695 | 11 | 196 | qwhelan/xarray | xarray/tests/test_backends.py | Python | TestValidateAttrs | TestValidateAttrs | 4,065 | 4,153 | 4,065 | 4,066 | c788fd60bc518ccb087dbd4e3899620870b0c5e7 | bigcode/the-stack | train |
51cb167b553f356a839ab203 | train | class | @requires_netCDF4
class TestNetCDF4ClassicViaNetCDF4Data(CFEncodedBase, NetCDF3Only):
engine = "netcdf4"
file_format = "NETCDF4_CLASSIC"
@contextlib.contextmanager
def create_store(self):
with create_tmp_file() as tmp_file:
with backends.NetCDF4DataStore.open(
tmp_fi... | @requires_netCDF4
class TestNetCDF4ClassicViaNetCDF4Data(CFEncodedBase, NetCDF3Only):
| engine = "netcdf4"
file_format = "NETCDF4_CLASSIC"
@contextlib.contextmanager
def create_store(self):
with create_tmp_file() as tmp_file:
with backends.NetCDF4DataStore.open(
tmp_file, mode="w", format="NETCDF4_CLASSIC"
) as store:
yield s... | x": {"dtype": str}})
with raises_regex(ValueError, "encoding dtype=str for vlen"):
with self.roundtrip(original, save_kwargs=kwargs):
pass
@requires_netCDF4
class TestNetCDF4ClassicViaNetCDF4Data(CFEncodedBase, NetCDF3Only):
| 64 | 64 | 105 | 27 | 36 | qwhelan/xarray | xarray/tests/test_backends.py | Python | TestNetCDF4ClassicViaNetCDF4Data | TestNetCDF4ClassicViaNetCDF4Data | 2,056 | 2,067 | 2,056 | 2,057 | 3a3064fad03e95060aa9c0e039c47aa159c9a645 | bigcode/the-stack | train |
9e24ad30bd8a28d81c55e0b9 | train | class | @requires_scipy_or_netCDF4
@requires_dask
class TestOpenMFDataSetDeprecation:
"""
Set of tests to check that FutureWarnings are correctly raised until the
deprecation cycle is complete. #2616
"""
def test_open_mfdataset_default(self):
ds1, ds2 = Dataset({"x": [0]}), Dataset({"x": [1]})
... | @requires_scipy_or_netCDF4
@requires_dask
class TestOpenMFDataSetDeprecation:
| """
Set of tests to check that FutureWarnings are correctly raised until the
deprecation cycle is complete. #2616
"""
def test_open_mfdataset_default(self):
ds1, ds2 = Dataset({"x": [0]}), Dataset({"x": [1]})
with create_tmp_file() as tmp1:
with create_tmp_file() as tmp2... | combine="nested", concat_dim="x"
) as actual:
assert_identical(actual, original)
def test_load_dataset(self):
with create_tmp_file() as tmp:
original = Dataset({"foo": ("x", np.random.randn(10))})
original.to_netcdf(tmp)
ds = load_dat... | 196 | 196 | 655 | 25 | 171 | qwhelan/xarray | xarray/tests/test_backends.py | Python | TestOpenMFDataSetDeprecation | TestOpenMFDataSetDeprecation | 3,038 | 3,102 | 3,038 | 3,040 | 3322affd78eea1b59f637af93a2329123a682b65 | bigcode/the-stack | train |
fd7b7a6ccd8bd15c10692f36 | train | class | @requires_scipy_or_netCDF4
@requires_dask
class TestOpenMFDatasetWithDataVarsAndCoordsKw:
coord_name = "lon"
var_name = "v1"
@contextlib.contextmanager
def setup_files_and_datasets(self, fuzz=0):
ds1, ds2 = self.gen_datasets_with_common_coord_and_time()
# to test join='exact'
d... | @requires_scipy_or_netCDF4
@requires_dask
class TestOpenMFDatasetWithDataVarsAndCoordsKw:
| coord_name = "lon"
var_name = "v1"
@contextlib.contextmanager
def setup_files_and_datasets(self, fuzz=0):
ds1, ds2 = self.gen_datasets_with_common_coord_and_time()
# to test join='exact'
ds1["x"] = ds1.x + fuzz
with create_tmp_file() as tmpfile1:
with creat... | actual)
@requires_netCDF4
def test_open_mfdataset_list_attr():
"""
Case when an attribute of type list differs across the multiple files
"""
from netCDF4 import Dataset
with create_tmp_files(2) as nfiles:
for i in range(2):
f = Dataset(nfiles[i], "w")
f.createDime... | 256 | 256 | 1,074 | 28 | 228 | qwhelan/xarray | xarray/tests/test_backends.py | Python | TestOpenMFDatasetWithDataVarsAndCoordsKw | TestOpenMFDatasetWithDataVarsAndCoordsKw | 2,505 | 2,622 | 2,505 | 2,507 | e529924ee9d67418b4d8c63e650ec8e3906a64ee | bigcode/the-stack | train |
d706c62d5f986f3bad75fe59 | train | class | @requires_cfgrib
class TestCfGrib:
def test_read(self):
expected = {
"number": 2,
"time": 3,
"isobaricInhPa": 2,
"latitude": 3,
"longitude": 4,
}
with open_example_dataset("example.grib", engine="cfgrib") as ds:
assert d... | @requires_cfgrib
class TestCfGrib:
| def test_read(self):
expected = {
"number": 2,
"time": 3,
"isobaricInhPa": 2,
"latitude": 3,
"longitude": 4,
}
with open_example_dataset("example.grib", engine="cfgrib") as ds:
assert ds.dims == expected
asse... | .to_netcdf(tmp_file, engine="scipy")
on_disk = open_dataset(tmp_file, engine="pynio")
actual = on_disk.rename({"foo": "bar", "x": "y"})
del on_disk # trigger garbage collection
assert_identical(actual, expected)
@requires_cfgrib
class TestCfGrib:
| 75 | 75 | 252 | 12 | 63 | qwhelan/xarray | xarray/tests/test_backends.py | Python | TestCfGrib | TestCfGrib | 3,239 | 3,268 | 3,239 | 3,240 | 3483c789954bad3cd9aabc40b7dca07a7932f169 | bigcode/the-stack | train |
2ca298e12b1d1cad924860d9 | train | function | def skip_if_not_engine(engine):
if engine == "netcdf4":
pytest.importorskip("netCDF4")
elif engine == "pynio":
pytest.importorskip("Nio")
else:
pytest.importorskip(engine)
| def skip_if_not_engine(engine):
| if engine == "netcdf4":
pytest.importorskip("netCDF4")
elif engine == "pynio":
pytest.importorskip("Nio")
else:
pytest.importorskip(engine)
| else:
yield maxsize
@pytest.fixture(params=[True, False])
def parallel(request):
return request.param
@pytest.fixture(params=[None, 5])
def chunks(request):
return request.param
# using pytest.mark.skipif does not work so this a work around
def skip_if_not_engine(engine):
| 64 | 64 | 54 | 7 | 56 | qwhelan/xarray | xarray/tests/test_backends.py | Python | skip_if_not_engine | skip_if_not_engine | 2,433 | 2,439 | 2,433 | 2,433 | b45e993367cb81b0ff90a87d35a1092edf818c3a | bigcode/the-stack | train |
07d3299df6fe5f98e737885c | train | class | class CFEncodedBase(DatasetIOBase):
def test_roundtrip_bytes_with_fill_value(self):
values = np.array([b"ab", b"cdef", np.nan], dtype=object)
encoding = {"_FillValue": b"X", "dtype": "S1"}
original = Dataset({"x": ("t", values, {}, encoding)})
expected = original.copy(deep=True)
... | class CFEncodedBase(DatasetIOBase):
| def test_roundtrip_bytes_with_fill_value(self):
values = np.array([b"ab", b"cdef", np.nan], dtype=object)
encoding = {"_FillValue": b"X", "dtype": "S1"}
original = Dataset({"x": ("t", values, {}, encoding)})
expected = original.copy(deep=True)
with self.roundtrip(original) as... | = on_disk.isel(**indexers)
assert_identical(expected, actual)
self.validate_array_type(actual)
def test_dropna(self):
# regression test for GH:issue:1694
a = np.random.randn(4, 3)
a[1, 1] = np.NaN
in_memory = xr.Dataset(
{"a": (("y", "x"), a)}, c... | 256 | 256 | 2,738 | 9 | 246 | qwhelan/xarray | xarray/tests/test_backends.py | Python | CFEncodedBase | CFEncodedBase | 711 | 980 | 711 | 711 | b006451179c41b08acb290c28fd485c8f2dae55d | bigcode/the-stack | train |
e27bb9ecf8f854e65717962f | train | function | def make_circuit(n:int,f) -> QuantumCircuit:
# circuit begin
input_qubit = QuantumRegister(n,"qc")
classical = ClassicalRegister(n, "qm")
prog = QuantumCircuit(input_qubit, classical)
prog.h(input_qubit[0]) # number=3
prog.h(input_qubit[1]) # number=4
prog.h(input_qubit[2]) # number=5
pr... | def make_circuit(n:int,f) -> QuantumCircuit:
# circuit begin
| input_qubit = QuantumRegister(n,"qc")
classical = ClassicalRegister(n, "qm")
prog = QuantumCircuit(input_qubit, classical)
prog.h(input_qubit[0]) # number=3
prog.h(input_qubit[1]) # number=4
prog.h(input_qubit[2]) # number=5
prog.h(input_qubit[3]) # number=6
prog.h(input_qubit[4]) # num... | numpy as np
import networkx as nx
def build_oracle(n: int, f) -> QuantumCircuit:
# implement the oracle O_f^\pm
# NOTE: use U1 gate (P gate) with \lambda = 180 ==> CZ gate
# or multi_control_Z_gate (issue #127)
controls = QuantumRegister(n, "ofc")
oracle = QuantumCircuit(controls, name="Zf")
... | 224 | 224 | 748 | 17 | 206 | UCLA-SEAL/QDiff | benchmark/startQiskit_QC894.py | Python | make_circuit | make_circuit | 43 | 110 | 43 | 44 | f2ff10d6d00c966c7b34c3d6199bbbd500c8d544 | bigcode/the-stack | train |
a145f2fb5454231470efedf0 | train | function | def build_oracle(n: int, f) -> QuantumCircuit:
# implement the oracle O_f^\pm
# NOTE: use U1 gate (P gate) with \lambda = 180 ==> CZ gate
# or multi_control_Z_gate (issue #127)
controls = QuantumRegister(n, "ofc")
oracle = QuantumCircuit(controls, name="Zf")
for i in range(2 ** n):
rep... | def build_oracle(n: int, f) -> QuantumCircuit:
# implement the oracle O_f^\pm
# NOTE: use U1 gate (P gate) with \lambda = 180 ==> CZ gate
# or multi_control_Z_gate (issue #127)
| controls = QuantumRegister(n, "ofc")
oracle = QuantumCircuit(controls, name="Zf")
for i in range(2 ** n):
rep = np.binary_repr(i, n)
if f(rep) == "1":
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
# oracle.h(controls[... | import networkx as nx
def build_oracle(n: int, f) -> QuantumCircuit:
# implement the oracle O_f^\pm
# NOTE: use U1 gate (P gate) with \lambda = 180 ==> CZ gate
# or multi_control_Z_gate (issue #127)
| 64 | 64 | 197 | 58 | 5 | UCLA-SEAL/QDiff | benchmark/startQiskit_QC894.py | Python | build_oracle | build_oracle | 16 | 40 | 16 | 20 | 65ce9f82635737bf77eda8c5c06726774c01313a | bigcode/the-stack | train |
45afc5185d6414531ac2cb16 | train | class | class OsmxmlTest(unittest.TestCase):
def test_serialize(self):
data = osm.Osm()
n = data.Node(4,0)
n.tags['entrance'] = 'yes'
n.tags['addr:street'] = "Calle la Ñ"
n.tags['addr:housenumber'] = '7'
w = data.Way([(12,0), (14,0), (14,2), (12,2), (12,0)])
w.tags['... | class OsmxmlTest(unittest.TestCase):
| def test_serialize(self):
data = osm.Osm()
n = data.Node(4,0)
n.tags['entrance'] = 'yes'
n.tags['addr:street'] = "Calle la Ñ"
n.tags['addr:housenumber'] = '7'
w = data.Way([(12,0), (14,0), (14,2), (12,2), (12,0)])
w.tags['leisure'] = 'swiming_pool'
r =... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from future import standard_library
standard_library.install_aliases()
from builtins import bytes, str
import unittest
from io import StringIO, BytesIO
from catatom2osm import osm, osmxml
from catatom2osm.osmxml import etree
class OsmxmlTest(unittest.Test... | 78 | 256 | 2,254 | 8 | 69 | OSM-es/CatAtom2Osm | test/test_osmxml.py | Python | OsmxmlTest | OsmxmlTest | 13 | 171 | 13 | 14 | 9498ead3a53516539bbdef475309283766387bde | bigcode/the-stack | train |
192afec2cd36fd2c5f30265d | train | class | class asset_metadata_receiver(trigger_receiver):
__db = None
__asset = ''
__source = None
__target_hash = ''
__payload_bytes = b''
@classmethod
def initialise (cls, db):
with db:
cursor = db.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS asset_metadata... | class asset_metadata_receiver(trigger_receiver):
| __db = None
__asset = ''
__source = None
__target_hash = ''
__payload_bytes = b''
@classmethod
def initialise (cls, db):
with db:
cursor = db.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS asset_metadatas(
tx_index INTEGER PRIMA... | """ 'trigger module' for asset_metadata """
import bson
import struct
import marshal
import logging
logger = logging.getLogger(__name__)
from counterpartylib.lib.messages import (issuance)
from counterpartylib.lib.messages.triggers import (trigger_receiver)
FORMAT = '>B'
LENGTH = 1
TYPE_STORE = 1
TYPE_LOCK ... | 99 | 256 | 1,216 | 7 | 91 | monaparty/counterparty-lib | counterpartylib/lib/messages/triggers/asset_metadata.py | Python | asset_metadata_receiver | asset_metadata_receiver | 19 | 180 | 19 | 19 | acf2b6b89863aac944b2aa276e2414c4f0736b52 | bigcode/the-stack | train |
59a7ca2ce051f7fca3e14cab | train | class | class TestRequest(TestUsingServer):
@pytest.mark.xfail(sys.version_info >= (3,), reason="wptserve only works on Py2")
def test_body(self):
@wptserve.handlers.handler
def handler(request, response):
request.raw_input.seek(5)
return request.body
route = ("POST", "/... | class TestRequest(TestUsingServer):
@pytest.mark.xfail(sys.version_info >= (3,), reason="wptserve only works on Py2")
| def test_body(self):
@wptserve.handlers.handler
def handler(request, response):
request.raw_input.seek(5)
return request.body
route = ("POST", "/test/test_body", handler)
self.server.router.register(*route)
resp = self.request(route[1], method="POST",... | self.assertEqual(["12345\n", "abcdef\r\n", "zyxwv"], resp.read().split(" "))
finally:
InputFile.max_buffer_size = old_max_buf
class TestRequest(TestUsingServer):
@pytest.mark.xfail(sys.version_info >= (3,), reason="wptserve only works on Py2")
| 69 | 69 | 231 | 31 | 37 | mtrzos/wpt | tools/wptserve/tests/functional/test_request.py | Python | TestRequest | TestRequest | 100 | 122 | 100 | 101 | 0767d448fccd50aecbfaee040f3de70ea0204129 | bigcode/the-stack | train |
a9dc6133445755b83ef021e4 | train | class | class TestInputFile(TestUsingServer):
@pytest.mark.xfail(sys.version_info >= (3,), reason="wptserve only works on Py2")
def test_seek(self):
@wptserve.handlers.handler
def handler(request, response):
rv = []
f = request.raw_input
f.seek(5)
rv.appen... | class TestInputFile(TestUsingServer):
@pytest.mark.xfail(sys.version_info >= (3,), reason="wptserve only works on Py2")
| def test_seek(self):
@wptserve.handlers.handler
def handler(request, response):
rv = []
f = request.raw_input
f.seek(5)
rv.append(f.read(2))
rv.append(f.tell())
f.seek(0)
rv.append(f.readline())
rv.append... | import sys
import pytest
wptserve = pytest.importorskip("wptserve")
from .base import TestUsingServer
from wptserve.request import InputFile
class TestInputFile(TestUsingServer):
@pytest.mark.xfail(sys.version_info >= (3,), reason="wptserve only works on Py2")
| 68 | 245 | 818 | 32 | 35 | mtrzos/wpt | tools/wptserve/tests/functional/test_request.py | Python | TestInputFile | TestInputFile | 10 | 97 | 10 | 11 | b9e1c221a292c83469e2bb8978295282ac38447a | bigcode/the-stack | train |
c7c531ff9038f23689c9600f | train | class | class TestAuth(TestUsingServer):
@pytest.mark.xfail(sys.version_info >= (3,), reason="wptserve only works on Py2")
def test_auth(self):
@wptserve.handlers.handler
def handler(request, response):
return " ".join((request.auth.username, request.auth.password))
route = ("GET", ... | class TestAuth(TestUsingServer):
@pytest.mark.xfail(sys.version_info >= (3,), reason="wptserve only works on Py2")
| def test_auth(self):
@wptserve.handlers.handler
def handler(request, response):
return " ".join((request.auth.username, request.auth.password))
route = ("GET", "/test/test_auth", handler)
self.server.router.register(*route)
resp = self.request(route[1], auth=("te... | *", handler)
self.server.router.register(*route)
resp = self.request("/test/some_route")
self.assertEqual("some route", resp.read())
class TestAuth(TestUsingServer):
@pytest.mark.xfail(sys.version_info >= (3,), reason="wptserve only works on Py2")
| 64 | 64 | 130 | 31 | 33 | mtrzos/wpt | tools/wptserve/tests/functional/test_request.py | Python | TestAuth | TestAuth | 125 | 136 | 125 | 126 | 557e95991c49f59de48036d3138176a47b769314 | bigcode/the-stack | train |
47df0894eab3636391984504 | train | class | class TLSFeaturesExtnTestCase(unittest.TestCase):
pem_text = """\
MIIEbTCCBBOgAwIBAgIRAO5f2N8q74GBATjTMXQCjlgwCgYIKoZIzj0EAwIwgZYx
CzAJBgNVBAYTAkdCMRswGQYDVQQIExJHcmVhdGVyIE1hbmNoZXN0ZXIxEDAOBgNV
BAcTB1NhbGZvcmQxGjAYBgNVBAoTEUNPTU9ETyBDQSBMaW1pdGVkMTwwOgYDVQQD
EzNDT01PRE8gRUNDIE9yZ2FuaXphdGlvbiBWYWxpZGF0aW9uIFNlY3V... | class TLSFeaturesExtnTestCase(unittest.TestCase):
| pem_text = """\
MIIEbTCCBBOgAwIBAgIRAO5f2N8q74GBATjTMXQCjlgwCgYIKoZIzj0EAwIwgZYx
CzAJBgNVBAYTAkdCMRswGQYDVQQIExJHcmVhdGVyIE1hbmNoZXN0ZXIxEDAOBgNV
BAcTB1NhbGZvcmQxGjAYBgNVBAoTEUNPTU9ETyBDQSBMaW1pdGVkMTwwOgYDVQQD
EzNDT01PRE8gRUNDIE9yZ2FuaXphdGlvbiBWYWxpZGF0aW9uIFNlY3VyZSBTZXJ2
ZXIgQ0EwHhcNMTYwMTE1MDAwMDAwWhcNMTgwMTE0... | #
# This file is part of pyasn1-modules software.
#
# Created by Russ Housley
# Copyright (c) 2019, Vigil Security, LLC
# License: http://snmplabs.com/pyasn1/license.html
#
import sys
from pyasn1.codec.der.decoder import decode as der_decode
from pyasn1.codec.der.encoder import encode as der_encode
from pyasn1_modul... | 141 | 256 | 1,261 | 11 | 129 | Jamim/pyasn1-modules | tests/test_rfc7633.py | Python | TLSFeaturesExtnTestCase | TLSFeaturesExtnTestCase | 25 | 77 | 25 | 25 | b8e970c3db2a424656c920691d4da6557e502902 | bigcode/the-stack | train |
917679cf6010b97257c4f695 | train | function | @cli.command()
@click.option('-o', '--output', type=click.File(mode='wb'), required=False, default=sys.stdout, show_default=True, help="Write the Document Body to file")
@click.pass_context
def recvdoc(ctx, output):
"""
Receive Document from other HealthCare Provider.
"""
data = call_api(ctx.obj['base']... | @cli.command()
@click.option('-o', '--output', type=click.File(mode='wb'), required=False, default=sys.stdout, show_default=True, help="Write the Document Body to file")
@click.pass_context
def recvdoc(ctx, output):
| """
Receive Document from other HealthCare Provider.
"""
data = call_api(ctx.obj['base'] + '/msgstore/download', auth=(ctx.obj['user'], ctx.obj['password']), accept_codes=(404, ))
if data:
output.write(data)
| (data), indent=4))
else:
print(data)
@cli.command()
@click.option('-o', '--output', type=click.File(mode='wb'), required=False, default=sys.stdout, show_default=True, help="Write the Document Body to file")
@click.pass_context
def recvdoc(ctx, output):
| 64 | 64 | 107 | 51 | 13 | jraska1/py-isac | py-isac.py | Python | recvdoc | recvdoc | 255 | 264 | 255 | 258 | f11d66e45f8eb579115e57a6216ccc51f103390d | bigcode/the-stack | train |
f795bd721e7dbce4cba945ca | train | function | def call_api(url, *, params=None, json=None, headers=None, auth=(), accept_codes=()):
try:
resp = requests.post(url, data=params, json=json, headers=headers, auth=auth)
if resp.status_code in accept_codes:
return None
resp.raise_for_status()
return resp.text
except re... | def call_api(url, *, params=None, json=None, headers=None, auth=(), accept_codes=()):
| try:
resp = requests.post(url, data=params, json=json, headers=headers, auth=auth)
if resp.status_code in accept_codes:
return None
resp.raise_for_status()
return resp.text
except requests.exceptions.RequestException as e:
print(f"Connection error: {e}", file=... | re.match(r'^\d{4}-\d{2}-\d{2}$', value):
raise click.BadParameter('date parameter should be in format YYYY-MM-DD')
return value
def call_api(url, *, params=None, json=None, headers=None, auth=(), accept_codes=()):
| 64 | 64 | 98 | 22 | 41 | jraska1/py-isac | py-isac.py | Python | call_api | call_api | 46 | 55 | 46 | 46 | 1a5ffde2760b0ff738e5feb5621dbc401d6c8686 | bigcode/the-stack | train |
f09a9e2ac719fbcaeef79e18 | train | function | @cli.command()
@click.pass_context
def prodsys(ctx):
"""
Production system detail information.
"""
params = {
'username': ctx.obj['username'],
}
data = call_api(ctx.obj['base'] + '/prodsystem/get.json', params=params, auth=(ctx.obj['user'], ctx.obj['password']))
if ctx.obj['pretty']:... | @cli.command()
@click.pass_context
def prodsys(ctx):
| """
Production system detail information.
"""
params = {
'username': ctx.obj['username'],
}
data = call_api(ctx.obj['base'] + '/prodsystem/get.json', params=params, auth=(ctx.obj['user'], ctx.obj['password']))
if ctx.obj['pretty']:
print(json.dumps(json.loads(data), indent=4)... | base'] + '/confedit/provider.json', params=params, auth=(ctx.obj['user'], ctx.obj['password']))
if ctx.obj['pretty']:
print(json.dumps(json.loads(data), indent=4))
else:
print(data)
@cli.command()
@click.pass_context
def prodsys(ctx):
| 64 | 64 | 98 | 14 | 50 | jraska1/py-isac | py-isac.py | Python | prodsys | prodsys | 122 | 135 | 122 | 124 | 399a6c1fb5608a7cc23d821267d900fb5e703082 | bigcode/the-stack | train |
c68d5fe77f701e7c9db82bf3 | train | function | @cli.command()
@click.pass_context
def bedfund(ctx):
"""
Bed Fund Survey Client.
"""
params = {
'username': ctx.obj['username'],
}
data = call_api(ctx.obj['base'] + '/beds.json', params=params, auth=(ctx.obj['user'], ctx.obj['password']))
if ctx.obj['pretty']:
print(json.dump... | @cli.command()
@click.pass_context
def bedfund(ctx):
| """
Bed Fund Survey Client.
"""
params = {
'username': ctx.obj['username'],
}
data = call_api(ctx.obj['base'] + '/beds.json', params=params, auth=(ctx.obj['user'], ctx.obj['password']))
if ctx.obj['pretty']:
print(json.dumps(json.loads(data), indent=4))
else:
prin... | from other HealthCare Provider.
"""
data = call_api(ctx.obj['base'] + '/msgstore/download', auth=(ctx.obj['user'], ctx.obj['password']), accept_codes=(404, ))
if data:
output.write(data)
@cli.command()
@click.pass_context
def bedfund(ctx):
| 64 | 64 | 94 | 13 | 51 | jraska1/py-isac | py-isac.py | Python | bedfund | bedfund | 267 | 280 | 267 | 269 | db73bcf9f1925663fb25531c3b04f749a77bce2a | bigcode/the-stack | train |
24fb16e6426bca0c2ec09d89 | train | function | @cli.command()
@click.option('--provoid', type=str, required=True, help="HealthCare Provider OID")
@click.option('--eventid', type=str, required=True, help="Clinical Event ID")
@click.pass_context
def docview(ctx, provoid, eventid):
"""
Patient Clinical Event Documentation View Client.
"""
params = {
... | @cli.command()
@click.option('--provoid', type=str, required=True, help="HealthCare Provider OID")
@click.option('--eventid', type=str, required=True, help="Clinical Event ID")
@click.pass_context
def docview(ctx, provoid, eventid):
| """
Patient Clinical Event Documentation View Client.
"""
params = {
'icz': provoid,
'eventId': eventid,
'username': ctx.obj['username'],
}
data = call_api(ctx.obj['base'] + '/DocumentView.json', params=params, auth=(ctx.obj['user'], ctx.obj['password']))
if ctx.obj['... | else:
print(data)
@cli.command()
@click.option('--provoid', type=str, required=True, help="HealthCare Provider OID")
@click.option('--eventid', type=str, required=True, help="Clinical Event ID")
@click.pass_context
def docview(ctx, provoid, eventid):
| 64 | 64 | 156 | 57 | 7 | jraska1/py-isac | py-isac.py | Python | docview | docview | 160 | 177 | 160 | 164 | c7288a7a5119b229e21a64134bcfff17fb898b18 | bigcode/the-stack | train |
8616af2c39fe77a1b5b31cef | train | function | @cli.command()
@click.option('--patoid', type=str, required=False, help="Patient OID")
@click.option('--orgoid', type=str, required=True, help="HealthCare Provider OID")
@click.option('--docoid', type=str, required=True, help="Document OID")
@click.option('--bodytype', type=str, required=False, default="text/plain", sh... | @cli.command()
@click.option('--patoid', type=str, required=False, help="Patient OID")
@click.option('--orgoid', type=str, required=True, help="HealthCare Provider OID")
@click.option('--docoid', type=str, required=True, help="Document OID")
@click.option('--bodytype', type=str, required=False, default="text/plain", sh... | """
Patient Documentation Handover Client.
"""
params = {
'patoid': patoid,
'orgoid': orgoid,
'docoid': docoid,
'bodytype': bodytype,
'username': ctx.obj['username'],
}
data = call_api(ctx.obj['base'] + '/handover.json', json=params, auth=(ctx.obj['user'],... | @cli.command()
@click.option('--patoid', type=str, required=False, help="Patient OID")
@click.option('--orgoid', type=str, required=True, help="HealthCare Provider OID")
@click.option('--docoid', type=str, required=True, help="Document OID")
@click.option('--bodytype', type=str, required=False, default="text/plain", sh... | 143 | 91 | 304 | 143 | 0 | jraska1/py-isac | py-isac.py | Python | handover | handover | 204 | 233 | 204 | 211 | 510a81aaad3e6118a77081bc0af60973b78b372e | bigcode/the-stack | train |
d6a089ab8300ceea28abf1e1 | train | function | @cli.command()
@click.pass_context
def provider(ctx):
"""
HealthCare Provider detail information as a source for editing.
"""
params = {
'username': ctx.obj['username'],
}
data = call_api(ctx.obj['base'] + '/confedit/provider.json', params=params, auth=(ctx.obj['user'], ctx.obj['password... | @cli.command()
@click.pass_context
def provider(ctx):
| """
HealthCare Provider detail information as a source for editing.
"""
params = {
'username': ctx.obj['username'],
}
data = call_api(ctx.obj['base'] + '/confedit/provider.json', params=params, auth=(ctx.obj['user'], ctx.obj['password']))
if ctx.obj['pretty']:
print(json.dump... | (ctx.obj['base'] + '/nodestatus.json', params=params, auth=(ctx.obj['user'], ctx.obj['password']))
if ctx.obj['pretty']:
print(json.dumps(json.loads(data), indent=4))
else:
print(data)
@cli.command()
@click.pass_context
def provider(ctx):
| 64 | 64 | 101 | 12 | 52 | jraska1/py-isac | py-isac.py | Python | provider | provider | 106 | 119 | 106 | 108 | 19026c812ef102f47c102a9c4ad705d3f25aa369 | bigcode/the-stack | train |
01271519e2a98c07b78c1503 | train | function | @cli.command()
@click.option('--rc', type=str, required=True, help="Patient ID - rodne cislo")
@click.option('--lastname', type=str, help="Patient Surname")
@click.option('--from', 'fromdate', type=str, default='2000-01-01', show_default=True, callback=validate_date, help="Start date for searching documents")
@click.op... | @cli.command()
@click.option('--rc', type=str, required=True, help="Patient ID - rodne cislo")
@click.option('--lastname', type=str, help="Patient Surname")
@click.option('--from', 'fromdate', type=str, default='2000-01-01', show_default=True, callback=validate_date, help="Start date for searching documents")
@click.op... | """
Patient Documentation Survey Client.
"""
params = {
'rc': rc,
'lastname': lastname,
'from': fromdate,
'to': todate,
'username': ctx.obj['username'],
}
data = call_api(ctx.obj['base'] + '/survey.json', json=params, auth=(ctx.obj['user'], ctx.obj['passwo... | @cli.command()
@click.option('--rc', type=str, required=True, help="Patient ID - rodne cislo")
@click.option('--lastname', type=str, help="Patient Surname")
@click.option('--from', 'fromdate', type=str, default='2000-01-01', show_default=True, callback=validate_date, help="Start date for searching documents")
@click.op... | 120 | 68 | 227 | 120 | 0 | jraska1/py-isac | py-isac.py | Python | survey | survey | 180 | 201 | 180 | 186 | 72252cb9736ba25597db29e54dc0b130ff9f242d | bigcode/the-stack | train |
9af01b2ca7e52669b6d18f96 | train | function | @cli.command()
@click.option('--contype', type=str, required=False, default="application/xml", show_default=True, help="Document Content Type")
@click.option('-i', '--input', 'inputFile', type=click.File(mode='rb'), required=False, help="Read the Document Body from file")
@click.pass_context
def senddoc(ctx, contype, i... | @cli.command()
@click.option('--contype', type=str, required=False, default="application/xml", show_default=True, help="Document Content Type")
@click.option('-i', '--input', 'inputFile', type=click.File(mode='rb'), required=False, help="Read the Document Body from file")
@click.pass_context
def senddoc(ctx, contype, i... | """
Send Document to other HealthCare Provider.
"""
params = inputFile.read()
headers = {
'Content-Type': contype,
}
data = call_api(ctx.obj['base'] + '/msgstore/senddoc.json', params=params, headers=headers, auth=(ctx.obj['user'], ctx.obj['password']))
if ctx.obj['pretty']:
... | @cli.command()
@click.option('--contype', type=str, required=False, default="application/xml", show_default=True, help="Document Content Type")
@click.option('-i', '--input', 'inputFile', type=click.File(mode='rb'), required=False, help="Read the Document Body from file")
@click.pass_context
def senddoc(ctx, contype, i... | 78 | 64 | 174 | 78 | 0 | jraska1/py-isac | py-isac.py | Python | senddoc | senddoc | 236 | 252 | 236 | 240 | 436714f2e7ddbf6b86b84501b507cbf7439504ba | bigcode/the-stack | train |
3a2960497258613ae755113f | train | function | def validate_date(ctx, param, value):
if value and not re.match(r'^\d{4}-\d{2}-\d{2}$', value):
raise click.BadParameter('date parameter should be in format YYYY-MM-DD')
return value
| def validate_date(ctx, param, value):
| if value and not re.match(r'^\d{4}-\d{2}-\d{2}$', value):
raise click.BadParameter('date parameter should be in format YYYY-MM-DD')
return value
| tools are intended for testing purposes only.
"""
ctx.ensure_object(dict)
ctx.obj.update({
'base': base.rstrip('/'),
'user': user,
'password': password,
'username': username,
'pretty': pretty,
})
def validate_date(ctx, param, value):
| 64 | 64 | 56 | 9 | 55 | jraska1/py-isac | py-isac.py | Python | validate_date | validate_date | 40 | 43 | 40 | 40 | 57c8a7c789533086ff6ef401a2ccc9a64a6225a9 | bigcode/the-stack | train |
d757a865d9fd5e657eaae829 | train | function | @click.group(context_settings=CONTEXT_SETTINGS)
@click.option('-b', '--base', type=str, default=URL_BASE, show_default=True, help="Service Base URL")
@click.option('-u', '--user', type=str, default='amis', show_default=True, help="User login")
@click.option('-p', '--password', default='amis', show_default=True, type=st... | @click.group(context_settings=CONTEXT_SETTINGS)
@click.option('-b', '--base', type=str, default=URL_BASE, show_default=True, help="Service Base URL")
@click.option('-u', '--user', type=str, default='amis', show_default=True, help="User login")
@click.option('-p', '--password', default='amis', show_default=True, type=st... | """
ICZ ISAC Client - tools for calling services through the REST API.
This tools are intended for testing purposes only.
"""
ctx.ensure_object(dict)
ctx.obj.update({
'base': base.rstrip('/'),
'user': user,
'password': password,
'username': username,
'pr... | @click.group(context_settings=CONTEXT_SETTINGS)
@click.option('-b', '--base', type=str, default=URL_BASE, show_default=True, help="Service Base URL")
@click.option('-u', '--user', type=str, default='amis', show_default=True, help="User login")
@click.option('-p', '--password', default='amis', show_default=True, type=st... | 143 | 65 | 218 | 143 | 0 | jraska1/py-isac | py-isac.py | Python | cli | cli | 16 | 37 | 16 | 23 | 7bc4fe1e5b353ad5ad8720695dc77b72011b977f | bigcode/the-stack | train |
139db5c895c9e26ac6f10a9d | train | function | @cli.command()
@click.pass_context
def status(ctx):
"""
Communication Node Status information.
"""
params = {
'username': ctx.obj['username'],
}
data = call_api(ctx.obj['base'] + '/nodestatus.json', params=params, auth=(ctx.obj['user'], ctx.obj['password']))
if ctx.obj['pretty']:
... | @cli.command()
@click.pass_context
def status(ctx):
| """
Communication Node Status information.
"""
params = {
'username': ctx.obj['username'],
}
data = call_api(ctx.obj['base'] + '/nodestatus.json', params=params, auth=(ctx.obj['user'], ctx.obj['password']))
if ctx.obj['pretty']:
print(json.dumps(json.loads(data), indent=4))
... | (ctx.obj['base'] + '/nodeconfig.json', params=params, auth=(ctx.obj['user'], ctx.obj['password']))
if ctx.obj['pretty']:
print(json.dumps(json.loads(data), indent=4))
else:
print(data)
@cli.command()
@click.pass_context
def status(ctx):
| 64 | 64 | 94 | 12 | 52 | jraska1/py-isac | py-isac.py | Python | status | status | 90 | 103 | 90 | 92 | d4543979ca44dd829475ea21f69f6c34deda6e20 | bigcode/the-stack | train |
a4f0fa3de6d43fe65e27c098 | train | function | @cli.command()
@click.pass_context
def info(ctx):
"""
ISAC Communication Node operational information.
"""
params = {
'username': ctx.obj['username'],
}
data = call_api(ctx.obj['base'] + '/app.json', params=params, auth=(ctx.obj['user'], ctx.obj['password']))
if ctx.obj['pretty']:
... | @cli.command()
@click.pass_context
def info(ctx):
| """
ISAC Communication Node operational information.
"""
params = {
'username': ctx.obj['username'],
}
data = call_api(ctx.obj['base'] + '/app.json', params=params, auth=(ctx.obj['user'], ctx.obj['password']))
if ctx.obj['pretty']:
print(json.dumps(json.loads(data), indent=4)... | if resp.status_code in accept_codes:
return None
resp.raise_for_status()
return resp.text
except requests.exceptions.RequestException as e:
print(f"Connection error: {e}", file=sys.stderr)
sys.exit(1)
@cli.command()
@click.pass_context
def info(ctx):
| 64 | 64 | 95 | 12 | 52 | jraska1/py-isac | py-isac.py | Python | info | info | 58 | 71 | 58 | 60 | 03ef9885bd33d738254ed10f70d3dee1b21966ae | bigcode/the-stack | train |
16ed6f0da80ada015822716e | train | function | @cli.command()
@click.option('--id', type=str, required=True, help="Patient ID - rodne cislo")
@click.option('--firstname', type=str, required=False, help="Patient First Name")
@click.option('--lastname', type=str, required=False, help="Patient Last Name")
@click.pass_context
def patsum(ctx, id, firstname, lastname):
... | @cli.command()
@click.option('--id', type=str, required=True, help="Patient ID - rodne cislo")
@click.option('--firstname', type=str, required=False, help="Patient First Name")
@click.option('--lastname', type=str, required=False, help="Patient Last Name")
@click.pass_context
def patsum(ctx, id, firstname, lastname):
| """
Patient Emergency Information Summary Client.
"""
params = {
'rc': id,
'firstname': firstname,
'lastname': lastname,
'username': ctx.obj['username'],
}
data = call_api(ctx.obj['base'] + '/ec.json', params=params, auth=(ctx.obj['user'], ctx.obj['password']))
... | @cli.command()
@click.option('--id', type=str, required=True, help="Patient ID - rodne cislo")
@click.option('--firstname', type=str, required=False, help="Patient First Name")
@click.option('--lastname', type=str, required=False, help="Patient Last Name")
@click.pass_context
def patsum(ctx, id, firstname, lastname):
| 74 | 64 | 174 | 74 | 0 | jraska1/py-isac | py-isac.py | Python | patsum | patsum | 138 | 157 | 138 | 143 | 4c5cad0d6da356e2e8fe0e8c6dba13f11f7dd744 | bigcode/the-stack | train |
3502ecfd23ed71d62960184a | train | function | @cli.command()
@click.pass_context
def config(ctx):
"""
Communication Node Configuration information.
"""
params = {
'username': ctx.obj['username'],
}
data = call_api(ctx.obj['base'] + '/nodeconfig.json', params=params, auth=(ctx.obj['user'], ctx.obj['password']))
if ctx.obj['pretty... | @cli.command()
@click.pass_context
def config(ctx):
| """
Communication Node Configuration information.
"""
params = {
'username': ctx.obj['username'],
}
data = call_api(ctx.obj['base'] + '/nodeconfig.json', params=params, auth=(ctx.obj['user'], ctx.obj['password']))
if ctx.obj['pretty']:
print(json.dumps(json.loads(data), inden... | _api(ctx.obj['base'] + '/app.json', params=params, auth=(ctx.obj['user'], ctx.obj['password']))
if ctx.obj['pretty']:
print(json.dumps(json.loads(data), indent=4))
else:
print(data)
@cli.command()
@click.pass_context
def config(ctx):
| 64 | 64 | 94 | 12 | 52 | jraska1/py-isac | py-isac.py | Python | config | config | 74 | 87 | 74 | 76 | d3274003e639789272e490a9ea430b873352e7de | bigcode/the-stack | train |
59e1aa93dd1751e8c5e0da3e | train | function | @liveOut.callback(
dash.dependencies.Output('internal_state', 'children'),
[dash.dependencies.Input('named_count_pipe', 'value'),
dash.dependencies.Input('state_uid', 'value'),],
)
def callback_liveOut_pipe_in(named_count, state_uid, **kwargs):
'Handle something changing the value of the input pipe... | @liveOut.callback(
dash.dependencies.Output('internal_state', 'children'),
[dash.dependencies.Input('named_count_pipe', 'value'),
dash.dependencies.Input('state_uid', 'value'),],
)
def callback_liveOut_pipe_in(named_count, state_uid, **kwargs):
| 'Handle something changing the value of the input pipe or the associated state uid'
cache_key = _get_cache_key(state_uid)
state = cache.get(cache_key)
# If nothing in cache, prepopulate
if not state:
state = {}
# Guard against missing input on startup
if not named_count:
n... | .Graph(id="timeseries_plot"),
dcc.Input(value=str(uuid.uuid4()),
id="state_uid",
style={'display':'none'},
)
])
liveOut.layout = generate_liveOut_layout
#pylint: disable=unused-argument
#@liveOut.expanded_callback(
@liveOut.callback(
dash.depend... | 120 | 120 | 403 | 58 | 62 | dwinston/django-plotly-dash | demo/demo/plotly_apps.py | Python | callback_liveOut_pipe_in | callback_liveOut_pipe_in | 216 | 266 | 216 | 221 | 8bb80baf97afcaa12c50bb60551c83a5ba8313ae | bigcode/the-stack | train |
0e37c8e9a1f21c8330f95320 | train | function | @app.callback(
dash.dependencies.Output('output-color', 'children'),
[dash.dependencies.Input('dropdown-color', 'value')])
def callback_color(dropdown_value):
'Change output message'
return "The selected color is %s." % dropdown_value
| @app.callback(
dash.dependencies.Output('output-color', 'children'),
[dash.dependencies.Input('dropdown-color', 'value')])
def callback_color(dropdown_value):
| 'Change output message'
return "The selected color is %s." % dropdown_value
| ('M', 'medium'),
('S', 'small')]],
value='medium'
),
html.Div(id='output-size')
])
@app.callback(
dash.dependencies.Output('output-color', 'children'),
[dash.dependencies.Input('dropdown-color', 'value')])
def callback_color(dropdown_value... | 64 | 64 | 54 | 34 | 30 | dwinston/django-plotly-dash | demo/demo/plotly_apps.py | Python | callback_color | callback_color | 69 | 74 | 69 | 72 | 14eaecafa8f8c4fca63936edc540199bbfb204ca | bigcode/the-stack | train |
9c04eb973a2432a061ae9b40 | train | function | def _get_cache_key(state_uid):
return "demo-liveout-s6-%s" % state_uid
| def _get_cache_key(state_uid):
| return "demo-liveout-s6-%s" % state_uid
| is %s red and %s blue; last change is %s at %s" % (red_clicks,
blue_clicks,
change_col,
... | 64 | 64 | 23 | 8 | 56 | dwinston/django-plotly-dash | demo/demo/plotly_apps.py | Python | _get_cache_key | _get_cache_key | 192 | 193 | 192 | 192 | f226eb84a52501a51a019b24e9449918a3c22022 | bigcode/the-stack | train |
2b6b7990c8f89c5f6ad463b3 | train | function | def generate_liveOut_layout():
'Generate the layout per-app, generating each tine a new uuid for the state_uid argument'
return html.Div([
dpd.Pipe(id="named_count_pipe",
value=None,
label="named_counts",
channel_name="live_button_counter"),
htm... | def generate_liveOut_layout():
| 'Generate the layout per-app, generating each tine a new uuid for the state_uid argument'
return html.Div([
dpd.Pipe(id="named_count_pipe",
value=None,
label="named_counts",
channel_name="live_button_counter"),
html.Div(id="internal_state",
... | _clicks,
blue_clicks,
change_col,
datetim... | 64 | 64 | 122 | 6 | 57 | dwinston/django-plotly-dash | demo/demo/plotly_apps.py | Python | generate_liveOut_layout | generate_liveOut_layout | 195 | 210 | 195 | 195 | 38e08d4224b943e4b6539fe24616114abe00d521 | bigcode/the-stack | train |
bfded9164372f67f5e82926e | train | function | @liveIn.expanded_callback(
dash.dependencies.Output('button_local_counter', 'children'),
[dash.dependencies.Input('red-button', 'n_clicks'),
dash.dependencies.Input('blue-button', 'n_clicks'),
dash.dependencies.Input('green-button', 'n_clicks'),
dash.dependencies.Input('red-button', 'n_clicks_tim... | @liveIn.expanded_callback(
dash.dependencies.Output('button_local_counter', 'children'),
[dash.dependencies.Input('red-button', 'n_clicks'),
dash.dependencies.Input('blue-button', 'n_clicks'),
dash.dependencies.Input('green-button', 'n_clicks'),
dash.dependencies.Input('red-button', 'n_clicks_tim... | 'Input app button pressed, so do something interesting'
if not rc_timestamp:
rc_timestamp = 0
if not bc_timestamp:
bc_timestamp = 0
if not gc_timestamp:
gc_timestamp = 0
if (rc_timestamp + bc_timestamp + gc_timestamp) < 1:
change_col = None
timestamp = 0
... | @liveIn.expanded_callback(
dash.dependencies.Output('button_local_counter', 'children'),
[dash.dependencies.Input('red-button', 'n_clicks'),
dash.dependencies.Input('blue-button', 'n_clicks'),
dash.dependencies.Input('green-button', 'n_clicks'),
dash.dependencies.Input('red-button', 'n_clicks_tim... | 145 | 126 | 423 | 145 | 0 | dwinston/django-plotly-dash | demo/demo/plotly_apps.py | Python | callback_liveIn_button_press | callback_liveIn_button_press | 139 | 188 | 139 | 150 | 274fe696ee4dd8156428e54a96bcffff4283c175 | bigcode/the-stack | train |
e99b48052dd6503d32e3731e | train | function | @liveOut.callback(
dash.dependencies.Output('timeseries_plot', 'figure'),
[dash.dependencies.Input('internal_state', 'children'),
dash.dependencies.Input('state_uid', 'value'),],
)
def callback_show_timeseries(internal_state_string, state_uid, **kwargs):
'Build a timeseries from the internal state'... | @liveOut.callback(
dash.dependencies.Output('timeseries_plot', 'figure'),
[dash.dependencies.Input('internal_state', 'children'),
dash.dependencies.Input('state_uid', 'value'),],
)
def callback_show_timeseries(internal_state_string, state_uid, **kwargs):
| 'Build a timeseries from the internal state'
cache_key = _get_cache_key(state_uid)
state = cache.get(cache_key)
# If nothing in cache, prepopulate
if not state:
state = {}
colour_series = {}
colors = {'red':'#FF0000',
'blue':'#0000FF',
'green':'#00FF00... | .1)),)
colour_set = colour_set[-100:]
state[click_colour] = colour_set
cache.set(cache_key, state, 3600)
return "(%s,%s)" % (cache_key, click_timestamp)
@liveOut.callback(
dash.dependencies.Output('timeseries_plot', 'figure'),
[dash.dependencies.Input('internal_state', 'childre... | 110 | 110 | 369 | 59 | 51 | dwinston/django-plotly-dash | demo/demo/plotly_apps.py | Python | callback_show_timeseries | callback_show_timeseries | 268 | 311 | 268 | 273 | 875c03bb522704fa2af4001b2c9012766dd3a145 | bigcode/the-stack | train |
dd3305e708861af3547dbf6d | train | function | @a2.expanded_callback(
dash.dependencies.Output('output-one', 'children'),
[dash.dependencies.Input('dropdown-one', 'value')]
)
def callback_c(*args, **kwargs):
'Update the output following a change of the input selection'
#da = kwargs['dash_app']
session_state = kwargs['session_state']
ca... | @a2.expanded_callback(
dash.dependencies.Output('output-one', 'children'),
[dash.dependencies.Input('dropdown-one', 'value')]
)
def callback_c(*args, **kwargs):
| 'Update the output following a change of the input selection'
#da = kwargs['dash_app']
session_state = kwargs['session_state']
calls_so_far = session_state.get('calls_so_far', 0)
session_state['calls_so_far'] = calls_so_far + 1
user_counts = session_state.get('user_counts', None)
user_nam... | ", "Carbon Dioxide")]],
value="Oxygen"),
html.Div(id="output-one")
])
@a2.expanded_callback(
dash.dependencies.Output('output-one', 'children'),
[dash.dependencies.Input('dropdown-one', 'value')]
)
def callback_c(*args, **kwargs):
| 64 | 64 | 200 | 41 | 23 | dwinston/django-plotly-dash | demo/demo/plotly_apps.py | Python | callback_c | callback_c | 97 | 118 | 97 | 101 | e10b3a4601092d9a7fed4f57e22fba8afc13b981 | bigcode/the-stack | train |
2341499a3c1e027b1899dc3a | train | function | @app.callback(
dash.dependencies.Output('output-size', 'children'),
[dash.dependencies.Input('dropdown-color', 'value'),
dash.dependencies.Input('dropdown-size', 'value')])
def callback_size(dropdown_color, dropdown_size):
'Change output message'
return "The chosen T-shirt is a %s %s one." %(dropdo... | @app.callback(
dash.dependencies.Output('output-size', 'children'),
[dash.dependencies.Input('dropdown-color', 'value'),
dash.dependencies.Input('dropdown-size', 'value')])
def callback_size(dropdown_color, dropdown_size):
| 'Change output message'
return "The chosen T-shirt is a %s %s one." %(dropdown_size,
dropdown_color)
| message'
return "The selected color is %s." % dropdown_value
@app.callback(
dash.dependencies.Output('output-size', 'children'),
[dash.dependencies.Input('dropdown-color', 'value'),
dash.dependencies.Input('dropdown-size', 'value')])
def callback_size(dropdown_color, dropdown_size):
| 64 | 64 | 77 | 48 | 15 | dwinston/django-plotly-dash | demo/demo/plotly_apps.py | Python | callback_size | callback_size | 76 | 83 | 76 | 80 | 624c9136ba7342771b9f9018de6779f18e90f728 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.