id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
229,400
intake/intake
intake/source/base.py
DataSource.yaml
def yaml(self, with_plugin=False): """Return YAML representation of this data-source The output may be roughly appropriate for inclusion in a YAML catalog. This is a best-effort implementation Parameters ---------- with_plugin: bool If True, create a "plugins" section, for cases where this source is created with a plugin not expected to be in the global Intake registry. """ from yaml import dump data = self._yaml(with_plugin=with_plugin) return dump(data, default_flow_style=False)
python
def yaml(self, with_plugin=False): """Return YAML representation of this data-source The output may be roughly appropriate for inclusion in a YAML catalog. This is a best-effort implementation Parameters ---------- with_plugin: bool If True, create a "plugins" section, for cases where this source is created with a plugin not expected to be in the global Intake registry. """ from yaml import dump data = self._yaml(with_plugin=with_plugin) return dump(data, default_flow_style=False)
[ "def", "yaml", "(", "self", ",", "with_plugin", "=", "False", ")", ":", "from", "yaml", "import", "dump", "data", "=", "self", ".", "_yaml", "(", "with_plugin", "=", "with_plugin", ")", "return", "dump", "(", "data", ",", "default_flow_style", "=", "False", ")" ]
Return YAML representation of this data-source The output may be roughly appropriate for inclusion in a YAML catalog. This is a best-effort implementation Parameters ---------- with_plugin: bool If True, create a "plugins" section, for cases where this source is created with a plugin not expected to be in the global Intake registry.
[ "Return", "YAML", "representation", "of", "this", "data", "-", "source" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/base.py#L145-L160
229,401
intake/intake
intake/source/base.py
DataSource.discover
def discover(self): """Open resource and populate the source attributes.""" self._load_metadata() return dict(datashape=self.datashape, dtype=self.dtype, shape=self.shape, npartitions=self.npartitions, metadata=self.metadata)
python
def discover(self): """Open resource and populate the source attributes.""" self._load_metadata() return dict(datashape=self.datashape, dtype=self.dtype, shape=self.shape, npartitions=self.npartitions, metadata=self.metadata)
[ "def", "discover", "(", "self", ")", ":", "self", ".", "_load_metadata", "(", ")", "return", "dict", "(", "datashape", "=", "self", ".", "datashape", ",", "dtype", "=", "self", ".", "dtype", ",", "shape", "=", "self", ".", "shape", ",", "npartitions", "=", "self", ".", "npartitions", ",", "metadata", "=", "self", ".", "metadata", ")" ]
Open resource and populate the source attributes.
[ "Open", "resource", "and", "populate", "the", "source", "attributes", "." ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/base.py#L167-L175
229,402
intake/intake
intake/source/base.py
DataSource.read_chunked
def read_chunked(self): """Return iterator over container fragments of data source""" self._load_metadata() for i in range(self.npartitions): yield self._get_partition(i)
python
def read_chunked(self): """Return iterator over container fragments of data source""" self._load_metadata() for i in range(self.npartitions): yield self._get_partition(i)
[ "def", "read_chunked", "(", "self", ")", ":", "self", ".", "_load_metadata", "(", ")", "for", "i", "in", "range", "(", "self", ".", "npartitions", ")", ":", "yield", "self", ".", "_get_partition", "(", "i", ")" ]
Return iterator over container fragments of data source
[ "Return", "iterator", "over", "container", "fragments", "of", "data", "source" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/base.py#L184-L188
229,403
intake/intake
intake/source/base.py
DataSource.read_partition
def read_partition(self, i): """Return a part of the data corresponding to i-th partition. By default, assumes i should be an integer between zero and npartitions; override for more complex indexing schemes. """ self._load_metadata() if i < 0 or i >= self.npartitions: raise IndexError('%d is out of range' % i) return self._get_partition(i)
python
def read_partition(self, i): """Return a part of the data corresponding to i-th partition. By default, assumes i should be an integer between zero and npartitions; override for more complex indexing schemes. """ self._load_metadata() if i < 0 or i >= self.npartitions: raise IndexError('%d is out of range' % i) return self._get_partition(i)
[ "def", "read_partition", "(", "self", ",", "i", ")", ":", "self", ".", "_load_metadata", "(", ")", "if", "i", "<", "0", "or", "i", ">=", "self", ".", "npartitions", ":", "raise", "IndexError", "(", "'%d is out of range'", "%", "i", ")", "return", "self", ".", "_get_partition", "(", "i", ")" ]
Return a part of the data corresponding to i-th partition. By default, assumes i should be an integer between zero and npartitions; override for more complex indexing schemes.
[ "Return", "a", "part", "of", "the", "data", "corresponding", "to", "i", "-", "th", "partition", "." ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/base.py#L190-L200
229,404
intake/intake
intake/source/base.py
DataSource.plot
def plot(self): """ Returns a hvPlot object to provide a high-level plotting API. To display in a notebook, be sure to run ``intake.output_notebook()`` first. """ try: from hvplot import hvPlot except ImportError: raise ImportError("The intake plotting API requires hvplot." "hvplot may be installed with:\n\n" "`conda install -c pyviz hvplot` or " "`pip install hvplot`.") metadata = self.metadata.get('plot', {}) fields = self.metadata.get('fields', {}) for attrs in fields.values(): if 'range' in attrs: attrs['range'] = tuple(attrs['range']) metadata['fields'] = fields plots = self.metadata.get('plots', {}) return hvPlot(self, custom_plots=plots, **metadata)
python
def plot(self): """ Returns a hvPlot object to provide a high-level plotting API. To display in a notebook, be sure to run ``intake.output_notebook()`` first. """ try: from hvplot import hvPlot except ImportError: raise ImportError("The intake plotting API requires hvplot." "hvplot may be installed with:\n\n" "`conda install -c pyviz hvplot` or " "`pip install hvplot`.") metadata = self.metadata.get('plot', {}) fields = self.metadata.get('fields', {}) for attrs in fields.values(): if 'range' in attrs: attrs['range'] = tuple(attrs['range']) metadata['fields'] = fields plots = self.metadata.get('plots', {}) return hvPlot(self, custom_plots=plots, **metadata)
[ "def", "plot", "(", "self", ")", ":", "try", ":", "from", "hvplot", "import", "hvPlot", "except", "ImportError", ":", "raise", "ImportError", "(", "\"The intake plotting API requires hvplot.\"", "\"hvplot may be installed with:\\n\\n\"", "\"`conda install -c pyviz hvplot` or \"", "\"`pip install hvplot`.\"", ")", "metadata", "=", "self", ".", "metadata", ".", "get", "(", "'plot'", ",", "{", "}", ")", "fields", "=", "self", ".", "metadata", ".", "get", "(", "'fields'", ",", "{", "}", ")", "for", "attrs", "in", "fields", ".", "values", "(", ")", ":", "if", "'range'", "in", "attrs", ":", "attrs", "[", "'range'", "]", "=", "tuple", "(", "attrs", "[", "'range'", "]", ")", "metadata", "[", "'fields'", "]", "=", "fields", "plots", "=", "self", ".", "metadata", ".", "get", "(", "'plots'", ",", "{", "}", ")", "return", "hvPlot", "(", "self", ",", "custom_plots", "=", "plots", ",", "*", "*", "metadata", ")" ]
Returns a hvPlot object to provide a high-level plotting API. To display in a notebook, be sure to run ``intake.output_notebook()`` first.
[ "Returns", "a", "hvPlot", "object", "to", "provide", "a", "high", "-", "level", "plotting", "API", "." ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/base.py#L231-L252
229,405
intake/intake
intake/source/base.py
DataSource.persist
def persist(self, ttl=None, **kwargs): """Save data from this source to local persistent storage""" from ..container import container_map from ..container.persist import PersistStore import time if 'original_tok' in self.metadata: raise ValueError('Cannot persist a source taken from the persist ' 'store') method = container_map[self.container]._persist store = PersistStore() out = method(self, path=store.getdir(self), **kwargs) out.description = self.description metadata = {'timestamp': time.time(), 'original_metadata': self.metadata, 'original_source': self.__getstate__(), 'original_name': self.name, 'original_tok': self._tok, 'persist_kwargs': kwargs, 'ttl': ttl, 'cat': {} if self.cat is None else self.cat.__getstate__()} out.metadata = metadata out.name = self.name store.add(self._tok, out) return out
python
def persist(self, ttl=None, **kwargs): """Save data from this source to local persistent storage""" from ..container import container_map from ..container.persist import PersistStore import time if 'original_tok' in self.metadata: raise ValueError('Cannot persist a source taken from the persist ' 'store') method = container_map[self.container]._persist store = PersistStore() out = method(self, path=store.getdir(self), **kwargs) out.description = self.description metadata = {'timestamp': time.time(), 'original_metadata': self.metadata, 'original_source': self.__getstate__(), 'original_name': self.name, 'original_tok': self._tok, 'persist_kwargs': kwargs, 'ttl': ttl, 'cat': {} if self.cat is None else self.cat.__getstate__()} out.metadata = metadata out.name = self.name store.add(self._tok, out) return out
[ "def", "persist", "(", "self", ",", "ttl", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", ".", ".", "container", "import", "container_map", "from", ".", ".", "container", ".", "persist", "import", "PersistStore", "import", "time", "if", "'original_tok'", "in", "self", ".", "metadata", ":", "raise", "ValueError", "(", "'Cannot persist a source taken from the persist '", "'store'", ")", "method", "=", "container_map", "[", "self", ".", "container", "]", ".", "_persist", "store", "=", "PersistStore", "(", ")", "out", "=", "method", "(", "self", ",", "path", "=", "store", ".", "getdir", "(", "self", ")", ",", "*", "*", "kwargs", ")", "out", ".", "description", "=", "self", ".", "description", "metadata", "=", "{", "'timestamp'", ":", "time", ".", "time", "(", ")", ",", "'original_metadata'", ":", "self", ".", "metadata", ",", "'original_source'", ":", "self", ".", "__getstate__", "(", ")", ",", "'original_name'", ":", "self", ".", "name", ",", "'original_tok'", ":", "self", ".", "_tok", ",", "'persist_kwargs'", ":", "kwargs", ",", "'ttl'", ":", "ttl", ",", "'cat'", ":", "{", "}", "if", "self", ".", "cat", "is", "None", "else", "self", ".", "cat", ".", "__getstate__", "(", ")", "}", "out", ".", "metadata", "=", "metadata", "out", ".", "name", "=", "self", ".", "name", "store", ".", "add", "(", "self", ".", "_tok", ",", "out", ")", "return", "out" ]
Save data from this source to local persistent storage
[ "Save", "data", "from", "this", "source", "to", "local", "persistent", "storage" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/base.py#L261-L284
229,406
intake/intake
intake/source/base.py
DataSource.export
def export(self, path, **kwargs): """Save this data for sharing with other people Creates a copy of the data in a format appropriate for its container, in the location specified (which can be remote, e.g., s3). Returns a YAML representation of this saved dataset, so that it can be put into a catalog file. """ from ..container import container_map import time method = container_map[self.container]._persist # may need to create path - access file-system method out = method(self, path=path, **kwargs) out.description = self.description metadata = {'timestamp': time.time(), 'original_metadata': self.metadata, 'original_source': self.__getstate__(), 'original_name': self.name, 'original_tok': self._tok, 'persist_kwargs': kwargs} out.metadata = metadata out.name = self.name return out.yaml()
python
def export(self, path, **kwargs): """Save this data for sharing with other people Creates a copy of the data in a format appropriate for its container, in the location specified (which can be remote, e.g., s3). Returns a YAML representation of this saved dataset, so that it can be put into a catalog file. """ from ..container import container_map import time method = container_map[self.container]._persist # may need to create path - access file-system method out = method(self, path=path, **kwargs) out.description = self.description metadata = {'timestamp': time.time(), 'original_metadata': self.metadata, 'original_source': self.__getstate__(), 'original_name': self.name, 'original_tok': self._tok, 'persist_kwargs': kwargs} out.metadata = metadata out.name = self.name return out.yaml()
[ "def", "export", "(", "self", ",", "path", ",", "*", "*", "kwargs", ")", ":", "from", ".", ".", "container", "import", "container_map", "import", "time", "method", "=", "container_map", "[", "self", ".", "container", "]", ".", "_persist", "# may need to create path - access file-system method", "out", "=", "method", "(", "self", ",", "path", "=", "path", ",", "*", "*", "kwargs", ")", "out", ".", "description", "=", "self", ".", "description", "metadata", "=", "{", "'timestamp'", ":", "time", ".", "time", "(", ")", ",", "'original_metadata'", ":", "self", ".", "metadata", ",", "'original_source'", ":", "self", ".", "__getstate__", "(", ")", ",", "'original_name'", ":", "self", ".", "name", ",", "'original_tok'", ":", "self", ".", "_tok", ",", "'persist_kwargs'", ":", "kwargs", "}", "out", ".", "metadata", "=", "metadata", "out", ".", "name", "=", "self", ".", "name", "return", "out", ".", "yaml", "(", ")" ]
Save this data for sharing with other people Creates a copy of the data in a format appropriate for its container, in the location specified (which can be remote, e.g., s3). Returns a YAML representation of this saved dataset, so that it can be put into a catalog file.
[ "Save", "this", "data", "for", "sharing", "with", "other", "people" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/base.py#L286-L308
229,407
intake/intake
intake/catalog/default.py
load_user_catalog
def load_user_catalog(): """Return a catalog for the platform-specific user Intake directory""" cat_dir = user_data_dir() if not os.path.isdir(cat_dir): return Catalog() else: return YAMLFilesCatalog(cat_dir)
python
def load_user_catalog(): """Return a catalog for the platform-specific user Intake directory""" cat_dir = user_data_dir() if not os.path.isdir(cat_dir): return Catalog() else: return YAMLFilesCatalog(cat_dir)
[ "def", "load_user_catalog", "(", ")", ":", "cat_dir", "=", "user_data_dir", "(", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "cat_dir", ")", ":", "return", "Catalog", "(", ")", "else", ":", "return", "YAMLFilesCatalog", "(", "cat_dir", ")" ]
Return a catalog for the platform-specific user Intake directory
[ "Return", "a", "catalog", "for", "the", "platform", "-", "specific", "user", "Intake", "directory" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/default.py#L19-L25
229,408
intake/intake
intake/catalog/default.py
load_global_catalog
def load_global_catalog(): """Return a catalog for the environment-specific Intake directory""" cat_dir = global_data_dir() if not os.path.isdir(cat_dir): return Catalog() else: return YAMLFilesCatalog(cat_dir)
python
def load_global_catalog(): """Return a catalog for the environment-specific Intake directory""" cat_dir = global_data_dir() if not os.path.isdir(cat_dir): return Catalog() else: return YAMLFilesCatalog(cat_dir)
[ "def", "load_global_catalog", "(", ")", ":", "cat_dir", "=", "global_data_dir", "(", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "cat_dir", ")", ":", "return", "Catalog", "(", ")", "else", ":", "return", "YAMLFilesCatalog", "(", "cat_dir", ")" ]
Return a catalog for the environment-specific Intake directory
[ "Return", "a", "catalog", "for", "the", "environment", "-", "specific", "Intake", "directory" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/default.py#L33-L39
229,409
intake/intake
intake/catalog/default.py
global_data_dir
def global_data_dir(): """Return the global Intake catalog dir for the current environment""" prefix = False if VIRTUALENV_VAR in os.environ: prefix = os.environ[VIRTUALENV_VAR] elif CONDA_VAR in os.environ: prefix = sys.prefix elif which('conda'): # conda exists but is not activated prefix = conda_prefix() if prefix: # conda and virtualenv use Linux-style directory pattern return make_path_posix(os.path.join(prefix, 'share', 'intake')) else: return appdirs.site_data_dir(appname='intake', appauthor='intake')
python
def global_data_dir(): """Return the global Intake catalog dir for the current environment""" prefix = False if VIRTUALENV_VAR in os.environ: prefix = os.environ[VIRTUALENV_VAR] elif CONDA_VAR in os.environ: prefix = sys.prefix elif which('conda'): # conda exists but is not activated prefix = conda_prefix() if prefix: # conda and virtualenv use Linux-style directory pattern return make_path_posix(os.path.join(prefix, 'share', 'intake')) else: return appdirs.site_data_dir(appname='intake', appauthor='intake')
[ "def", "global_data_dir", "(", ")", ":", "prefix", "=", "False", "if", "VIRTUALENV_VAR", "in", "os", ".", "environ", ":", "prefix", "=", "os", ".", "environ", "[", "VIRTUALENV_VAR", "]", "elif", "CONDA_VAR", "in", "os", ".", "environ", ":", "prefix", "=", "sys", ".", "prefix", "elif", "which", "(", "'conda'", ")", ":", "# conda exists but is not activated", "prefix", "=", "conda_prefix", "(", ")", "if", "prefix", ":", "# conda and virtualenv use Linux-style directory pattern", "return", "make_path_posix", "(", "os", ".", "path", ".", "join", "(", "prefix", ",", "'share'", ",", "'intake'", ")", ")", "else", ":", "return", "appdirs", ".", "site_data_dir", "(", "appname", "=", "'intake'", ",", "appauthor", "=", "'intake'", ")" ]
Return the global Intake catalog dir for the current environment
[ "Return", "the", "global", "Intake", "catalog", "dir", "for", "the", "current", "environment" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/default.py#L61-L76
229,410
intake/intake
intake/catalog/default.py
load_combo_catalog
def load_combo_catalog(): """Load a union of the user and global catalogs for convenience""" user_dir = user_data_dir() global_dir = global_data_dir() desc = 'Generated from data packages found on your intake search path' cat_dirs = [] if os.path.isdir(user_dir): cat_dirs.append(user_dir + '/*.yaml') cat_dirs.append(user_dir + '/*.yml') if os.path.isdir(global_dir): cat_dirs.append(global_dir + '/*.yaml') cat_dirs.append(global_dir + '/*.yml') for path_dir in conf.get('catalog_path', []): if path_dir != '': if not path_dir.endswith(('yaml', 'yml')): cat_dirs.append(path_dir + '/*.yaml') cat_dirs.append(path_dir + '/*.yml') else: cat_dirs.append(path_dir) return YAMLFilesCatalog(cat_dirs, name='builtin', description=desc)
python
def load_combo_catalog(): """Load a union of the user and global catalogs for convenience""" user_dir = user_data_dir() global_dir = global_data_dir() desc = 'Generated from data packages found on your intake search path' cat_dirs = [] if os.path.isdir(user_dir): cat_dirs.append(user_dir + '/*.yaml') cat_dirs.append(user_dir + '/*.yml') if os.path.isdir(global_dir): cat_dirs.append(global_dir + '/*.yaml') cat_dirs.append(global_dir + '/*.yml') for path_dir in conf.get('catalog_path', []): if path_dir != '': if not path_dir.endswith(('yaml', 'yml')): cat_dirs.append(path_dir + '/*.yaml') cat_dirs.append(path_dir + '/*.yml') else: cat_dirs.append(path_dir) return YAMLFilesCatalog(cat_dirs, name='builtin', description=desc)
[ "def", "load_combo_catalog", "(", ")", ":", "user_dir", "=", "user_data_dir", "(", ")", "global_dir", "=", "global_data_dir", "(", ")", "desc", "=", "'Generated from data packages found on your intake search path'", "cat_dirs", "=", "[", "]", "if", "os", ".", "path", ".", "isdir", "(", "user_dir", ")", ":", "cat_dirs", ".", "append", "(", "user_dir", "+", "'/*.yaml'", ")", "cat_dirs", ".", "append", "(", "user_dir", "+", "'/*.yml'", ")", "if", "os", ".", "path", ".", "isdir", "(", "global_dir", ")", ":", "cat_dirs", ".", "append", "(", "global_dir", "+", "'/*.yaml'", ")", "cat_dirs", ".", "append", "(", "global_dir", "+", "'/*.yml'", ")", "for", "path_dir", "in", "conf", ".", "get", "(", "'catalog_path'", ",", "[", "]", ")", ":", "if", "path_dir", "!=", "''", ":", "if", "not", "path_dir", ".", "endswith", "(", "(", "'yaml'", ",", "'yml'", ")", ")", ":", "cat_dirs", ".", "append", "(", "path_dir", "+", "'/*.yaml'", ")", "cat_dirs", ".", "append", "(", "path_dir", "+", "'/*.yml'", ")", "else", ":", "cat_dirs", ".", "append", "(", "path_dir", ")", "return", "YAMLFilesCatalog", "(", "cat_dirs", ",", "name", "=", "'builtin'", ",", "description", "=", "desc", ")" ]
Load a union of the user and global catalogs for convenience
[ "Load", "a", "union", "of", "the", "user", "and", "global", "catalogs", "for", "convenience" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/default.py#L79-L99
229,411
intake/intake
intake/catalog/base.py
Catalog.from_dict
def from_dict(cls, entries, **kwargs): """ Create Catalog from the given set of entries Parameters ---------- entries : dict-like A mapping of name:entry which supports dict-like functionality, e.g., is derived from ``collections.abc.Mapping``. kwargs : passed on the constructor Things like metadata, name; see ``__init__``. Returns ------- Catalog instance """ from dask.base import tokenize cat = cls(**kwargs) cat._entries = entries cat._tok = tokenize(kwargs, entries) return cat
python
def from_dict(cls, entries, **kwargs): """ Create Catalog from the given set of entries Parameters ---------- entries : dict-like A mapping of name:entry which supports dict-like functionality, e.g., is derived from ``collections.abc.Mapping``. kwargs : passed on the constructor Things like metadata, name; see ``__init__``. Returns ------- Catalog instance """ from dask.base import tokenize cat = cls(**kwargs) cat._entries = entries cat._tok = tokenize(kwargs, entries) return cat
[ "def", "from_dict", "(", "cls", ",", "entries", ",", "*", "*", "kwargs", ")", ":", "from", "dask", ".", "base", "import", "tokenize", "cat", "=", "cls", "(", "*", "*", "kwargs", ")", "cat", ".", "_entries", "=", "entries", "cat", ".", "_tok", "=", "tokenize", "(", "kwargs", ",", "entries", ")", "return", "cat" ]
Create Catalog from the given set of entries Parameters ---------- entries : dict-like A mapping of name:entry which supports dict-like functionality, e.g., is derived from ``collections.abc.Mapping``. kwargs : passed on the constructor Things like metadata, name; see ``__init__``. Returns ------- Catalog instance
[ "Create", "Catalog", "from", "the", "given", "set", "of", "entries" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/base.py#L118-L138
229,412
intake/intake
intake/catalog/base.py
Catalog.reload
def reload(self): """Reload catalog if sufficient time has passed""" if time.time() - self.updated > self.ttl: self.force_reload()
python
def reload(self): """Reload catalog if sufficient time has passed""" if time.time() - self.updated > self.ttl: self.force_reload()
[ "def", "reload", "(", "self", ")", ":", "if", "time", ".", "time", "(", ")", "-", "self", ".", "updated", ">", "self", ".", "ttl", ":", "self", ".", "force_reload", "(", ")" ]
Reload catalog if sufficient time has passed
[ "Reload", "catalog", "if", "sufficient", "time", "has", "passed" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/base.py#L177-L180
229,413
intake/intake
intake/catalog/base.py
Catalog.filter
def filter(self, func): """Create a Catalog of a subset of entries based on a condition Note that, whatever specific class this is performed on, the return instance is a Catalog. The entries are passed unmodified, so they will still reference the original catalog instance and include its details such as directory,. Parameters ---------- func : function This should take a CatalogEntry and return True or False. Those items returning True will be included in the new Catalog, with the same entry names Returns ------- New Catalog """ return Catalog.from_dict({key: entry for key, entry in self.items() if func(entry)})
python
def filter(self, func): """Create a Catalog of a subset of entries based on a condition Note that, whatever specific class this is performed on, the return instance is a Catalog. The entries are passed unmodified, so they will still reference the original catalog instance and include its details such as directory,. Parameters ---------- func : function This should take a CatalogEntry and return True or False. Those items returning True will be included in the new Catalog, with the same entry names Returns ------- New Catalog """ return Catalog.from_dict({key: entry for key, entry in self.items() if func(entry)})
[ "def", "filter", "(", "self", ",", "func", ")", ":", "return", "Catalog", ".", "from_dict", "(", "{", "key", ":", "entry", "for", "key", ",", "entry", "in", "self", ".", "items", "(", ")", "if", "func", "(", "entry", ")", "}", ")" ]
Create a Catalog of a subset of entries based on a condition Note that, whatever specific class this is performed on, the return instance is a Catalog. The entries are passed unmodified, so they will still reference the original catalog instance and include its details such as directory,. Parameters ---------- func : function This should take a CatalogEntry and return True or False. Those items returning True will be included in the new Catalog, with the same entry names Returns ------- New Catalog
[ "Create", "a", "Catalog", "of", "a", "subset", "of", "entries", "based", "on", "a", "condition" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/base.py#L208-L228
229,414
intake/intake
intake/catalog/base.py
Catalog.walk
def walk(self, sofar=None, prefix=None, depth=2): """Get all entries in this catalog and sub-catalogs Parameters ---------- sofar: dict or None Within recursion, use this dict for output prefix: list of str or None Names of levels already visited depth: int Number of levels to descend; needed to truncate circular references and for cleaner output Returns ------- Dict where the keys are the entry names in dotted syntax, and the values are entry instances. """ out = sofar if sofar is not None else {} prefix = [] if prefix is None else prefix for name, item in self._entries.items(): if item._container == 'catalog' and depth > 1: # recurse with default open parameters try: item().walk(out, prefix + [name], depth-1) except Exception as e: print(e) pass # ignore inability to descend n = '.'.join(prefix + [name]) out[n] = item return out
python
def walk(self, sofar=None, prefix=None, depth=2): """Get all entries in this catalog and sub-catalogs Parameters ---------- sofar: dict or None Within recursion, use this dict for output prefix: list of str or None Names of levels already visited depth: int Number of levels to descend; needed to truncate circular references and for cleaner output Returns ------- Dict where the keys are the entry names in dotted syntax, and the values are entry instances. """ out = sofar if sofar is not None else {} prefix = [] if prefix is None else prefix for name, item in self._entries.items(): if item._container == 'catalog' and depth > 1: # recurse with default open parameters try: item().walk(out, prefix + [name], depth-1) except Exception as e: print(e) pass # ignore inability to descend n = '.'.join(prefix + [name]) out[n] = item return out
[ "def", "walk", "(", "self", ",", "sofar", "=", "None", ",", "prefix", "=", "None", ",", "depth", "=", "2", ")", ":", "out", "=", "sofar", "if", "sofar", "is", "not", "None", "else", "{", "}", "prefix", "=", "[", "]", "if", "prefix", "is", "None", "else", "prefix", "for", "name", ",", "item", "in", "self", ".", "_entries", ".", "items", "(", ")", ":", "if", "item", ".", "_container", "==", "'catalog'", "and", "depth", ">", "1", ":", "# recurse with default open parameters", "try", ":", "item", "(", ")", ".", "walk", "(", "out", ",", "prefix", "+", "[", "name", "]", ",", "depth", "-", "1", ")", "except", "Exception", "as", "e", ":", "print", "(", "e", ")", "pass", "# ignore inability to descend", "n", "=", "'.'", ".", "join", "(", "prefix", "+", "[", "name", "]", ")", "out", "[", "n", "]", "=", "item", "return", "out" ]
Get all entries in this catalog and sub-catalogs Parameters ---------- sofar: dict or None Within recursion, use this dict for output prefix: list of str or None Names of levels already visited depth: int Number of levels to descend; needed to truncate circular references and for cleaner output Returns ------- Dict where the keys are the entry names in dotted syntax, and the values are entry instances.
[ "Get", "all", "entries", "in", "this", "catalog", "and", "sub", "-", "catalogs" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/base.py#L231-L261
229,415
intake/intake
intake/catalog/base.py
Catalog.serialize
def serialize(self): """ Produce YAML version of this catalog. Note that this is not the same as ``.yaml()``, which produces a YAML block referring to this catalog. """ import yaml output = {"metadata": self.metadata, "sources": {}, "name": self.name} for key, entry in self.items(): output["sources"][key] = entry._captured_init_kwargs return yaml.dump(output)
python
def serialize(self): """ Produce YAML version of this catalog. Note that this is not the same as ``.yaml()``, which produces a YAML block referring to this catalog. """ import yaml output = {"metadata": self.metadata, "sources": {}, "name": self.name} for key, entry in self.items(): output["sources"][key] = entry._captured_init_kwargs return yaml.dump(output)
[ "def", "serialize", "(", "self", ")", ":", "import", "yaml", "output", "=", "{", "\"metadata\"", ":", "self", ".", "metadata", ",", "\"sources\"", ":", "{", "}", ",", "\"name\"", ":", "self", ".", "name", "}", "for", "key", ",", "entry", "in", "self", ".", "items", "(", ")", ":", "output", "[", "\"sources\"", "]", "[", "key", "]", "=", "entry", ".", "_captured_init_kwargs", "return", "yaml", ".", "dump", "(", "output", ")" ]
Produce YAML version of this catalog. Note that this is not the same as ``.yaml()``, which produces a YAML block referring to this catalog.
[ "Produce", "YAML", "version", "of", "this", "catalog", "." ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/base.py#L267-L279
229,416
intake/intake
intake/catalog/base.py
Catalog.save
def save(self, url, storage_options=None): """ Output this catalog to a file as YAML Parameters ---------- url : str Location to save to, perhaps remote storage_options : dict Extra arguments for the file-system """ from dask.bytes import open_files with open_files([url], **(storage_options or {}), mode='wt')[0] as f: f.write(self.serialize())
python
def save(self, url, storage_options=None): """ Output this catalog to a file as YAML Parameters ---------- url : str Location to save to, perhaps remote storage_options : dict Extra arguments for the file-system """ from dask.bytes import open_files with open_files([url], **(storage_options or {}), mode='wt')[0] as f: f.write(self.serialize())
[ "def", "save", "(", "self", ",", "url", ",", "storage_options", "=", "None", ")", ":", "from", "dask", ".", "bytes", "import", "open_files", "with", "open_files", "(", "[", "url", "]", ",", "*", "*", "(", "storage_options", "or", "{", "}", ")", ",", "mode", "=", "'wt'", ")", "[", "0", "]", "as", "f", ":", "f", ".", "write", "(", "self", ".", "serialize", "(", ")", ")" ]
Output this catalog to a file as YAML Parameters ---------- url : str Location to save to, perhaps remote storage_options : dict Extra arguments for the file-system
[ "Output", "this", "catalog", "to", "a", "file", "as", "YAML" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/base.py#L281-L294
229,417
intake/intake
intake/catalog/base.py
Entries.reset
def reset(self): "Clear caches to force a reload." self._page_cache.clear() self._direct_lookup_cache.clear() self._page_offset = 0 self.complete = self._catalog.page_size is None
python
def reset(self): "Clear caches to force a reload." self._page_cache.clear() self._direct_lookup_cache.clear() self._page_offset = 0 self.complete = self._catalog.page_size is None
[ "def", "reset", "(", "self", ")", ":", "self", ".", "_page_cache", ".", "clear", "(", ")", "self", ".", "_direct_lookup_cache", ".", "clear", "(", ")", "self", ".", "_page_offset", "=", "0", "self", ".", "complete", "=", "self", ".", "_catalog", ".", "page_size", "is", "None" ]
Clear caches to force a reload.
[ "Clear", "caches", "to", "force", "a", "reload", "." ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/base.py#L444-L449
229,418
intake/intake
intake/catalog/base.py
Entries.cached_items
def cached_items(self): """ Iterate over items that are already cached. Perform no requests. """ for item in six.iteritems(self._page_cache): yield item for item in six.iteritems(self._direct_lookup_cache): yield item
python
def cached_items(self): """ Iterate over items that are already cached. Perform no requests. """ for item in six.iteritems(self._page_cache): yield item for item in six.iteritems(self._direct_lookup_cache): yield item
[ "def", "cached_items", "(", "self", ")", ":", "for", "item", "in", "six", ".", "iteritems", "(", "self", ".", "_page_cache", ")", ":", "yield", "item", "for", "item", "in", "six", ".", "iteritems", "(", "self", ".", "_direct_lookup_cache", ")", ":", "yield", "item" ]
Iterate over items that are already cached. Perform no requests.
[ "Iterate", "over", "items", "that", "are", "already", "cached", ".", "Perform", "no", "requests", "." ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/base.py#L473-L480
229,419
intake/intake
intake/catalog/base.py
RemoteCatalog._get_http_args
def _get_http_args(self, params): """ Return a copy of the http_args Adds auth headers and 'source_id', merges in params. """ # Add the auth headers to any other headers headers = self.http_args.get('headers', {}) if self.auth is not None: auth_headers = self.auth.get_headers() headers.update(auth_headers) # build new http args with these headers http_args = self.http_args.copy() if self._source_id is not None: headers['source_id'] = self._source_id http_args['headers'] = headers # Merge in any params specified by the caller. merged_params = http_args.get('params', {}) merged_params.update(params) http_args['params'] = merged_params return http_args
python
def _get_http_args(self, params): """ Return a copy of the http_args Adds auth headers and 'source_id', merges in params. """ # Add the auth headers to any other headers headers = self.http_args.get('headers', {}) if self.auth is not None: auth_headers = self.auth.get_headers() headers.update(auth_headers) # build new http args with these headers http_args = self.http_args.copy() if self._source_id is not None: headers['source_id'] = self._source_id http_args['headers'] = headers # Merge in any params specified by the caller. merged_params = http_args.get('params', {}) merged_params.update(params) http_args['params'] = merged_params return http_args
[ "def", "_get_http_args", "(", "self", ",", "params", ")", ":", "# Add the auth headers to any other headers", "headers", "=", "self", ".", "http_args", ".", "get", "(", "'headers'", ",", "{", "}", ")", "if", "self", ".", "auth", "is", "not", "None", ":", "auth_headers", "=", "self", ".", "auth", ".", "get_headers", "(", ")", "headers", ".", "update", "(", "auth_headers", ")", "# build new http args with these headers", "http_args", "=", "self", ".", "http_args", ".", "copy", "(", ")", "if", "self", ".", "_source_id", "is", "not", "None", ":", "headers", "[", "'source_id'", "]", "=", "self", ".", "_source_id", "http_args", "[", "'headers'", "]", "=", "headers", "# Merge in any params specified by the caller.", "merged_params", "=", "http_args", ".", "get", "(", "'params'", ",", "{", "}", ")", "merged_params", ".", "update", "(", "params", ")", "http_args", "[", "'params'", "]", "=", "merged_params", "return", "http_args" ]
Return a copy of the http_args Adds auth headers and 'source_id', merges in params.
[ "Return", "a", "copy", "of", "the", "http_args" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/base.py#L650-L672
229,420
intake/intake
intake/catalog/base.py
RemoteCatalog._load
def _load(self): """Fetch metadata from remote. Entries are fetched lazily.""" # This will not immediately fetch any sources (entries). It will lazily # fetch sources from the server in paginated blocks when this Catalog # is iterated over. It will fetch specific sources when they are # accessed in this Catalog via __getitem__. if self.page_size is None: # Fetch all source info. params = {} else: # Just fetch the metadata now; fetch source info later in pages. params = {'page_offset': 0, 'page_size': 0} http_args = self._get_http_args(params) response = requests.get(self.info_url, **http_args) try: response.raise_for_status() except requests.HTTPError as err: six.raise_from(RemoteCatalogError( "Failed to fetch metadata."), err) info = msgpack.unpackb(response.content, **unpack_kwargs) self.metadata = info['metadata'] # The intake server now always provides a length, but the server may be # running an older version of intake. self._len = info.get('length') self._entries.reset() # If we are paginating (page_size is not None) and the server we are # working with is new enough to support pagination, info['sources'] # should be empty. If either of those things is not true, # info['sources'] will contain all the entries and we should cache them # now. if info['sources']: # Signal that we are not paginating, even if we were asked to. self._page_size = None self._entries._page_cache.update( {source['name']: RemoteCatalogEntry( url=self.url, getenv=self.getenv, getshell=self.getshell, auth=self.auth, http_args=self.http_args, **source) for source in info['sources']})
python
def _load(self): """Fetch metadata from remote. Entries are fetched lazily.""" # This will not immediately fetch any sources (entries). It will lazily # fetch sources from the server in paginated blocks when this Catalog # is iterated over. It will fetch specific sources when they are # accessed in this Catalog via __getitem__. if self.page_size is None: # Fetch all source info. params = {} else: # Just fetch the metadata now; fetch source info later in pages. params = {'page_offset': 0, 'page_size': 0} http_args = self._get_http_args(params) response = requests.get(self.info_url, **http_args) try: response.raise_for_status() except requests.HTTPError as err: six.raise_from(RemoteCatalogError( "Failed to fetch metadata."), err) info = msgpack.unpackb(response.content, **unpack_kwargs) self.metadata = info['metadata'] # The intake server now always provides a length, but the server may be # running an older version of intake. self._len = info.get('length') self._entries.reset() # If we are paginating (page_size is not None) and the server we are # working with is new enough to support pagination, info['sources'] # should be empty. If either of those things is not true, # info['sources'] will contain all the entries and we should cache them # now. if info['sources']: # Signal that we are not paginating, even if we were asked to. self._page_size = None self._entries._page_cache.update( {source['name']: RemoteCatalogEntry( url=self.url, getenv=self.getenv, getshell=self.getshell, auth=self.auth, http_args=self.http_args, **source) for source in info['sources']})
[ "def", "_load", "(", "self", ")", ":", "# This will not immediately fetch any sources (entries). It will lazily", "# fetch sources from the server in paginated blocks when this Catalog", "# is iterated over. It will fetch specific sources when they are", "# accessed in this Catalog via __getitem__.", "if", "self", ".", "page_size", "is", "None", ":", "# Fetch all source info.", "params", "=", "{", "}", "else", ":", "# Just fetch the metadata now; fetch source info later in pages.", "params", "=", "{", "'page_offset'", ":", "0", ",", "'page_size'", ":", "0", "}", "http_args", "=", "self", ".", "_get_http_args", "(", "params", ")", "response", "=", "requests", ".", "get", "(", "self", ".", "info_url", ",", "*", "*", "http_args", ")", "try", ":", "response", ".", "raise_for_status", "(", ")", "except", "requests", ".", "HTTPError", "as", "err", ":", "six", ".", "raise_from", "(", "RemoteCatalogError", "(", "\"Failed to fetch metadata.\"", ")", ",", "err", ")", "info", "=", "msgpack", ".", "unpackb", "(", "response", ".", "content", ",", "*", "*", "unpack_kwargs", ")", "self", ".", "metadata", "=", "info", "[", "'metadata'", "]", "# The intake server now always provides a length, but the server may be", "# running an older version of intake.", "self", ".", "_len", "=", "info", ".", "get", "(", "'length'", ")", "self", ".", "_entries", ".", "reset", "(", ")", "# If we are paginating (page_size is not None) and the server we are", "# working with is new enough to support pagination, info['sources']", "# should be empty. If either of those things is not true,", "# info['sources'] will contain all the entries and we should cache them", "# now.", "if", "info", "[", "'sources'", "]", ":", "# Signal that we are not paginating, even if we were asked to.", "self", ".", "_page_size", "=", "None", "self", ".", "_entries", ".", "_page_cache", ".", "update", "(", "{", "source", "[", "'name'", "]", ":", "RemoteCatalogEntry", "(", "url", "=", "self", ".", "url", ",", "getenv", "=", "self", ".", "getenv", ",", "getshell", "=", "self", ".", "getshell", ",", "auth", "=", "self", ".", "auth", ",", "http_args", "=", "self", ".", "http_args", ",", "*", "*", "source", ")", "for", "source", "in", "info", "[", "'sources'", "]", "}", ")" ]
Fetch metadata from remote. Entries are fetched lazily.
[ "Fetch", "metadata", "from", "remote", ".", "Entries", "are", "fetched", "lazily", "." ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/base.py#L674-L715
229,421
intake/intake
intake/cli/util.py
nice_join
def nice_join(seq, sep=", ", conjunction="or"): ''' Join together sequences of strings into English-friendly phrases using a conjunction when appropriate. Args: seq (seq[str]) : a sequence of strings to nicely join sep (str, optional) : a sequence delimiter to use (default: ", ") conjunction (str or None, optional) : a conjunction to use for the last two items, or None to reproduce basic join behavior (default: "or") Returns: a joined string Examples: >>> nice_join(["a", "b", "c"]) 'a, b or c' ''' seq = [str(x) for x in seq] if len(seq) <= 1 or conjunction is None: return sep.join(seq) else: return "%s %s %s" % (sep.join(seq[:-1]), conjunction, seq[-1])
python
def nice_join(seq, sep=", ", conjunction="or"): ''' Join together sequences of strings into English-friendly phrases using a conjunction when appropriate. Args: seq (seq[str]) : a sequence of strings to nicely join sep (str, optional) : a sequence delimiter to use (default: ", ") conjunction (str or None, optional) : a conjunction to use for the last two items, or None to reproduce basic join behavior (default: "or") Returns: a joined string Examples: >>> nice_join(["a", "b", "c"]) 'a, b or c' ''' seq = [str(x) for x in seq] if len(seq) <= 1 or conjunction is None: return sep.join(seq) else: return "%s %s %s" % (sep.join(seq[:-1]), conjunction, seq[-1])
[ "def", "nice_join", "(", "seq", ",", "sep", "=", "\", \"", ",", "conjunction", "=", "\"or\"", ")", ":", "seq", "=", "[", "str", "(", "x", ")", "for", "x", "in", "seq", "]", "if", "len", "(", "seq", ")", "<=", "1", "or", "conjunction", "is", "None", ":", "return", "sep", ".", "join", "(", "seq", ")", "else", ":", "return", "\"%s %s %s\"", "%", "(", "sep", ".", "join", "(", "seq", "[", ":", "-", "1", "]", ")", ",", "conjunction", ",", "seq", "[", "-", "1", "]", ")" ]
Join together sequences of strings into English-friendly phrases using a conjunction when appropriate. Args: seq (seq[str]) : a sequence of strings to nicely join sep (str, optional) : a sequence delimiter to use (default: ", ") conjunction (str or None, optional) : a conjunction to use for the last two items, or None to reproduce basic join behavior (default: "or") Returns: a joined string Examples: >>> nice_join(["a", "b", "c"]) 'a, b or c'
[ "Join", "together", "sequences", "of", "strings", "into", "English", "-", "friendly", "phrases", "using", "a", "conjunction", "when", "appropriate", "." ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/cli/util.py#L46-L71
229,422
intake/intake
intake/__init__.py
output_notebook
def output_notebook(inline=True, logo=False): """ Load the notebook extension Parameters ---------- inline : boolean (optional) Whether to inline JS code or load it from a CDN logo : boolean (optional) Whether to show the logo(s) """ try: import hvplot except ImportError: raise ImportError("The intake plotting API requires hvplot." "hvplot may be installed with:\n\n" "`conda install -c pyviz hvplot` or " "`pip install hvplot`.") import holoviews as hv return hv.extension('bokeh', inline=inline, logo=logo)
python
def output_notebook(inline=True, logo=False): """ Load the notebook extension Parameters ---------- inline : boolean (optional) Whether to inline JS code or load it from a CDN logo : boolean (optional) Whether to show the logo(s) """ try: import hvplot except ImportError: raise ImportError("The intake plotting API requires hvplot." "hvplot may be installed with:\n\n" "`conda install -c pyviz hvplot` or " "`pip install hvplot`.") import holoviews as hv return hv.extension('bokeh', inline=inline, logo=logo)
[ "def", "output_notebook", "(", "inline", "=", "True", ",", "logo", "=", "False", ")", ":", "try", ":", "import", "hvplot", "except", "ImportError", ":", "raise", "ImportError", "(", "\"The intake plotting API requires hvplot.\"", "\"hvplot may be installed with:\\n\\n\"", "\"`conda install -c pyviz hvplot` or \"", "\"`pip install hvplot`.\"", ")", "import", "holoviews", "as", "hv", "return", "hv", ".", "extension", "(", "'bokeh'", ",", "inline", "=", "inline", ",", "logo", "=", "logo", ")" ]
Load the notebook extension Parameters ---------- inline : boolean (optional) Whether to inline JS code or load it from a CDN logo : boolean (optional) Whether to show the logo(s)
[ "Load", "the", "notebook", "extension" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/__init__.py#L57-L76
229,423
intake/intake
intake/__init__.py
open_catalog
def open_catalog(uri=None, **kwargs): """Create a Catalog object Can load YAML catalog files, connect to an intake server, or create any arbitrary Catalog subclass instance. In the general case, the user should supply ``driver=`` with a value from the plugins registry which has a container type of catalog. File locations can generally be remote, if specifying a URL protocol. The default behaviour if not specifying the driver is as follows: - if ``uri`` is a a single string ending in "yml" or "yaml", open it as a catalog file - if ``uri`` is a list of strings, a string containing a glob character ("*") or a string not ending in "y(a)ml", open as a set of catalog files. In the latter case, assume it is a directory. - if ``uri`` beings with protocol ``"intake:"``, connect to a remote Intake server - otherwise, create a base Catalog object without entries. Parameters ---------- uri: str Designator for the location of the catalog. kwargs: passed to subclass instance, see documentation of the individual catalog classes. For example, ``yaml_files_cat`` (when specifying multiple uris or a glob string) takes the additional parameter ``flatten=True|False``, specifying whether all data sources are merged in a single namespace, or each file becomes a sub-catalog. See also -------- intake.open_yaml_files_cat, intake.open_yaml_file_cat, intake.open_intake_remote """ driver = kwargs.pop('driver', None) if driver is None: if uri: if ((isinstance(uri, str) and "*" in uri) or ((isinstance(uri, (list, tuple))) and len(uri) > 1)): # glob string or list of files/globs driver = 'yaml_files_cat' elif isinstance(uri, (list, tuple)) and len(uri) == 1: uri = uri[0] if "*" in uri[0]: # single glob string in a list driver = 'yaml_files_cat' else: # single filename in a list driver = 'yaml_file_cat' elif isinstance(uri, str): # single URL if uri.startswith('intake:'): # server driver = 'intake_remote' else: if uri.endswith(('.yml', '.yaml')): driver = 'yaml_file_cat' else: uri = uri.rstrip('/') + '/*.y*ml' driver = 'yaml_files_cat' else: # empty cat driver = 'catalog' if driver not in registry: raise ValueError('Unknown catalog driver (%s), supply one of: %s' % (driver, list(sorted(registry)))) return registry[driver](uri, **kwargs)
python
def open_catalog(uri=None, **kwargs): """Create a Catalog object Can load YAML catalog files, connect to an intake server, or create any arbitrary Catalog subclass instance. In the general case, the user should supply ``driver=`` with a value from the plugins registry which has a container type of catalog. File locations can generally be remote, if specifying a URL protocol. The default behaviour if not specifying the driver is as follows: - if ``uri`` is a a single string ending in "yml" or "yaml", open it as a catalog file - if ``uri`` is a list of strings, a string containing a glob character ("*") or a string not ending in "y(a)ml", open as a set of catalog files. In the latter case, assume it is a directory. - if ``uri`` beings with protocol ``"intake:"``, connect to a remote Intake server - otherwise, create a base Catalog object without entries. Parameters ---------- uri: str Designator for the location of the catalog. kwargs: passed to subclass instance, see documentation of the individual catalog classes. For example, ``yaml_files_cat`` (when specifying multiple uris or a glob string) takes the additional parameter ``flatten=True|False``, specifying whether all data sources are merged in a single namespace, or each file becomes a sub-catalog. See also -------- intake.open_yaml_files_cat, intake.open_yaml_file_cat, intake.open_intake_remote """ driver = kwargs.pop('driver', None) if driver is None: if uri: if ((isinstance(uri, str) and "*" in uri) or ((isinstance(uri, (list, tuple))) and len(uri) > 1)): # glob string or list of files/globs driver = 'yaml_files_cat' elif isinstance(uri, (list, tuple)) and len(uri) == 1: uri = uri[0] if "*" in uri[0]: # single glob string in a list driver = 'yaml_files_cat' else: # single filename in a list driver = 'yaml_file_cat' elif isinstance(uri, str): # single URL if uri.startswith('intake:'): # server driver = 'intake_remote' else: if uri.endswith(('.yml', '.yaml')): driver = 'yaml_file_cat' else: uri = uri.rstrip('/') + '/*.y*ml' driver = 'yaml_files_cat' else: # empty cat driver = 'catalog' if driver not in registry: raise ValueError('Unknown catalog driver (%s), supply one of: %s' % (driver, list(sorted(registry)))) return registry[driver](uri, **kwargs)
[ "def", "open_catalog", "(", "uri", "=", "None", ",", "*", "*", "kwargs", ")", ":", "driver", "=", "kwargs", ".", "pop", "(", "'driver'", ",", "None", ")", "if", "driver", "is", "None", ":", "if", "uri", ":", "if", "(", "(", "isinstance", "(", "uri", ",", "str", ")", "and", "\"*\"", "in", "uri", ")", "or", "(", "(", "isinstance", "(", "uri", ",", "(", "list", ",", "tuple", ")", ")", ")", "and", "len", "(", "uri", ")", ">", "1", ")", ")", ":", "# glob string or list of files/globs", "driver", "=", "'yaml_files_cat'", "elif", "isinstance", "(", "uri", ",", "(", "list", ",", "tuple", ")", ")", "and", "len", "(", "uri", ")", "==", "1", ":", "uri", "=", "uri", "[", "0", "]", "if", "\"*\"", "in", "uri", "[", "0", "]", ":", "# single glob string in a list", "driver", "=", "'yaml_files_cat'", "else", ":", "# single filename in a list", "driver", "=", "'yaml_file_cat'", "elif", "isinstance", "(", "uri", ",", "str", ")", ":", "# single URL", "if", "uri", ".", "startswith", "(", "'intake:'", ")", ":", "# server", "driver", "=", "'intake_remote'", "else", ":", "if", "uri", ".", "endswith", "(", "(", "'.yml'", ",", "'.yaml'", ")", ")", ":", "driver", "=", "'yaml_file_cat'", "else", ":", "uri", "=", "uri", ".", "rstrip", "(", "'/'", ")", "+", "'/*.y*ml'", "driver", "=", "'yaml_files_cat'", "else", ":", "# empty cat", "driver", "=", "'catalog'", "if", "driver", "not", "in", "registry", ":", "raise", "ValueError", "(", "'Unknown catalog driver (%s), supply one of: %s'", "%", "(", "driver", ",", "list", "(", "sorted", "(", "registry", ")", ")", ")", ")", "return", "registry", "[", "driver", "]", "(", "uri", ",", "*", "*", "kwargs", ")" ]
Create a Catalog object Can load YAML catalog files, connect to an intake server, or create any arbitrary Catalog subclass instance. In the general case, the user should supply ``driver=`` with a value from the plugins registry which has a container type of catalog. File locations can generally be remote, if specifying a URL protocol. The default behaviour if not specifying the driver is as follows: - if ``uri`` is a a single string ending in "yml" or "yaml", open it as a catalog file - if ``uri`` is a list of strings, a string containing a glob character ("*") or a string not ending in "y(a)ml", open as a set of catalog files. In the latter case, assume it is a directory. - if ``uri`` beings with protocol ``"intake:"``, connect to a remote Intake server - otherwise, create a base Catalog object without entries. Parameters ---------- uri: str Designator for the location of the catalog. kwargs: passed to subclass instance, see documentation of the individual catalog classes. For example, ``yaml_files_cat`` (when specifying multiple uris or a glob string) takes the additional parameter ``flatten=True|False``, specifying whether all data sources are merged in a single namespace, or each file becomes a sub-catalog. See also -------- intake.open_yaml_files_cat, intake.open_yaml_file_cat, intake.open_intake_remote
[ "Create", "a", "Catalog", "object" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/__init__.py#L83-L152
229,424
intake/intake
intake/container/dataframe.py
RemoteDataFrame._persist
def _persist(source, path, **kwargs): """Save dataframe to local persistent store Makes a parquet dataset out of the data using dask.dataframe.to_parquet. This then becomes a data entry in the persisted datasets catalog. Parameters ---------- source: a DataSource instance to save name: str or None Key to refer to this persisted dataset by. If not given, will attempt to get from the source's name kwargs: passed on to dask.dataframe.to_parquet """ try: from intake_parquet import ParquetSource except ImportError: raise ImportError("Please install intake-parquet to use persistence" " on dataframe container sources.") try: df = source.to_dask() except NotImplementedError: import dask.dataframe as dd df = dd.from_pandas(source.read(), 1) df.to_parquet(path, **kwargs) source = ParquetSource(path, meta={}) return source
python
def _persist(source, path, **kwargs): """Save dataframe to local persistent store Makes a parquet dataset out of the data using dask.dataframe.to_parquet. This then becomes a data entry in the persisted datasets catalog. Parameters ---------- source: a DataSource instance to save name: str or None Key to refer to this persisted dataset by. If not given, will attempt to get from the source's name kwargs: passed on to dask.dataframe.to_parquet """ try: from intake_parquet import ParquetSource except ImportError: raise ImportError("Please install intake-parquet to use persistence" " on dataframe container sources.") try: df = source.to_dask() except NotImplementedError: import dask.dataframe as dd df = dd.from_pandas(source.read(), 1) df.to_parquet(path, **kwargs) source = ParquetSource(path, meta={}) return source
[ "def", "_persist", "(", "source", ",", "path", ",", "*", "*", "kwargs", ")", ":", "try", ":", "from", "intake_parquet", "import", "ParquetSource", "except", "ImportError", ":", "raise", "ImportError", "(", "\"Please install intake-parquet to use persistence\"", "\" on dataframe container sources.\"", ")", "try", ":", "df", "=", "source", ".", "to_dask", "(", ")", "except", "NotImplementedError", ":", "import", "dask", ".", "dataframe", "as", "dd", "df", "=", "dd", ".", "from_pandas", "(", "source", ".", "read", "(", ")", ",", "1", ")", "df", ".", "to_parquet", "(", "path", ",", "*", "*", "kwargs", ")", "source", "=", "ParquetSource", "(", "path", ",", "meta", "=", "{", "}", ")", "return", "source" ]
Save dataframe to local persistent store Makes a parquet dataset out of the data using dask.dataframe.to_parquet. This then becomes a data entry in the persisted datasets catalog. Parameters ---------- source: a DataSource instance to save name: str or None Key to refer to this persisted dataset by. If not given, will attempt to get from the source's name kwargs: passed on to dask.dataframe.to_parquet
[ "Save", "dataframe", "to", "local", "persistent", "store" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/container/dataframe.py#L61-L87
229,425
intake/intake
intake/config.py
save_conf
def save_conf(fn=None): """Save current configuration to file as YAML If not given, uses current config directory, ``confdir``, which can be set by INTAKE_CONF_DIR. """ if fn is None: fn = cfile() try: os.makedirs(os.path.dirname(fn)) except (OSError, IOError): pass with open(fn, 'w') as f: yaml.dump(conf, f)
python
def save_conf(fn=None): """Save current configuration to file as YAML If not given, uses current config directory, ``confdir``, which can be set by INTAKE_CONF_DIR. """ if fn is None: fn = cfile() try: os.makedirs(os.path.dirname(fn)) except (OSError, IOError): pass with open(fn, 'w') as f: yaml.dump(conf, f)
[ "def", "save_conf", "(", "fn", "=", "None", ")", ":", "if", "fn", "is", "None", ":", "fn", "=", "cfile", "(", ")", "try", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "fn", ")", ")", "except", "(", "OSError", ",", "IOError", ")", ":", "pass", "with", "open", "(", "fn", ",", "'w'", ")", "as", "f", ":", "yaml", ".", "dump", "(", "conf", ",", "f", ")" ]
Save current configuration to file as YAML If not given, uses current config directory, ``confdir``, which can be set by INTAKE_CONF_DIR.
[ "Save", "current", "configuration", "to", "file", "as", "YAML" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/config.py#L46-L59
229,426
intake/intake
intake/config.py
load_conf
def load_conf(fn=None): """Update global config from YAML file If fn is None, looks in global config directory, which is either defined by the INTAKE_CONF_DIR env-var or is ~/.intake/ . """ if fn is None: fn = cfile() if os.path.isfile(fn): with open(fn) as f: try: conf.update(yaml_load(f)) except Exception as e: logger.warning('Failure to load config file "{fn}": {e}' ''.format(fn=fn, e=e))
python
def load_conf(fn=None): """Update global config from YAML file If fn is None, looks in global config directory, which is either defined by the INTAKE_CONF_DIR env-var or is ~/.intake/ . """ if fn is None: fn = cfile() if os.path.isfile(fn): with open(fn) as f: try: conf.update(yaml_load(f)) except Exception as e: logger.warning('Failure to load config file "{fn}": {e}' ''.format(fn=fn, e=e))
[ "def", "load_conf", "(", "fn", "=", "None", ")", ":", "if", "fn", "is", "None", ":", "fn", "=", "cfile", "(", ")", "if", "os", ".", "path", ".", "isfile", "(", "fn", ")", ":", "with", "open", "(", "fn", ")", "as", "f", ":", "try", ":", "conf", ".", "update", "(", "yaml_load", "(", "f", ")", ")", "except", "Exception", "as", "e", ":", "logger", ".", "warning", "(", "'Failure to load config file \"{fn}\": {e}'", "''", ".", "format", "(", "fn", "=", "fn", ",", "e", "=", "e", ")", ")" ]
Update global config from YAML file If fn is None, looks in global config directory, which is either defined by the INTAKE_CONF_DIR env-var or is ~/.intake/ .
[ "Update", "global", "config", "from", "YAML", "file" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/config.py#L62-L76
229,427
intake/intake
intake/config.py
intake_path_dirs
def intake_path_dirs(path): """Return a list of directories from the intake path. If a string, perhaps taken from an environment variable, then the list of paths will be split on the character ":" for posix of ";" for windows. Protocol indicators ("protocol://") will be ignored. """ if isinstance(path, (list, tuple)): return path import re pattern = re.compile(";" if os.name == 'nt' else r"(?<!:):(?![:/])") return pattern.split(path)
python
def intake_path_dirs(path): """Return a list of directories from the intake path. If a string, perhaps taken from an environment variable, then the list of paths will be split on the character ":" for posix of ";" for windows. Protocol indicators ("protocol://") will be ignored. """ if isinstance(path, (list, tuple)): return path import re pattern = re.compile(";" if os.name == 'nt' else r"(?<!:):(?![:/])") return pattern.split(path)
[ "def", "intake_path_dirs", "(", "path", ")", ":", "if", "isinstance", "(", "path", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "path", "import", "re", "pattern", "=", "re", ".", "compile", "(", "\";\"", "if", "os", ".", "name", "==", "'nt'", "else", "r\"(?<!:):(?![:/])\"", ")", "return", "pattern", ".", "split", "(", "path", ")" ]
Return a list of directories from the intake path. If a string, perhaps taken from an environment variable, then the list of paths will be split on the character ":" for posix of ";" for windows. Protocol indicators ("protocol://") will be ignored.
[ "Return", "a", "list", "of", "directories", "from", "the", "intake", "path", "." ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/config.py#L79-L90
229,428
intake/intake
intake/config.py
load_env
def load_env(): """Analyse enviroment variables and update conf accordingly""" # environment variables take precedence over conf file for key, envvar in [['cache_dir', 'INTAKE_CACHE_DIR'], ['catalog_path', 'INTAKE_PATH'], ['persist_path', 'INTAKE_PERSIST_PATH']]: if envvar in os.environ: conf[key] = make_path_posix(os.environ[envvar]) conf['catalog_path'] = intake_path_dirs(conf['catalog_path']) for key, envvar in [['cache_disabled', 'INTAKE_DISABLE_CACHING'], ['cache_download_progress', 'INTAKE_CACHE_PROGRESS']]: if envvar in os.environ: conf[key] = os.environ[envvar].lower() in ['true', 't', 'y', 'yes'] if 'INTAKE_LOG_LEVEL' in os.environ: conf['logging'] = os.environ['INTAKE_LOG_LEVEL']
python
def load_env(): """Analyse enviroment variables and update conf accordingly""" # environment variables take precedence over conf file for key, envvar in [['cache_dir', 'INTAKE_CACHE_DIR'], ['catalog_path', 'INTAKE_PATH'], ['persist_path', 'INTAKE_PERSIST_PATH']]: if envvar in os.environ: conf[key] = make_path_posix(os.environ[envvar]) conf['catalog_path'] = intake_path_dirs(conf['catalog_path']) for key, envvar in [['cache_disabled', 'INTAKE_DISABLE_CACHING'], ['cache_download_progress', 'INTAKE_CACHE_PROGRESS']]: if envvar in os.environ: conf[key] = os.environ[envvar].lower() in ['true', 't', 'y', 'yes'] if 'INTAKE_LOG_LEVEL' in os.environ: conf['logging'] = os.environ['INTAKE_LOG_LEVEL']
[ "def", "load_env", "(", ")", ":", "# environment variables take precedence over conf file", "for", "key", ",", "envvar", "in", "[", "[", "'cache_dir'", ",", "'INTAKE_CACHE_DIR'", "]", ",", "[", "'catalog_path'", ",", "'INTAKE_PATH'", "]", ",", "[", "'persist_path'", ",", "'INTAKE_PERSIST_PATH'", "]", "]", ":", "if", "envvar", "in", "os", ".", "environ", ":", "conf", "[", "key", "]", "=", "make_path_posix", "(", "os", ".", "environ", "[", "envvar", "]", ")", "conf", "[", "'catalog_path'", "]", "=", "intake_path_dirs", "(", "conf", "[", "'catalog_path'", "]", ")", "for", "key", ",", "envvar", "in", "[", "[", "'cache_disabled'", ",", "'INTAKE_DISABLE_CACHING'", "]", ",", "[", "'cache_download_progress'", ",", "'INTAKE_CACHE_PROGRESS'", "]", "]", ":", "if", "envvar", "in", "os", ".", "environ", ":", "conf", "[", "key", "]", "=", "os", ".", "environ", "[", "envvar", "]", ".", "lower", "(", ")", "in", "[", "'true'", ",", "'t'", ",", "'y'", ",", "'yes'", "]", "if", "'INTAKE_LOG_LEVEL'", "in", "os", ".", "environ", ":", "conf", "[", "'logging'", "]", "=", "os", ".", "environ", "[", "'INTAKE_LOG_LEVEL'", "]" ]
Analyse enviroment variables and update conf accordingly
[ "Analyse", "enviroment", "variables", "and", "update", "conf", "accordingly" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/config.py#L93-L107
229,429
intake/intake
intake/gui/source/description.py
Description.source
def source(self, source): """When the source gets updated, update the pane object""" BaseView.source.fset(self, source) if self.main_pane: self.main_pane.object = self.contents self.label_pane.object = self.label
python
def source(self, source): """When the source gets updated, update the pane object""" BaseView.source.fset(self, source) if self.main_pane: self.main_pane.object = self.contents self.label_pane.object = self.label
[ "def", "source", "(", "self", ",", "source", ")", ":", "BaseView", ".", "source", ".", "fset", "(", "self", ",", "source", ")", "if", "self", ".", "main_pane", ":", "self", ".", "main_pane", ".", "object", "=", "self", ".", "contents", "self", ".", "label_pane", ".", "object", "=", "self", ".", "label" ]
When the source gets updated, update the pane object
[ "When", "the", "source", "gets", "updated", "update", "the", "pane", "object" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/gui/source/description.py#L52-L57
229,430
intake/intake
intake/gui/source/description.py
Description.contents
def contents(self): """String representation of the source's description""" if not self._source: return ' ' * 100 # HACK - make sure that area is big contents = self.source.describe() return pretty_describe(contents)
python
def contents(self): """String representation of the source's description""" if not self._source: return ' ' * 100 # HACK - make sure that area is big contents = self.source.describe() return pretty_describe(contents)
[ "def", "contents", "(", "self", ")", ":", "if", "not", "self", ".", "_source", ":", "return", "' '", "*", "100", "# HACK - make sure that area is big", "contents", "=", "self", ".", "source", ".", "describe", "(", ")", "return", "pretty_describe", "(", "contents", ")" ]
String representation of the source's description
[ "String", "representation", "of", "the", "source", "s", "description" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/gui/source/description.py#L60-L65
229,431
intake/intake
intake/source/utils.py
_get_parts_of_format_string
def _get_parts_of_format_string(resolved_string, literal_texts, format_specs): """ Inner function of reverse_format, returns the resolved value for each field in pattern. """ _text = resolved_string bits = [] if literal_texts[-1] != '' and _text.endswith(literal_texts[-1]): _text = _text[:-len(literal_texts[-1])] literal_texts = literal_texts[:-1] format_specs = format_specs[:-1] for i, literal_text in enumerate(literal_texts): if literal_text != '': if literal_text not in _text: raise ValueError(("Resolved string must match pattern. " "'{}' not found.".format(literal_text))) bit, _text = _text.split(literal_text, 1) if bit: bits.append(bit) elif i == 0: continue else: try: format_spec = _validate_format_spec(format_specs[i-1]) bits.append(_text[0:format_spec]) _text = _text[format_spec:] except: if i == len(format_specs) - 1: format_spec = _validate_format_spec(format_specs[i]) bits.append(_text[:-format_spec]) bits.append(_text[-format_spec:]) _text = [] else: _validate_format_spec(format_specs[i-1]) if _text: bits.append(_text) if len(bits) > len([fs for fs in format_specs if fs is not None]): bits = bits[1:] return bits
python
def _get_parts_of_format_string(resolved_string, literal_texts, format_specs): """ Inner function of reverse_format, returns the resolved value for each field in pattern. """ _text = resolved_string bits = [] if literal_texts[-1] != '' and _text.endswith(literal_texts[-1]): _text = _text[:-len(literal_texts[-1])] literal_texts = literal_texts[:-1] format_specs = format_specs[:-1] for i, literal_text in enumerate(literal_texts): if literal_text != '': if literal_text not in _text: raise ValueError(("Resolved string must match pattern. " "'{}' not found.".format(literal_text))) bit, _text = _text.split(literal_text, 1) if bit: bits.append(bit) elif i == 0: continue else: try: format_spec = _validate_format_spec(format_specs[i-1]) bits.append(_text[0:format_spec]) _text = _text[format_spec:] except: if i == len(format_specs) - 1: format_spec = _validate_format_spec(format_specs[i]) bits.append(_text[:-format_spec]) bits.append(_text[-format_spec:]) _text = [] else: _validate_format_spec(format_specs[i-1]) if _text: bits.append(_text) if len(bits) > len([fs for fs in format_specs if fs is not None]): bits = bits[1:] return bits
[ "def", "_get_parts_of_format_string", "(", "resolved_string", ",", "literal_texts", ",", "format_specs", ")", ":", "_text", "=", "resolved_string", "bits", "=", "[", "]", "if", "literal_texts", "[", "-", "1", "]", "!=", "''", "and", "_text", ".", "endswith", "(", "literal_texts", "[", "-", "1", "]", ")", ":", "_text", "=", "_text", "[", ":", "-", "len", "(", "literal_texts", "[", "-", "1", "]", ")", "]", "literal_texts", "=", "literal_texts", "[", ":", "-", "1", "]", "format_specs", "=", "format_specs", "[", ":", "-", "1", "]", "for", "i", ",", "literal_text", "in", "enumerate", "(", "literal_texts", ")", ":", "if", "literal_text", "!=", "''", ":", "if", "literal_text", "not", "in", "_text", ":", "raise", "ValueError", "(", "(", "\"Resolved string must match pattern. \"", "\"'{}' not found.\"", ".", "format", "(", "literal_text", ")", ")", ")", "bit", ",", "_text", "=", "_text", ".", "split", "(", "literal_text", ",", "1", ")", "if", "bit", ":", "bits", ".", "append", "(", "bit", ")", "elif", "i", "==", "0", ":", "continue", "else", ":", "try", ":", "format_spec", "=", "_validate_format_spec", "(", "format_specs", "[", "i", "-", "1", "]", ")", "bits", ".", "append", "(", "_text", "[", "0", ":", "format_spec", "]", ")", "_text", "=", "_text", "[", "format_spec", ":", "]", "except", ":", "if", "i", "==", "len", "(", "format_specs", ")", "-", "1", ":", "format_spec", "=", "_validate_format_spec", "(", "format_specs", "[", "i", "]", ")", "bits", ".", "append", "(", "_text", "[", ":", "-", "format_spec", "]", ")", "bits", ".", "append", "(", "_text", "[", "-", "format_spec", ":", "]", ")", "_text", "=", "[", "]", "else", ":", "_validate_format_spec", "(", "format_specs", "[", "i", "-", "1", "]", ")", "if", "_text", ":", "bits", ".", "append", "(", "_text", ")", "if", "len", "(", "bits", ")", ">", "len", "(", "[", "fs", "for", "fs", "in", "format_specs", "if", "fs", "is", "not", "None", "]", ")", ":", "bits", "=", "bits", "[", "1", ":", "]", "return", "bits" ]
Inner function of reverse_format, returns the resolved value for each field in pattern.
[ "Inner", "function", "of", "reverse_format", "returns", "the", "resolved", "value", "for", "each", "field", "in", "pattern", "." ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/utils.py#L26-L66
229,432
intake/intake
intake/source/utils.py
reverse_formats
def reverse_formats(format_string, resolved_strings): """ Reverse the string method format for a list of strings. Given format_string and resolved_strings, for each resolved string find arguments that would give ``format_string.format(**arguments) == resolved_string``. Each item in the output corresponds to a new column with the key setting the name and the values representing a mapping from list of resolved_strings to the related value. Parameters ---------- format_strings : str Format template string as used with str.format method resolved_strings : list List of strings with same pattern as format_string but with fields filled out. Returns ------- args : dict Dict of the form ``{field: [value_0, ..., value_n], ...}`` where values are in the same order as resolved_strings, so: ``format_sting.format(**{f: v[0] for f, v in args.items()}) == resolved_strings[0]`` Examples -------- >>> paths = ['data_2014_01_03.csv', 'data_2014_02_03.csv', 'data_2015_12_03.csv'] >>> reverse_formats('data_{year}_{month}_{day}.csv', paths) {'year': ['2014', '2014', '2015'], 'month': ['01', '02', '12'], 'day': ['03', '03', '03']} >>> reverse_formats('data_{year:d}_{month:d}_{day:d}.csv', paths) {'year': [2014, 2014, 2015], 'month': [1, 2, 12], 'day': [3, 3, 3]} >>> reverse_formats('data_{date:%Y_%m_%d}.csv', paths) {'date': [datetime.datetime(2014, 1, 3, 0, 0), datetime.datetime(2014, 2, 3, 0, 0), datetime.datetime(2015, 12, 3, 0, 0)]} >>> reverse_formats('{state:2}{zip:5}', ['PA19104', 'PA19143', 'MA02534']) {'state': ['PA', 'PA', 'MA'], 'zip': ['19104', '19143', '02534']} See also -------- str.format : method that this reverses reverse_format : method for reversing just one string using a pattern """ from string import Formatter fmt = Formatter() # get the fields from the format_string field_names = [i[1] for i in fmt.parse(format_string) if i[1]] # itialize the args dict with an empty dict for each field args = {field_name: [] for field_name in field_names} for resolved_string in resolved_strings: for field, value in reverse_format(format_string, resolved_string).items(): args[field].append(value) return args
python
def reverse_formats(format_string, resolved_strings): """ Reverse the string method format for a list of strings. Given format_string and resolved_strings, for each resolved string find arguments that would give ``format_string.format(**arguments) == resolved_string``. Each item in the output corresponds to a new column with the key setting the name and the values representing a mapping from list of resolved_strings to the related value. Parameters ---------- format_strings : str Format template string as used with str.format method resolved_strings : list List of strings with same pattern as format_string but with fields filled out. Returns ------- args : dict Dict of the form ``{field: [value_0, ..., value_n], ...}`` where values are in the same order as resolved_strings, so: ``format_sting.format(**{f: v[0] for f, v in args.items()}) == resolved_strings[0]`` Examples -------- >>> paths = ['data_2014_01_03.csv', 'data_2014_02_03.csv', 'data_2015_12_03.csv'] >>> reverse_formats('data_{year}_{month}_{day}.csv', paths) {'year': ['2014', '2014', '2015'], 'month': ['01', '02', '12'], 'day': ['03', '03', '03']} >>> reverse_formats('data_{year:d}_{month:d}_{day:d}.csv', paths) {'year': [2014, 2014, 2015], 'month': [1, 2, 12], 'day': [3, 3, 3]} >>> reverse_formats('data_{date:%Y_%m_%d}.csv', paths) {'date': [datetime.datetime(2014, 1, 3, 0, 0), datetime.datetime(2014, 2, 3, 0, 0), datetime.datetime(2015, 12, 3, 0, 0)]} >>> reverse_formats('{state:2}{zip:5}', ['PA19104', 'PA19143', 'MA02534']) {'state': ['PA', 'PA', 'MA'], 'zip': ['19104', '19143', '02534']} See also -------- str.format : method that this reverses reverse_format : method for reversing just one string using a pattern """ from string import Formatter fmt = Formatter() # get the fields from the format_string field_names = [i[1] for i in fmt.parse(format_string) if i[1]] # itialize the args dict with an empty dict for each field args = {field_name: [] for field_name in field_names} for resolved_string in resolved_strings: for field, value in reverse_format(format_string, resolved_string).items(): args[field].append(value) return args
[ "def", "reverse_formats", "(", "format_string", ",", "resolved_strings", ")", ":", "from", "string", "import", "Formatter", "fmt", "=", "Formatter", "(", ")", "# get the fields from the format_string", "field_names", "=", "[", "i", "[", "1", "]", "for", "i", "in", "fmt", ".", "parse", "(", "format_string", ")", "if", "i", "[", "1", "]", "]", "# itialize the args dict with an empty dict for each field", "args", "=", "{", "field_name", ":", "[", "]", "for", "field_name", "in", "field_names", "}", "for", "resolved_string", "in", "resolved_strings", ":", "for", "field", ",", "value", "in", "reverse_format", "(", "format_string", ",", "resolved_string", ")", ".", "items", "(", ")", ":", "args", "[", "field", "]", ".", "append", "(", "value", ")", "return", "args" ]
Reverse the string method format for a list of strings. Given format_string and resolved_strings, for each resolved string find arguments that would give ``format_string.format(**arguments) == resolved_string``. Each item in the output corresponds to a new column with the key setting the name and the values representing a mapping from list of resolved_strings to the related value. Parameters ---------- format_strings : str Format template string as used with str.format method resolved_strings : list List of strings with same pattern as format_string but with fields filled out. Returns ------- args : dict Dict of the form ``{field: [value_0, ..., value_n], ...}`` where values are in the same order as resolved_strings, so: ``format_sting.format(**{f: v[0] for f, v in args.items()}) == resolved_strings[0]`` Examples -------- >>> paths = ['data_2014_01_03.csv', 'data_2014_02_03.csv', 'data_2015_12_03.csv'] >>> reverse_formats('data_{year}_{month}_{day}.csv', paths) {'year': ['2014', '2014', '2015'], 'month': ['01', '02', '12'], 'day': ['03', '03', '03']} >>> reverse_formats('data_{year:d}_{month:d}_{day:d}.csv', paths) {'year': [2014, 2014, 2015], 'month': [1, 2, 12], 'day': [3, 3, 3]} >>> reverse_formats('data_{date:%Y_%m_%d}.csv', paths) {'date': [datetime.datetime(2014, 1, 3, 0, 0), datetime.datetime(2014, 2, 3, 0, 0), datetime.datetime(2015, 12, 3, 0, 0)]} >>> reverse_formats('{state:2}{zip:5}', ['PA19104', 'PA19143', 'MA02534']) {'state': ['PA', 'PA', 'MA'], 'zip': ['19104', '19143', '02534']} See also -------- str.format : method that this reverses reverse_format : method for reversing just one string using a pattern
[ "Reverse", "the", "string", "method", "format", "for", "a", "list", "of", "strings", "." ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/utils.py#L69-L131
229,433
intake/intake
intake/source/utils.py
reverse_format
def reverse_format(format_string, resolved_string): """ Reverse the string method format. Given format_string and resolved_string, find arguments that would give ``format_string.format(**arguments) == resolved_string`` Parameters ---------- format_string : str Format template string as used with str.format method resolved_string : str String with same pattern as format_string but with fields filled out. Returns ------- args : dict Dict of the form {field_name: value} such that ``format_string.(**args) == resolved_string`` Examples -------- >>> reverse_format('data_{year}_{month}_{day}.csv', 'data_2014_01_03.csv') {'year': '2014', 'month': '01', 'day': '03'} >>> reverse_format('data_{year:d}_{month:d}_{day:d}.csv', 'data_2014_01_03.csv') {'year': 2014, 'month': 1, 'day': 3} >>> reverse_format('data_{date:%Y_%m_%d}.csv', 'data_2016_10_01.csv') {'date': datetime.datetime(2016, 10, 1, 0, 0)} >>> reverse_format('{state:2}{zip:5}', 'PA19104') {'state': 'PA', 'zip': '19104'} See also -------- str.format : method that this reverses reverse_formats : method for reversing a list of strings using one pattern """ from string import Formatter from datetime import datetime fmt = Formatter() args = {} # ensure that format_string is in posix format format_string = make_path_posix(format_string) # split the string into bits literal_texts, field_names, format_specs, conversions = zip(*fmt.parse(format_string)) if not any(field_names): return {} for i, conversion in enumerate(conversions): if conversion: raise ValueError(('Conversion not allowed. Found on {}.' .format(field_names[i]))) # ensure that resolved string is in posix format resolved_string = make_path_posix(resolved_string) # get a list of the parts that matter bits = _get_parts_of_format_string(resolved_string, literal_texts, format_specs) for i, (field_name, format_spec) in enumerate(zip(field_names, format_specs)): if field_name: try: if format_spec.startswith('%'): args[field_name] = datetime.strptime(bits[i], format_spec) elif format_spec[-1] in list('bcdoxX'): args[field_name] = int(bits[i]) elif format_spec[-1] in list('eEfFgGn'): args[field_name] = float(bits[i]) elif format_spec[-1] == '%': args[field_name] = float(bits[i][:-1])/100 else: args[field_name] = fmt.format_field(bits[i], format_spec) except: args[field_name] = bits[i] return args
python
def reverse_format(format_string, resolved_string): """ Reverse the string method format. Given format_string and resolved_string, find arguments that would give ``format_string.format(**arguments) == resolved_string`` Parameters ---------- format_string : str Format template string as used with str.format method resolved_string : str String with same pattern as format_string but with fields filled out. Returns ------- args : dict Dict of the form {field_name: value} such that ``format_string.(**args) == resolved_string`` Examples -------- >>> reverse_format('data_{year}_{month}_{day}.csv', 'data_2014_01_03.csv') {'year': '2014', 'month': '01', 'day': '03'} >>> reverse_format('data_{year:d}_{month:d}_{day:d}.csv', 'data_2014_01_03.csv') {'year': 2014, 'month': 1, 'day': 3} >>> reverse_format('data_{date:%Y_%m_%d}.csv', 'data_2016_10_01.csv') {'date': datetime.datetime(2016, 10, 1, 0, 0)} >>> reverse_format('{state:2}{zip:5}', 'PA19104') {'state': 'PA', 'zip': '19104'} See also -------- str.format : method that this reverses reverse_formats : method for reversing a list of strings using one pattern """ from string import Formatter from datetime import datetime fmt = Formatter() args = {} # ensure that format_string is in posix format format_string = make_path_posix(format_string) # split the string into bits literal_texts, field_names, format_specs, conversions = zip(*fmt.parse(format_string)) if not any(field_names): return {} for i, conversion in enumerate(conversions): if conversion: raise ValueError(('Conversion not allowed. Found on {}.' .format(field_names[i]))) # ensure that resolved string is in posix format resolved_string = make_path_posix(resolved_string) # get a list of the parts that matter bits = _get_parts_of_format_string(resolved_string, literal_texts, format_specs) for i, (field_name, format_spec) in enumerate(zip(field_names, format_specs)): if field_name: try: if format_spec.startswith('%'): args[field_name] = datetime.strptime(bits[i], format_spec) elif format_spec[-1] in list('bcdoxX'): args[field_name] = int(bits[i]) elif format_spec[-1] in list('eEfFgGn'): args[field_name] = float(bits[i]) elif format_spec[-1] == '%': args[field_name] = float(bits[i][:-1])/100 else: args[field_name] = fmt.format_field(bits[i], format_spec) except: args[field_name] = bits[i] return args
[ "def", "reverse_format", "(", "format_string", ",", "resolved_string", ")", ":", "from", "string", "import", "Formatter", "from", "datetime", "import", "datetime", "fmt", "=", "Formatter", "(", ")", "args", "=", "{", "}", "# ensure that format_string is in posix format", "format_string", "=", "make_path_posix", "(", "format_string", ")", "# split the string into bits", "literal_texts", ",", "field_names", ",", "format_specs", ",", "conversions", "=", "zip", "(", "*", "fmt", ".", "parse", "(", "format_string", ")", ")", "if", "not", "any", "(", "field_names", ")", ":", "return", "{", "}", "for", "i", ",", "conversion", "in", "enumerate", "(", "conversions", ")", ":", "if", "conversion", ":", "raise", "ValueError", "(", "(", "'Conversion not allowed. Found on {}.'", ".", "format", "(", "field_names", "[", "i", "]", ")", ")", ")", "# ensure that resolved string is in posix format", "resolved_string", "=", "make_path_posix", "(", "resolved_string", ")", "# get a list of the parts that matter", "bits", "=", "_get_parts_of_format_string", "(", "resolved_string", ",", "literal_texts", ",", "format_specs", ")", "for", "i", ",", "(", "field_name", ",", "format_spec", ")", "in", "enumerate", "(", "zip", "(", "field_names", ",", "format_specs", ")", ")", ":", "if", "field_name", ":", "try", ":", "if", "format_spec", ".", "startswith", "(", "'%'", ")", ":", "args", "[", "field_name", "]", "=", "datetime", ".", "strptime", "(", "bits", "[", "i", "]", ",", "format_spec", ")", "elif", "format_spec", "[", "-", "1", "]", "in", "list", "(", "'bcdoxX'", ")", ":", "args", "[", "field_name", "]", "=", "int", "(", "bits", "[", "i", "]", ")", "elif", "format_spec", "[", "-", "1", "]", "in", "list", "(", "'eEfFgGn'", ")", ":", "args", "[", "field_name", "]", "=", "float", "(", "bits", "[", "i", "]", ")", "elif", "format_spec", "[", "-", "1", "]", "==", "'%'", ":", "args", "[", "field_name", "]", "=", "float", "(", "bits", "[", "i", "]", "[", ":", "-", "1", "]", ")", "/", "100", "else", ":", "args", "[", "field_name", "]", "=", "fmt", ".", "format_field", "(", "bits", "[", "i", "]", ",", "format_spec", ")", "except", ":", "args", "[", "field_name", "]", "=", "bits", "[", "i", "]", "return", "args" ]
Reverse the string method format. Given format_string and resolved_string, find arguments that would give ``format_string.format(**arguments) == resolved_string`` Parameters ---------- format_string : str Format template string as used with str.format method resolved_string : str String with same pattern as format_string but with fields filled out. Returns ------- args : dict Dict of the form {field_name: value} such that ``format_string.(**args) == resolved_string`` Examples -------- >>> reverse_format('data_{year}_{month}_{day}.csv', 'data_2014_01_03.csv') {'year': '2014', 'month': '01', 'day': '03'} >>> reverse_format('data_{year:d}_{month:d}_{day:d}.csv', 'data_2014_01_03.csv') {'year': 2014, 'month': 1, 'day': 3} >>> reverse_format('data_{date:%Y_%m_%d}.csv', 'data_2016_10_01.csv') {'date': datetime.datetime(2016, 10, 1, 0, 0)} >>> reverse_format('{state:2}{zip:5}', 'PA19104') {'state': 'PA', 'zip': '19104'} See also -------- str.format : method that this reverses reverse_formats : method for reversing a list of strings using one pattern
[ "Reverse", "the", "string", "method", "format", "." ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/utils.py#L134-L213
229,434
intake/intake
intake/source/utils.py
path_to_glob
def path_to_glob(path): """ Convert pattern style paths to glob style paths Returns path if path is not str Parameters ---------- path : str Path to data optionally containing format_strings Returns ------- glob : str Path with any format strings replaced with * Examples -------- >>> path_to_glob('{year}/{month}/{day}.csv') '*/*/*.csv' >>> path_to_glob('data/{year:4}{month:02}{day:02}.csv') 'data/*.csv' >>> path_to_glob('data/*.csv') 'data/*.csv' """ from string import Formatter fmt = Formatter() if not isinstance(path, str): return path # Get just the real bits of the urlpath literal_texts = [i[0] for i in fmt.parse(path)] # Only use a star for first empty string in literal_texts index_of_empty = [i for i, lt in enumerate(literal_texts) if lt == '' and i != 0] glob = '*'.join([literal_texts[i] for i in range(len(literal_texts)) if i not in index_of_empty]) return glob
python
def path_to_glob(path): """ Convert pattern style paths to glob style paths Returns path if path is not str Parameters ---------- path : str Path to data optionally containing format_strings Returns ------- glob : str Path with any format strings replaced with * Examples -------- >>> path_to_glob('{year}/{month}/{day}.csv') '*/*/*.csv' >>> path_to_glob('data/{year:4}{month:02}{day:02}.csv') 'data/*.csv' >>> path_to_glob('data/*.csv') 'data/*.csv' """ from string import Formatter fmt = Formatter() if not isinstance(path, str): return path # Get just the real bits of the urlpath literal_texts = [i[0] for i in fmt.parse(path)] # Only use a star for first empty string in literal_texts index_of_empty = [i for i, lt in enumerate(literal_texts) if lt == '' and i != 0] glob = '*'.join([literal_texts[i] for i in range(len(literal_texts)) if i not in index_of_empty]) return glob
[ "def", "path_to_glob", "(", "path", ")", ":", "from", "string", "import", "Formatter", "fmt", "=", "Formatter", "(", ")", "if", "not", "isinstance", "(", "path", ",", "str", ")", ":", "return", "path", "# Get just the real bits of the urlpath", "literal_texts", "=", "[", "i", "[", "0", "]", "for", "i", "in", "fmt", ".", "parse", "(", "path", ")", "]", "# Only use a star for first empty string in literal_texts", "index_of_empty", "=", "[", "i", "for", "i", ",", "lt", "in", "enumerate", "(", "literal_texts", ")", "if", "lt", "==", "''", "and", "i", "!=", "0", "]", "glob", "=", "'*'", ".", "join", "(", "[", "literal_texts", "[", "i", "]", "for", "i", "in", "range", "(", "len", "(", "literal_texts", ")", ")", "if", "i", "not", "in", "index_of_empty", "]", ")", "return", "glob" ]
Convert pattern style paths to glob style paths Returns path if path is not str Parameters ---------- path : str Path to data optionally containing format_strings Returns ------- glob : str Path with any format strings replaced with * Examples -------- >>> path_to_glob('{year}/{month}/{day}.csv') '*/*/*.csv' >>> path_to_glob('data/{year:4}{month:02}{day:02}.csv') 'data/*.csv' >>> path_to_glob('data/*.csv') 'data/*.csv'
[ "Convert", "pattern", "style", "paths", "to", "glob", "style", "paths" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/utils.py#L215-L255
229,435
intake/intake
intake/source/utils.py
path_to_pattern
def path_to_pattern(path, metadata=None): """ Remove source information from path when using chaching Returns None if path is not str Parameters ---------- path : str Path to data optionally containing format_strings metadata : dict, optional Extra arguments to the class, contains any cache information Returns ------- pattern : str Pattern style path stripped of everything to the left of cache regex. """ if not isinstance(path, str): return pattern = path if metadata: cache = metadata.get('cache') if cache: regex = next(c.get('regex') for c in cache if c.get('argkey') == 'urlpath') pattern = pattern.split(regex)[-1] return pattern
python
def path_to_pattern(path, metadata=None): """ Remove source information from path when using chaching Returns None if path is not str Parameters ---------- path : str Path to data optionally containing format_strings metadata : dict, optional Extra arguments to the class, contains any cache information Returns ------- pattern : str Pattern style path stripped of everything to the left of cache regex. """ if not isinstance(path, str): return pattern = path if metadata: cache = metadata.get('cache') if cache: regex = next(c.get('regex') for c in cache if c.get('argkey') == 'urlpath') pattern = pattern.split(regex)[-1] return pattern
[ "def", "path_to_pattern", "(", "path", ",", "metadata", "=", "None", ")", ":", "if", "not", "isinstance", "(", "path", ",", "str", ")", ":", "return", "pattern", "=", "path", "if", "metadata", ":", "cache", "=", "metadata", ".", "get", "(", "'cache'", ")", "if", "cache", ":", "regex", "=", "next", "(", "c", ".", "get", "(", "'regex'", ")", "for", "c", "in", "cache", "if", "c", ".", "get", "(", "'argkey'", ")", "==", "'urlpath'", ")", "pattern", "=", "pattern", ".", "split", "(", "regex", ")", "[", "-", "1", "]", "return", "pattern" ]
Remove source information from path when using chaching Returns None if path is not str Parameters ---------- path : str Path to data optionally containing format_strings metadata : dict, optional Extra arguments to the class, contains any cache information Returns ------- pattern : str Pattern style path stripped of everything to the left of cache regex.
[ "Remove", "source", "information", "from", "path", "when", "using", "chaching" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/utils.py#L258-L285
229,436
intake/intake
intake/container/base.py
get_partition
def get_partition(url, headers, source_id, container, partition): """Serializable function for fetching a data source partition Parameters ---------- url: str Server address headers: dict HTTP header parameters source_id: str ID of the source in the server's cache (unique per user) container: str Type of data, like "dataframe" one of ``intake.container.container_map`` partition: serializable Part of data to fetch, e.g., an integer for a dataframe. """ accepted_formats = list(serializer.format_registry.keys()) accepted_compression = list(serializer.compression_registry.keys()) payload = dict(action='read', source_id=source_id, accepted_formats=accepted_formats, accepted_compression=accepted_compression) if partition is not None: payload['partition'] = partition try: resp = requests.post(urljoin(url, '/v1/source'), data=msgpack.packb(payload, use_bin_type=True), **headers) if resp.status_code != 200: raise Exception('Error reading data') msg = msgpack.unpackb(resp.content, **unpack_kwargs) format = msg['format'] compression = msg['compression'] compressor = serializer.compression_registry[compression] encoder = serializer.format_registry[format] chunk = encoder.decode(compressor.decompress(msg['data']), container) return chunk finally: if resp is not None: resp.close()
python
def get_partition(url, headers, source_id, container, partition): """Serializable function for fetching a data source partition Parameters ---------- url: str Server address headers: dict HTTP header parameters source_id: str ID of the source in the server's cache (unique per user) container: str Type of data, like "dataframe" one of ``intake.container.container_map`` partition: serializable Part of data to fetch, e.g., an integer for a dataframe. """ accepted_formats = list(serializer.format_registry.keys()) accepted_compression = list(serializer.compression_registry.keys()) payload = dict(action='read', source_id=source_id, accepted_formats=accepted_formats, accepted_compression=accepted_compression) if partition is not None: payload['partition'] = partition try: resp = requests.post(urljoin(url, '/v1/source'), data=msgpack.packb(payload, use_bin_type=True), **headers) if resp.status_code != 200: raise Exception('Error reading data') msg = msgpack.unpackb(resp.content, **unpack_kwargs) format = msg['format'] compression = msg['compression'] compressor = serializer.compression_registry[compression] encoder = serializer.format_registry[format] chunk = encoder.decode(compressor.decompress(msg['data']), container) return chunk finally: if resp is not None: resp.close()
[ "def", "get_partition", "(", "url", ",", "headers", ",", "source_id", ",", "container", ",", "partition", ")", ":", "accepted_formats", "=", "list", "(", "serializer", ".", "format_registry", ".", "keys", "(", ")", ")", "accepted_compression", "=", "list", "(", "serializer", ".", "compression_registry", ".", "keys", "(", ")", ")", "payload", "=", "dict", "(", "action", "=", "'read'", ",", "source_id", "=", "source_id", ",", "accepted_formats", "=", "accepted_formats", ",", "accepted_compression", "=", "accepted_compression", ")", "if", "partition", "is", "not", "None", ":", "payload", "[", "'partition'", "]", "=", "partition", "try", ":", "resp", "=", "requests", ".", "post", "(", "urljoin", "(", "url", ",", "'/v1/source'", ")", ",", "data", "=", "msgpack", ".", "packb", "(", "payload", ",", "use_bin_type", "=", "True", ")", ",", "*", "*", "headers", ")", "if", "resp", ".", "status_code", "!=", "200", ":", "raise", "Exception", "(", "'Error reading data'", ")", "msg", "=", "msgpack", ".", "unpackb", "(", "resp", ".", "content", ",", "*", "*", "unpack_kwargs", ")", "format", "=", "msg", "[", "'format'", "]", "compression", "=", "msg", "[", "'compression'", "]", "compressor", "=", "serializer", ".", "compression_registry", "[", "compression", "]", "encoder", "=", "serializer", ".", "format_registry", "[", "format", "]", "chunk", "=", "encoder", ".", "decode", "(", "compressor", ".", "decompress", "(", "msg", "[", "'data'", "]", ")", ",", "container", ")", "return", "chunk", "finally", ":", "if", "resp", "is", "not", "None", ":", "resp", ".", "close", "(", ")" ]
Serializable function for fetching a data source partition Parameters ---------- url: str Server address headers: dict HTTP header parameters source_id: str ID of the source in the server's cache (unique per user) container: str Type of data, like "dataframe" one of ``intake.container.container_map`` partition: serializable Part of data to fetch, e.g., an integer for a dataframe.
[ "Serializable", "function", "for", "fetching", "a", "data", "source", "partition" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/container/base.py#L81-L124
229,437
intake/intake
intake/catalog/utils.py
flatten
def flatten(iterable): """Flatten an arbitrarily deep list""" # likely not used iterable = iter(iterable) while True: try: item = next(iterable) except StopIteration: break if isinstance(item, six.string_types): yield item continue try: data = iter(item) iterable = itertools.chain(data, iterable) except: yield item
python
def flatten(iterable): """Flatten an arbitrarily deep list""" # likely not used iterable = iter(iterable) while True: try: item = next(iterable) except StopIteration: break if isinstance(item, six.string_types): yield item continue try: data = iter(item) iterable = itertools.chain(data, iterable) except: yield item
[ "def", "flatten", "(", "iterable", ")", ":", "# likely not used", "iterable", "=", "iter", "(", "iterable", ")", "while", "True", ":", "try", ":", "item", "=", "next", "(", "iterable", ")", "except", "StopIteration", ":", "break", "if", "isinstance", "(", "item", ",", "six", ".", "string_types", ")", ":", "yield", "item", "continue", "try", ":", "data", "=", "iter", "(", "item", ")", "iterable", "=", "itertools", ".", "chain", "(", "data", ",", "iterable", ")", "except", ":", "yield", "item" ]
Flatten an arbitrarily deep list
[ "Flatten", "an", "arbitrarily", "deep", "list" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/utils.py#L20-L38
229,438
intake/intake
intake/catalog/utils.py
clamp
def clamp(value, lower=0, upper=sys.maxsize): """Clamp float between given range""" return max(lower, min(upper, value))
python
def clamp(value, lower=0, upper=sys.maxsize): """Clamp float between given range""" return max(lower, min(upper, value))
[ "def", "clamp", "(", "value", ",", "lower", "=", "0", ",", "upper", "=", "sys", ".", "maxsize", ")", ":", "return", "max", "(", "lower", ",", "min", "(", "upper", ",", "value", ")", ")" ]
Clamp float between given range
[ "Clamp", "float", "between", "given", "range" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/utils.py#L50-L52
229,439
intake/intake
intake/catalog/utils.py
expand_templates
def expand_templates(pars, context, return_left=False, client=False, getenv=True, getshell=True): """ Render variables in context into the set of parameters with jinja2. For variables that are not strings, nothing happens. Parameters ---------- pars: dict values are strings containing some jinja2 controls context: dict values to use while rendering return_left: bool whether to return the set of variables in context that were not used in rendering parameters Returns ------- dict with the same keys as ``pars``, but updated values; optionally also return set of unused parameter names. """ all_vars = set(context) out = _expand(pars, context, all_vars, client, getenv, getshell) if return_left: return out, all_vars return out
python
def expand_templates(pars, context, return_left=False, client=False, getenv=True, getshell=True): """ Render variables in context into the set of parameters with jinja2. For variables that are not strings, nothing happens. Parameters ---------- pars: dict values are strings containing some jinja2 controls context: dict values to use while rendering return_left: bool whether to return the set of variables in context that were not used in rendering parameters Returns ------- dict with the same keys as ``pars``, but updated values; optionally also return set of unused parameter names. """ all_vars = set(context) out = _expand(pars, context, all_vars, client, getenv, getshell) if return_left: return out, all_vars return out
[ "def", "expand_templates", "(", "pars", ",", "context", ",", "return_left", "=", "False", ",", "client", "=", "False", ",", "getenv", "=", "True", ",", "getshell", "=", "True", ")", ":", "all_vars", "=", "set", "(", "context", ")", "out", "=", "_expand", "(", "pars", ",", "context", ",", "all_vars", ",", "client", ",", "getenv", ",", "getshell", ")", "if", "return_left", ":", "return", "out", ",", "all_vars", "return", "out" ]
Render variables in context into the set of parameters with jinja2. For variables that are not strings, nothing happens. Parameters ---------- pars: dict values are strings containing some jinja2 controls context: dict values to use while rendering return_left: bool whether to return the set of variables in context that were not used in rendering parameters Returns ------- dict with the same keys as ``pars``, but updated values; optionally also return set of unused parameter names.
[ "Render", "variables", "in", "context", "into", "the", "set", "of", "parameters", "with", "jinja2", "." ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/utils.py#L109-L135
229,440
intake/intake
intake/catalog/utils.py
merge_pars
def merge_pars(params, user_inputs, spec_pars, client=False, getenv=True, getshell=True): """Produce open arguments by merging various inputs This function is called in the context of a catalog entry, when finalising the arguments for instantiating the corresponding data source. The three sets of inputs to be considered are: - the arguments section of the original spec (params) - UserParameters associated with the entry (spec_pars) - explicit arguments provided at instantiation time, like entry(arg=value) (user_inputs) Both spec_pars and user_inputs can be considered as template variables and used in expanding string values in params. The default value of a spec_par, if given, may have embedded env and shell functions, which will be evaluated before use, if the default is used and the corresponding getenv/getsgell are set. Similarly, string value params will also have access to these functions within jinja template groups, as well as full jinja processing. Where a key exists in both the spec_pars and the user_inputs, the user_input wins. Where user_inputs contains keys not seen elsewhere, they are regarded as extra kwargs to pass to the data source. Where spec pars have the same name as keys in params, their type, max/min and allowed fields are used to validate the final values of the corresponding arguments. Parameters ---------- params : dict From the entry's original spec user_inputs : dict Provided by the user/calling function spec_pars : list of UserParameters Default and validation instances client : bool Whether this is all running on a client to a remote server - sets which of the env/shell functions are in operation. getenv : bool Whether to allow pulling environment variables. If False, the template blocks will pass through unevaluated getshell : bool Whether or not to allow executing of shell commands. If False, the template blocks will pass through unevaluated Returns ------- Final parameter dict """ context = params.copy() for par in spec_pars: val = user_inputs.get(par.name, par.default) if val is not None: if isinstance(val, six.string_types): val = expand_defaults(val, getenv=getenv, getshell=getshell, client=client) context[par.name] = par.validate(val) context.update({k: v for k, v in user_inputs.items() if k not in context}) out, left = expand_templates(params, context, True, client, getenv, getshell) context = {k: v for k, v in context.items() if k in left} for par in spec_pars: if par.name in context: # coerces to type context[par.name] = par.validate(context[par.name]) left.remove(par.name) params.update(out) user_inputs = expand_templates(user_inputs, context, False, client, getenv, getshell) params.update({k: v for k, v in user_inputs.items() if k in left}) params.pop('CATALOG_DIR') for k, v in params.copy().items(): # final validation/coersion for sp in [p for p in spec_pars if p.name == k]: params[k] = sp.validate(params[k]) return params
python
def merge_pars(params, user_inputs, spec_pars, client=False, getenv=True, getshell=True): """Produce open arguments by merging various inputs This function is called in the context of a catalog entry, when finalising the arguments for instantiating the corresponding data source. The three sets of inputs to be considered are: - the arguments section of the original spec (params) - UserParameters associated with the entry (spec_pars) - explicit arguments provided at instantiation time, like entry(arg=value) (user_inputs) Both spec_pars and user_inputs can be considered as template variables and used in expanding string values in params. The default value of a spec_par, if given, may have embedded env and shell functions, which will be evaluated before use, if the default is used and the corresponding getenv/getsgell are set. Similarly, string value params will also have access to these functions within jinja template groups, as well as full jinja processing. Where a key exists in both the spec_pars and the user_inputs, the user_input wins. Where user_inputs contains keys not seen elsewhere, they are regarded as extra kwargs to pass to the data source. Where spec pars have the same name as keys in params, their type, max/min and allowed fields are used to validate the final values of the corresponding arguments. Parameters ---------- params : dict From the entry's original spec user_inputs : dict Provided by the user/calling function spec_pars : list of UserParameters Default and validation instances client : bool Whether this is all running on a client to a remote server - sets which of the env/shell functions are in operation. getenv : bool Whether to allow pulling environment variables. If False, the template blocks will pass through unevaluated getshell : bool Whether or not to allow executing of shell commands. If False, the template blocks will pass through unevaluated Returns ------- Final parameter dict """ context = params.copy() for par in spec_pars: val = user_inputs.get(par.name, par.default) if val is not None: if isinstance(val, six.string_types): val = expand_defaults(val, getenv=getenv, getshell=getshell, client=client) context[par.name] = par.validate(val) context.update({k: v for k, v in user_inputs.items() if k not in context}) out, left = expand_templates(params, context, True, client, getenv, getshell) context = {k: v for k, v in context.items() if k in left} for par in spec_pars: if par.name in context: # coerces to type context[par.name] = par.validate(context[par.name]) left.remove(par.name) params.update(out) user_inputs = expand_templates(user_inputs, context, False, client, getenv, getshell) params.update({k: v for k, v in user_inputs.items() if k in left}) params.pop('CATALOG_DIR') for k, v in params.copy().items(): # final validation/coersion for sp in [p for p in spec_pars if p.name == k]: params[k] = sp.validate(params[k]) return params
[ "def", "merge_pars", "(", "params", ",", "user_inputs", ",", "spec_pars", ",", "client", "=", "False", ",", "getenv", "=", "True", ",", "getshell", "=", "True", ")", ":", "context", "=", "params", ".", "copy", "(", ")", "for", "par", "in", "spec_pars", ":", "val", "=", "user_inputs", ".", "get", "(", "par", ".", "name", ",", "par", ".", "default", ")", "if", "val", "is", "not", "None", ":", "if", "isinstance", "(", "val", ",", "six", ".", "string_types", ")", ":", "val", "=", "expand_defaults", "(", "val", ",", "getenv", "=", "getenv", ",", "getshell", "=", "getshell", ",", "client", "=", "client", ")", "context", "[", "par", ".", "name", "]", "=", "par", ".", "validate", "(", "val", ")", "context", ".", "update", "(", "{", "k", ":", "v", "for", "k", ",", "v", "in", "user_inputs", ".", "items", "(", ")", "if", "k", "not", "in", "context", "}", ")", "out", ",", "left", "=", "expand_templates", "(", "params", ",", "context", ",", "True", ",", "client", ",", "getenv", ",", "getshell", ")", "context", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "context", ".", "items", "(", ")", "if", "k", "in", "left", "}", "for", "par", "in", "spec_pars", ":", "if", "par", ".", "name", "in", "context", ":", "# coerces to type", "context", "[", "par", ".", "name", "]", "=", "par", ".", "validate", "(", "context", "[", "par", ".", "name", "]", ")", "left", ".", "remove", "(", "par", ".", "name", ")", "params", ".", "update", "(", "out", ")", "user_inputs", "=", "expand_templates", "(", "user_inputs", ",", "context", ",", "False", ",", "client", ",", "getenv", ",", "getshell", ")", "params", ".", "update", "(", "{", "k", ":", "v", "for", "k", ",", "v", "in", "user_inputs", ".", "items", "(", ")", "if", "k", "in", "left", "}", ")", "params", ".", "pop", "(", "'CATALOG_DIR'", ")", "for", "k", ",", "v", "in", "params", ".", "copy", "(", ")", ".", "items", "(", ")", ":", "# final validation/coersion", "for", "sp", "in", "[", "p", "for", "p", "in", "spec_pars", "if", "p", ".", "name", "==", "k", "]", ":", "params", "[", "k", "]", "=", "sp", ".", "validate", "(", "params", "[", "k", "]", ")", "return", "params" ]
Produce open arguments by merging various inputs This function is called in the context of a catalog entry, when finalising the arguments for instantiating the corresponding data source. The three sets of inputs to be considered are: - the arguments section of the original spec (params) - UserParameters associated with the entry (spec_pars) - explicit arguments provided at instantiation time, like entry(arg=value) (user_inputs) Both spec_pars and user_inputs can be considered as template variables and used in expanding string values in params. The default value of a spec_par, if given, may have embedded env and shell functions, which will be evaluated before use, if the default is used and the corresponding getenv/getsgell are set. Similarly, string value params will also have access to these functions within jinja template groups, as well as full jinja processing. Where a key exists in both the spec_pars and the user_inputs, the user_input wins. Where user_inputs contains keys not seen elsewhere, they are regarded as extra kwargs to pass to the data source. Where spec pars have the same name as keys in params, their type, max/min and allowed fields are used to validate the final values of the corresponding arguments. Parameters ---------- params : dict From the entry's original spec user_inputs : dict Provided by the user/calling function spec_pars : list of UserParameters Default and validation instances client : bool Whether this is all running on a client to a remote server - sets which of the env/shell functions are in operation. getenv : bool Whether to allow pulling environment variables. If False, the template blocks will pass through unevaluated getshell : bool Whether or not to allow executing of shell commands. If False, the template blocks will pass through unevaluated Returns ------- Final parameter dict
[ "Produce", "open", "arguments", "by", "merging", "various", "inputs" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/utils.py#L177-L257
229,441
intake/intake
intake/catalog/utils.py
coerce
def coerce(dtype, value): """ Convert a value to a specific type. If the value is already the given type, then the original value is returned. If the value is None, then the default value given by the type constructor is returned. Otherwise, the type constructor converts and returns the value. """ if dtype is None: return value if type(value).__name__ == dtype: return value op = COERCION_RULES[dtype] return op() if value is None else op(value)
python
def coerce(dtype, value): """ Convert a value to a specific type. If the value is already the given type, then the original value is returned. If the value is None, then the default value given by the type constructor is returned. Otherwise, the type constructor converts and returns the value. """ if dtype is None: return value if type(value).__name__ == dtype: return value op = COERCION_RULES[dtype] return op() if value is None else op(value)
[ "def", "coerce", "(", "dtype", ",", "value", ")", ":", "if", "dtype", "is", "None", ":", "return", "value", "if", "type", "(", "value", ")", ".", "__name__", "==", "dtype", ":", "return", "value", "op", "=", "COERCION_RULES", "[", "dtype", "]", "return", "op", "(", ")", "if", "value", "is", "None", "else", "op", "(", "value", ")" ]
Convert a value to a specific type. If the value is already the given type, then the original value is returned. If the value is None, then the default value given by the type constructor is returned. Otherwise, the type constructor converts and returns the value.
[ "Convert", "a", "value", "to", "a", "specific", "type", "." ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/utils.py#L276-L290
229,442
intake/intake
intake/catalog/remote.py
open_remote
def open_remote(url, entry, container, user_parameters, description, http_args, page_size=None, auth=None, getenv=None, getshell=None): """Create either local direct data source or remote streamed source""" from intake.container import container_map if url.startswith('intake://'): url = url[len('intake://'):] payload = dict(action='open', name=entry, parameters=user_parameters, available_plugins=list(plugin_registry.keys())) req = requests.post(urljoin(url, '/v1/source'), data=msgpack.packb(payload, use_bin_type=True), **http_args) if req.ok: response = msgpack.unpackb(req.content, **unpack_kwargs) if 'plugin' in response: pl = response['plugin'] pl = [pl] if isinstance(pl, str) else pl # Direct access for p in pl: if p in plugin_registry: source = plugin_registry[p](**response['args']) proxy = False break else: proxy = True else: proxy = True if proxy: response.pop('container') response.update({'name': entry, 'parameters': user_parameters}) if container == 'catalog': response.update({'auth': auth, 'getenv': getenv, 'getshell': getshell, 'page_size': page_size # TODO ttl? # TODO storage_options? }) source = container_map[container](url, http_args, **response) source.description = description return source else: raise Exception('Server error: %d, %s' % (req.status_code, req.reason))
python
def open_remote(url, entry, container, user_parameters, description, http_args, page_size=None, auth=None, getenv=None, getshell=None): """Create either local direct data source or remote streamed source""" from intake.container import container_map if url.startswith('intake://'): url = url[len('intake://'):] payload = dict(action='open', name=entry, parameters=user_parameters, available_plugins=list(plugin_registry.keys())) req = requests.post(urljoin(url, '/v1/source'), data=msgpack.packb(payload, use_bin_type=True), **http_args) if req.ok: response = msgpack.unpackb(req.content, **unpack_kwargs) if 'plugin' in response: pl = response['plugin'] pl = [pl] if isinstance(pl, str) else pl # Direct access for p in pl: if p in plugin_registry: source = plugin_registry[p](**response['args']) proxy = False break else: proxy = True else: proxy = True if proxy: response.pop('container') response.update({'name': entry, 'parameters': user_parameters}) if container == 'catalog': response.update({'auth': auth, 'getenv': getenv, 'getshell': getshell, 'page_size': page_size # TODO ttl? # TODO storage_options? }) source = container_map[container](url, http_args, **response) source.description = description return source else: raise Exception('Server error: %d, %s' % (req.status_code, req.reason))
[ "def", "open_remote", "(", "url", ",", "entry", ",", "container", ",", "user_parameters", ",", "description", ",", "http_args", ",", "page_size", "=", "None", ",", "auth", "=", "None", ",", "getenv", "=", "None", ",", "getshell", "=", "None", ")", ":", "from", "intake", ".", "container", "import", "container_map", "if", "url", ".", "startswith", "(", "'intake://'", ")", ":", "url", "=", "url", "[", "len", "(", "'intake://'", ")", ":", "]", "payload", "=", "dict", "(", "action", "=", "'open'", ",", "name", "=", "entry", ",", "parameters", "=", "user_parameters", ",", "available_plugins", "=", "list", "(", "plugin_registry", ".", "keys", "(", ")", ")", ")", "req", "=", "requests", ".", "post", "(", "urljoin", "(", "url", ",", "'/v1/source'", ")", ",", "data", "=", "msgpack", ".", "packb", "(", "payload", ",", "use_bin_type", "=", "True", ")", ",", "*", "*", "http_args", ")", "if", "req", ".", "ok", ":", "response", "=", "msgpack", ".", "unpackb", "(", "req", ".", "content", ",", "*", "*", "unpack_kwargs", ")", "if", "'plugin'", "in", "response", ":", "pl", "=", "response", "[", "'plugin'", "]", "pl", "=", "[", "pl", "]", "if", "isinstance", "(", "pl", ",", "str", ")", "else", "pl", "# Direct access", "for", "p", "in", "pl", ":", "if", "p", "in", "plugin_registry", ":", "source", "=", "plugin_registry", "[", "p", "]", "(", "*", "*", "response", "[", "'args'", "]", ")", "proxy", "=", "False", "break", "else", ":", "proxy", "=", "True", "else", ":", "proxy", "=", "True", "if", "proxy", ":", "response", ".", "pop", "(", "'container'", ")", "response", ".", "update", "(", "{", "'name'", ":", "entry", ",", "'parameters'", ":", "user_parameters", "}", ")", "if", "container", "==", "'catalog'", ":", "response", ".", "update", "(", "{", "'auth'", ":", "auth", ",", "'getenv'", ":", "getenv", ",", "'getshell'", ":", "getshell", ",", "'page_size'", ":", "page_size", "# TODO ttl?", "# TODO storage_options?", "}", ")", "source", "=", "container_map", "[", "container", "]", "(", "url", ",", "http_args", ",", "*", "*", "response", ")", "source", ".", "description", "=", "description", "return", "source", "else", ":", "raise", "Exception", "(", "'Server error: %d, %s'", "%", "(", "req", ".", "status_code", ",", "req", ".", "reason", ")", ")" ]
Create either local direct data source or remote streamed source
[ "Create", "either", "local", "direct", "data", "source", "or", "remote", "streamed", "source" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/remote.py#L92-L137
229,443
intake/intake
intake/container/semistructured.py
RemoteSequenceSource._persist
def _persist(source, path, encoder=None): """Save list to files using encoding encoder : None or one of str|json|pickle None is equivalent to str """ import posixpath from dask.bytes import open_files import dask import pickle import json from intake.source.textfiles import TextFilesSource encoder = {None: str, 'str': str, 'json': json.dumps, 'pickle': pickle.dumps}[encoder] try: b = source.to_dask() except NotImplementedError: import dask.bag as db b = db.from_sequence(source.read(), npartitions=1) files = open_files(posixpath.join(path, 'part.*'), mode='wt', num=b.npartitions) dwrite = dask.delayed(write_file) out = [dwrite(part, f, encoder) for part, f in zip(b.to_delayed(), files)] dask.compute(out) s = TextFilesSource(posixpath.join(path, 'part.*')) return s
python
def _persist(source, path, encoder=None): """Save list to files using encoding encoder : None or one of str|json|pickle None is equivalent to str """ import posixpath from dask.bytes import open_files import dask import pickle import json from intake.source.textfiles import TextFilesSource encoder = {None: str, 'str': str, 'json': json.dumps, 'pickle': pickle.dumps}[encoder] try: b = source.to_dask() except NotImplementedError: import dask.bag as db b = db.from_sequence(source.read(), npartitions=1) files = open_files(posixpath.join(path, 'part.*'), mode='wt', num=b.npartitions) dwrite = dask.delayed(write_file) out = [dwrite(part, f, encoder) for part, f in zip(b.to_delayed(), files)] dask.compute(out) s = TextFilesSource(posixpath.join(path, 'part.*')) return s
[ "def", "_persist", "(", "source", ",", "path", ",", "encoder", "=", "None", ")", ":", "import", "posixpath", "from", "dask", ".", "bytes", "import", "open_files", "import", "dask", "import", "pickle", "import", "json", "from", "intake", ".", "source", ".", "textfiles", "import", "TextFilesSource", "encoder", "=", "{", "None", ":", "str", ",", "'str'", ":", "str", ",", "'json'", ":", "json", ".", "dumps", ",", "'pickle'", ":", "pickle", ".", "dumps", "}", "[", "encoder", "]", "try", ":", "b", "=", "source", ".", "to_dask", "(", ")", "except", "NotImplementedError", ":", "import", "dask", ".", "bag", "as", "db", "b", "=", "db", ".", "from_sequence", "(", "source", ".", "read", "(", ")", ",", "npartitions", "=", "1", ")", "files", "=", "open_files", "(", "posixpath", ".", "join", "(", "path", ",", "'part.*'", ")", ",", "mode", "=", "'wt'", ",", "num", "=", "b", ".", "npartitions", ")", "dwrite", "=", "dask", ".", "delayed", "(", "write_file", ")", "out", "=", "[", "dwrite", "(", "part", ",", "f", ",", "encoder", ")", "for", "part", ",", "f", "in", "zip", "(", "b", ".", "to_delayed", "(", ")", ",", "files", ")", "]", "dask", ".", "compute", "(", "out", ")", "s", "=", "TextFilesSource", "(", "posixpath", ".", "join", "(", "path", ",", "'part.*'", ")", ")", "return", "s" ]
Save list to files using encoding encoder : None or one of str|json|pickle None is equivalent to str
[ "Save", "list", "to", "files", "using", "encoding" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/container/semistructured.py#L55-L81
229,444
intake/intake
intake/catalog/entry.py
CatalogEntry._ipython_display_
def _ipython_display_(self): """Display the entry as a rich object in an IPython session.""" contents = self.describe() display({ # noqa: F821 'application/json': contents, 'text/plain': pretty_describe(contents) }, metadata={ 'application/json': {'root': contents["name"]} }, raw=True)
python
def _ipython_display_(self): """Display the entry as a rich object in an IPython session.""" contents = self.describe() display({ # noqa: F821 'application/json': contents, 'text/plain': pretty_describe(contents) }, metadata={ 'application/json': {'root': contents["name"]} }, raw=True)
[ "def", "_ipython_display_", "(", "self", ")", ":", "contents", "=", "self", ".", "describe", "(", ")", "display", "(", "{", "# noqa: F821", "'application/json'", ":", "contents", ",", "'text/plain'", ":", "pretty_describe", "(", "contents", ")", "}", ",", "metadata", "=", "{", "'application/json'", ":", "{", "'root'", ":", "contents", "[", "\"name\"", "]", "}", "}", ",", "raw", "=", "True", ")" ]
Display the entry as a rich object in an IPython session.
[ "Display", "the", "entry", "as", "a", "rich", "object", "in", "an", "IPython", "session", "." ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/catalog/entry.py#L103-L111
229,445
intake/intake
intake/source/discovery.py
autodiscover
def autodiscover(path=None, plugin_prefix='intake_'): """Scan for Intake plugin packages and return a dict of plugins. This function searches path (or sys.path) for packages with names that start with plugin_prefix. Those modules will be imported and scanned for subclasses of intake.source.base.Plugin. Any subclasses found will be instantiated and returned in a dictionary, with the plugin's name attribute as the key. """ plugins = {} for importer, name, ispkg in pkgutil.iter_modules(path=path): if name.startswith(plugin_prefix): t = time.time() new_plugins = load_plugins_from_module(name) for plugin_name, plugin in new_plugins.items(): if plugin_name in plugins: orig_path = inspect.getfile(plugins[plugin_name]) new_path = inspect.getfile(plugin) warnings.warn('Plugin name collision for "%s" from' '\n %s' '\nand' '\n %s' '\nKeeping plugin from first location.' % (plugin_name, orig_path, new_path)) else: plugins[plugin_name] = plugin logger.debug("Import %s took: %7.2f s" % (name, time.time() - t)) return plugins
python
def autodiscover(path=None, plugin_prefix='intake_'): """Scan for Intake plugin packages and return a dict of plugins. This function searches path (or sys.path) for packages with names that start with plugin_prefix. Those modules will be imported and scanned for subclasses of intake.source.base.Plugin. Any subclasses found will be instantiated and returned in a dictionary, with the plugin's name attribute as the key. """ plugins = {} for importer, name, ispkg in pkgutil.iter_modules(path=path): if name.startswith(plugin_prefix): t = time.time() new_plugins = load_plugins_from_module(name) for plugin_name, plugin in new_plugins.items(): if plugin_name in plugins: orig_path = inspect.getfile(plugins[plugin_name]) new_path = inspect.getfile(plugin) warnings.warn('Plugin name collision for "%s" from' '\n %s' '\nand' '\n %s' '\nKeeping plugin from first location.' % (plugin_name, orig_path, new_path)) else: plugins[plugin_name] = plugin logger.debug("Import %s took: %7.2f s" % (name, time.time() - t)) return plugins
[ "def", "autodiscover", "(", "path", "=", "None", ",", "plugin_prefix", "=", "'intake_'", ")", ":", "plugins", "=", "{", "}", "for", "importer", ",", "name", ",", "ispkg", "in", "pkgutil", ".", "iter_modules", "(", "path", "=", "path", ")", ":", "if", "name", ".", "startswith", "(", "plugin_prefix", ")", ":", "t", "=", "time", ".", "time", "(", ")", "new_plugins", "=", "load_plugins_from_module", "(", "name", ")", "for", "plugin_name", ",", "plugin", "in", "new_plugins", ".", "items", "(", ")", ":", "if", "plugin_name", "in", "plugins", ":", "orig_path", "=", "inspect", ".", "getfile", "(", "plugins", "[", "plugin_name", "]", ")", "new_path", "=", "inspect", ".", "getfile", "(", "plugin", ")", "warnings", ".", "warn", "(", "'Plugin name collision for \"%s\" from'", "'\\n %s'", "'\\nand'", "'\\n %s'", "'\\nKeeping plugin from first location.'", "%", "(", "plugin_name", ",", "orig_path", ",", "new_path", ")", ")", "else", ":", "plugins", "[", "plugin_name", "]", "=", "plugin", "logger", ".", "debug", "(", "\"Import %s took: %7.2f s\"", "%", "(", "name", ",", "time", ".", "time", "(", ")", "-", "t", ")", ")", "return", "plugins" ]
Scan for Intake plugin packages and return a dict of plugins. This function searches path (or sys.path) for packages with names that start with plugin_prefix. Those modules will be imported and scanned for subclasses of intake.source.base.Plugin. Any subclasses found will be instantiated and returned in a dictionary, with the plugin's name attribute as the key.
[ "Scan", "for", "Intake", "plugin", "packages", "and", "return", "a", "dict", "of", "plugins", "." ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/discovery.py#L20-L51
229,446
intake/intake
intake/source/discovery.py
load_plugins_from_module
def load_plugins_from_module(module_name): """Imports a module and returns dictionary of discovered Intake plugins. Plugin classes are instantiated and added to the dictionary, keyed by the name attribute of the plugin object. """ plugins = {} try: if module_name.endswith('.py'): import imp mod = imp.load_source('module.name', module_name) else: mod = importlib.import_module(module_name) except Exception as e: logger.debug("Import module <{}> failed: {}".format(module_name, e)) return {} for _, cls in inspect.getmembers(mod, inspect.isclass): # Don't try to register plugins imported into this module elsewhere if issubclass(cls, (Catalog, DataSource)): plugins[cls.name] = cls return plugins
python
def load_plugins_from_module(module_name): """Imports a module and returns dictionary of discovered Intake plugins. Plugin classes are instantiated and added to the dictionary, keyed by the name attribute of the plugin object. """ plugins = {} try: if module_name.endswith('.py'): import imp mod = imp.load_source('module.name', module_name) else: mod = importlib.import_module(module_name) except Exception as e: logger.debug("Import module <{}> failed: {}".format(module_name, e)) return {} for _, cls in inspect.getmembers(mod, inspect.isclass): # Don't try to register plugins imported into this module elsewhere if issubclass(cls, (Catalog, DataSource)): plugins[cls.name] = cls return plugins
[ "def", "load_plugins_from_module", "(", "module_name", ")", ":", "plugins", "=", "{", "}", "try", ":", "if", "module_name", ".", "endswith", "(", "'.py'", ")", ":", "import", "imp", "mod", "=", "imp", ".", "load_source", "(", "'module.name'", ",", "module_name", ")", "else", ":", "mod", "=", "importlib", ".", "import_module", "(", "module_name", ")", "except", "Exception", "as", "e", ":", "logger", ".", "debug", "(", "\"Import module <{}> failed: {}\"", ".", "format", "(", "module_name", ",", "e", ")", ")", "return", "{", "}", "for", "_", ",", "cls", "in", "inspect", ".", "getmembers", "(", "mod", ",", "inspect", ".", "isclass", ")", ":", "# Don't try to register plugins imported into this module elsewhere", "if", "issubclass", "(", "cls", ",", "(", "Catalog", ",", "DataSource", ")", ")", ":", "plugins", "[", "cls", ".", "name", "]", "=", "cls", "return", "plugins" ]
Imports a module and returns dictionary of discovered Intake plugins. Plugin classes are instantiated and added to the dictionary, keyed by the name attribute of the plugin object.
[ "Imports", "a", "module", "and", "returns", "dictionary", "of", "discovered", "Intake", "plugins", "." ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/discovery.py#L54-L76
229,447
intake/intake
intake/source/csv.py
CSVSource._set_pattern_columns
def _set_pattern_columns(self, path_column): """Get a column of values for each field in pattern """ try: # CategoricalDtype allows specifying known categories when # creating objects. It was added in pandas 0.21.0. from pandas.api.types import CategoricalDtype _HAS_CDT = True except ImportError: _HAS_CDT = False col = self._dataframe[path_column] paths = col.cat.categories column_by_field = {field: col.cat.codes.map(dict(enumerate(values))).astype( "category" if not _HAS_CDT else CategoricalDtype(set(values)) ) for field, values in reverse_formats(self.pattern, paths).items() } self._dataframe = self._dataframe.assign(**column_by_field)
python
def _set_pattern_columns(self, path_column): """Get a column of values for each field in pattern """ try: # CategoricalDtype allows specifying known categories when # creating objects. It was added in pandas 0.21.0. from pandas.api.types import CategoricalDtype _HAS_CDT = True except ImportError: _HAS_CDT = False col = self._dataframe[path_column] paths = col.cat.categories column_by_field = {field: col.cat.codes.map(dict(enumerate(values))).astype( "category" if not _HAS_CDT else CategoricalDtype(set(values)) ) for field, values in reverse_formats(self.pattern, paths).items() } self._dataframe = self._dataframe.assign(**column_by_field)
[ "def", "_set_pattern_columns", "(", "self", ",", "path_column", ")", ":", "try", ":", "# CategoricalDtype allows specifying known categories when", "# creating objects. It was added in pandas 0.21.0.", "from", "pandas", ".", "api", ".", "types", "import", "CategoricalDtype", "_HAS_CDT", "=", "True", "except", "ImportError", ":", "_HAS_CDT", "=", "False", "col", "=", "self", ".", "_dataframe", "[", "path_column", "]", "paths", "=", "col", ".", "cat", ".", "categories", "column_by_field", "=", "{", "field", ":", "col", ".", "cat", ".", "codes", ".", "map", "(", "dict", "(", "enumerate", "(", "values", ")", ")", ")", ".", "astype", "(", "\"category\"", "if", "not", "_HAS_CDT", "else", "CategoricalDtype", "(", "set", "(", "values", ")", ")", ")", "for", "field", ",", "values", "in", "reverse_formats", "(", "self", ".", "pattern", ",", "paths", ")", ".", "items", "(", ")", "}", "self", ".", "_dataframe", "=", "self", ".", "_dataframe", ".", "assign", "(", "*", "*", "column_by_field", ")" ]
Get a column of values for each field in pattern
[ "Get", "a", "column", "of", "values", "for", "each", "field", "in", "pattern" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/csv.py#L58-L77
229,448
intake/intake
intake/source/csv.py
CSVSource._path_column
def _path_column(self): """Set ``include_path_column`` in csv_kwargs and returns path column name """ path_column = self._csv_kwargs.get('include_path_column') if path_column is None: # if path column name is not set by user, set to a unique string to # avoid conflicts path_column = unique_string() self._csv_kwargs['include_path_column'] = path_column elif isinstance(path_column, bool): path_column = 'path' self._csv_kwargs['include_path_column'] = path_column return path_column
python
def _path_column(self): """Set ``include_path_column`` in csv_kwargs and returns path column name """ path_column = self._csv_kwargs.get('include_path_column') if path_column is None: # if path column name is not set by user, set to a unique string to # avoid conflicts path_column = unique_string() self._csv_kwargs['include_path_column'] = path_column elif isinstance(path_column, bool): path_column = 'path' self._csv_kwargs['include_path_column'] = path_column return path_column
[ "def", "_path_column", "(", "self", ")", ":", "path_column", "=", "self", ".", "_csv_kwargs", ".", "get", "(", "'include_path_column'", ")", "if", "path_column", "is", "None", ":", "# if path column name is not set by user, set to a unique string to", "# avoid conflicts", "path_column", "=", "unique_string", "(", ")", "self", ".", "_csv_kwargs", "[", "'include_path_column'", "]", "=", "path_column", "elif", "isinstance", "(", "path_column", ",", "bool", ")", ":", "path_column", "=", "'path'", "self", ".", "_csv_kwargs", "[", "'include_path_column'", "]", "=", "path_column", "return", "path_column" ]
Set ``include_path_column`` in csv_kwargs and returns path column name
[ "Set", "include_path_column", "in", "csv_kwargs", "and", "returns", "path", "column", "name" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/csv.py#L79-L92
229,449
intake/intake
intake/source/csv.py
CSVSource._open_dataset
def _open_dataset(self, urlpath): """Open dataset using dask and use pattern fields to set new columns """ import dask.dataframe if self.pattern is None: self._dataframe = dask.dataframe.read_csv( urlpath, storage_options=self._storage_options, **self._csv_kwargs) return if not (DASK_VERSION >= '0.19.0'): raise ValueError("Your version of dask is '{}'. " "The ability to include filenames in read_csv output " "(``include_path_column``) was added in 0.19.0, so " "pattern urlpaths are not supported.".format(DASK_VERSION)) drop_path_column = 'include_path_column' not in self._csv_kwargs path_column = self._path_column() self._dataframe = dask.dataframe.read_csv( urlpath, storage_options=self._storage_options, **self._csv_kwargs) # add the new columns to the dataframe self._set_pattern_columns(path_column) if drop_path_column: self._dataframe = self._dataframe.drop([path_column], axis=1)
python
def _open_dataset(self, urlpath): """Open dataset using dask and use pattern fields to set new columns """ import dask.dataframe if self.pattern is None: self._dataframe = dask.dataframe.read_csv( urlpath, storage_options=self._storage_options, **self._csv_kwargs) return if not (DASK_VERSION >= '0.19.0'): raise ValueError("Your version of dask is '{}'. " "The ability to include filenames in read_csv output " "(``include_path_column``) was added in 0.19.0, so " "pattern urlpaths are not supported.".format(DASK_VERSION)) drop_path_column = 'include_path_column' not in self._csv_kwargs path_column = self._path_column() self._dataframe = dask.dataframe.read_csv( urlpath, storage_options=self._storage_options, **self._csv_kwargs) # add the new columns to the dataframe self._set_pattern_columns(path_column) if drop_path_column: self._dataframe = self._dataframe.drop([path_column], axis=1)
[ "def", "_open_dataset", "(", "self", ",", "urlpath", ")", ":", "import", "dask", ".", "dataframe", "if", "self", ".", "pattern", "is", "None", ":", "self", ".", "_dataframe", "=", "dask", ".", "dataframe", ".", "read_csv", "(", "urlpath", ",", "storage_options", "=", "self", ".", "_storage_options", ",", "*", "*", "self", ".", "_csv_kwargs", ")", "return", "if", "not", "(", "DASK_VERSION", ">=", "'0.19.0'", ")", ":", "raise", "ValueError", "(", "\"Your version of dask is '{}'. \"", "\"The ability to include filenames in read_csv output \"", "\"(``include_path_column``) was added in 0.19.0, so \"", "\"pattern urlpaths are not supported.\"", ".", "format", "(", "DASK_VERSION", ")", ")", "drop_path_column", "=", "'include_path_column'", "not", "in", "self", ".", "_csv_kwargs", "path_column", "=", "self", ".", "_path_column", "(", ")", "self", ".", "_dataframe", "=", "dask", ".", "dataframe", ".", "read_csv", "(", "urlpath", ",", "storage_options", "=", "self", ".", "_storage_options", ",", "*", "*", "self", ".", "_csv_kwargs", ")", "# add the new columns to the dataframe", "self", ".", "_set_pattern_columns", "(", "path_column", ")", "if", "drop_path_column", ":", "self", ".", "_dataframe", "=", "self", ".", "_dataframe", ".", "drop", "(", "[", "path_column", "]", ",", "axis", "=", "1", ")" ]
Open dataset using dask and use pattern fields to set new columns
[ "Open", "dataset", "using", "dask", "and", "use", "pattern", "fields", "to", "set", "new", "columns" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/csv.py#L94-L121
229,450
intake/intake
intake/gui/catalog/search.py
Search.do_search
def do_search(self, arg=None): """Do search and close panel""" new_cats = [] for cat in self.cats: new_cat = cat.search(self.inputs.text, depth=self.inputs.depth) if len(list(new_cat)) > 0: new_cats.append(new_cat) if len(new_cats) > 0: self.done_callback(new_cats) self.visible = False
python
def do_search(self, arg=None): """Do search and close panel""" new_cats = [] for cat in self.cats: new_cat = cat.search(self.inputs.text, depth=self.inputs.depth) if len(list(new_cat)) > 0: new_cats.append(new_cat) if len(new_cats) > 0: self.done_callback(new_cats) self.visible = False
[ "def", "do_search", "(", "self", ",", "arg", "=", "None", ")", ":", "new_cats", "=", "[", "]", "for", "cat", "in", "self", ".", "cats", ":", "new_cat", "=", "cat", ".", "search", "(", "self", ".", "inputs", ".", "text", ",", "depth", "=", "self", ".", "inputs", ".", "depth", ")", "if", "len", "(", "list", "(", "new_cat", ")", ")", ">", "0", ":", "new_cats", ".", "append", "(", "new_cat", ")", "if", "len", "(", "new_cats", ")", ">", "0", ":", "self", ".", "done_callback", "(", "new_cats", ")", "self", ".", "visible", "=", "False" ]
Do search and close panel
[ "Do", "search", "and", "close", "panel" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/gui/catalog/search.py#L126-L136
229,451
intake/intake
intake/container/ndarray.py
RemoteArray._persist
def _persist(source, path, component=None, storage_options=None, **kwargs): """Save array to local persistent store Makes a parquet dataset out of the data using zarr. This then becomes a data entry in the persisted datasets catalog. Only works locally for the moment. Parameters ---------- source: a DataSource instance to save name: str or None Key to refer to this persisted dataset by. If not given, will attempt to get from the source's name kwargs: passed on to zarr array creation, see """ from dask.array import to_zarr, from_array from ..source.zarr import ZarrArraySource try: arr = source.to_dask() except NotImplementedError: arr = from_array(source.read(), chunks=-1).rechunk('auto') to_zarr(arr, path, component=None, storage_options=storage_options, **kwargs) source = ZarrArraySource(path, storage_options, component) return source
python
def _persist(source, path, component=None, storage_options=None, **kwargs): """Save array to local persistent store Makes a parquet dataset out of the data using zarr. This then becomes a data entry in the persisted datasets catalog. Only works locally for the moment. Parameters ---------- source: a DataSource instance to save name: str or None Key to refer to this persisted dataset by. If not given, will attempt to get from the source's name kwargs: passed on to zarr array creation, see """ from dask.array import to_zarr, from_array from ..source.zarr import ZarrArraySource try: arr = source.to_dask() except NotImplementedError: arr = from_array(source.read(), chunks=-1).rechunk('auto') to_zarr(arr, path, component=None, storage_options=storage_options, **kwargs) source = ZarrArraySource(path, storage_options, component) return source
[ "def", "_persist", "(", "source", ",", "path", ",", "component", "=", "None", ",", "storage_options", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", "dask", ".", "array", "import", "to_zarr", ",", "from_array", "from", ".", ".", "source", ".", "zarr", "import", "ZarrArraySource", "try", ":", "arr", "=", "source", ".", "to_dask", "(", ")", "except", "NotImplementedError", ":", "arr", "=", "from_array", "(", "source", ".", "read", "(", ")", ",", "chunks", "=", "-", "1", ")", ".", "rechunk", "(", "'auto'", ")", "to_zarr", "(", "arr", ",", "path", ",", "component", "=", "None", ",", "storage_options", "=", "storage_options", ",", "*", "*", "kwargs", ")", "source", "=", "ZarrArraySource", "(", "path", ",", "storage_options", ",", "component", ")", "return", "source" ]
Save array to local persistent store Makes a parquet dataset out of the data using zarr. This then becomes a data entry in the persisted datasets catalog. Only works locally for the moment. Parameters ---------- source: a DataSource instance to save name: str or None Key to refer to this persisted dataset by. If not given, will attempt to get from the source's name kwargs: passed on to zarr array creation, see
[ "Save", "array", "to", "local", "persistent", "store" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/container/ndarray.py#L68-L94
229,452
intake/intake
intake/gui/source/defined_plots.py
DefinedPlots.source
def source(self, source): """When the source gets updated, update the the options in the selector""" BaseView.source.fset(self, source) if self.select: self.select.options = self.options
python
def source(self, source): """When the source gets updated, update the the options in the selector""" BaseView.source.fset(self, source) if self.select: self.select.options = self.options
[ "def", "source", "(", "self", ",", "source", ")", ":", "BaseView", ".", "source", ".", "fset", "(", "self", ",", "source", ")", "if", "self", ".", "select", ":", "self", ".", "select", ".", "options", "=", "self", ".", "options" ]
When the source gets updated, update the the options in the selector
[ "When", "the", "source", "gets", "updated", "update", "the", "the", "options", "in", "the", "selector" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/gui/source/defined_plots.py#L87-L91
229,453
intake/intake
intake/source/textfiles.py
get_file
def get_file(f, decoder, read): """Serializable function to take an OpenFile object and read lines""" with f as f: if decoder is None: return list(f) else: d = f.read() if read else f out = decoder(d) if isinstance(out, (tuple, list)): return out else: return [out]
python
def get_file(f, decoder, read): """Serializable function to take an OpenFile object and read lines""" with f as f: if decoder is None: return list(f) else: d = f.read() if read else f out = decoder(d) if isinstance(out, (tuple, list)): return out else: return [out]
[ "def", "get_file", "(", "f", ",", "decoder", ",", "read", ")", ":", "with", "f", "as", "f", ":", "if", "decoder", "is", "None", ":", "return", "list", "(", "f", ")", "else", ":", "d", "=", "f", ".", "read", "(", ")", "if", "read", "else", "f", "out", "=", "decoder", "(", "d", ")", "if", "isinstance", "(", "out", ",", "(", "tuple", ",", "list", ")", ")", ":", "return", "out", "else", ":", "return", "[", "out", "]" ]
Serializable function to take an OpenFile object and read lines
[ "Serializable", "function", "to", "take", "an", "OpenFile", "object", "and", "read", "lines" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/textfiles.py#L113-L124
229,454
intake/intake
intake/auth/base.py
BaseAuth.get_case_insensitive
def get_case_insensitive(self, dictionary, key, default=None): """Case-insensitive search of a dictionary for key. Returns the value if key match is found, otherwise default. """ lower_key = key.lower() for k, v in dictionary.items(): if lower_key == k.lower(): return v else: return default
python
def get_case_insensitive(self, dictionary, key, default=None): """Case-insensitive search of a dictionary for key. Returns the value if key match is found, otherwise default. """ lower_key = key.lower() for k, v in dictionary.items(): if lower_key == k.lower(): return v else: return default
[ "def", "get_case_insensitive", "(", "self", ",", "dictionary", ",", "key", ",", "default", "=", "None", ")", ":", "lower_key", "=", "key", ".", "lower", "(", ")", "for", "k", ",", "v", "in", "dictionary", ".", "items", "(", ")", ":", "if", "lower_key", "==", "k", ".", "lower", "(", ")", ":", "return", "v", "else", ":", "return", "default" ]
Case-insensitive search of a dictionary for key. Returns the value if key match is found, otherwise default.
[ "Case", "-", "insensitive", "search", "of", "a", "dictionary", "for", "key", "." ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/auth/base.py#L46-L56
229,455
intake/intake
intake/gui/catalog/add.py
FileSelector.url
def url(self): """Path to local catalog file""" return os.path.join(self.path, self.main.value[0])
python
def url(self): """Path to local catalog file""" return os.path.join(self.path, self.main.value[0])
[ "def", "url", "(", "self", ")", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "self", ".", "main", ".", "value", "[", "0", "]", ")" ]
Path to local catalog file
[ "Path", "to", "local", "catalog", "file" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/gui/catalog/add.py#L81-L83
229,456
intake/intake
intake/gui/catalog/add.py
FileSelector.validate
def validate(self, arg=None): """Check that inputted path is valid - set validator accordingly""" if os.path.isdir(self.path): self.validator.object = None else: self.validator.object = ICONS['error']
python
def validate(self, arg=None): """Check that inputted path is valid - set validator accordingly""" if os.path.isdir(self.path): self.validator.object = None else: self.validator.object = ICONS['error']
[ "def", "validate", "(", "self", ",", "arg", "=", "None", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "self", ".", "path", ")", ":", "self", ".", "validator", ".", "object", "=", "None", "else", ":", "self", ".", "validator", ".", "object", "=", "ICONS", "[", "'error'", "]" ]
Check that inputted path is valid - set validator accordingly
[ "Check", "that", "inputted", "path", "is", "valid", "-", "set", "validator", "accordingly" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/gui/catalog/add.py#L91-L96
229,457
intake/intake
intake/gui/catalog/add.py
CatAdder.add_cat
def add_cat(self, arg=None): """Add cat and close panel""" try: self.done_callback(self.cat) self.visible = False except Exception as e: self.validator.object = ICONS['error'] raise e
python
def add_cat(self, arg=None): """Add cat and close panel""" try: self.done_callback(self.cat) self.visible = False except Exception as e: self.validator.object = ICONS['error'] raise e
[ "def", "add_cat", "(", "self", ",", "arg", "=", "None", ")", ":", "try", ":", "self", ".", "done_callback", "(", "self", ".", "cat", ")", "self", ".", "visible", "=", "False", "except", "Exception", "as", "e", ":", "self", ".", "validator", ".", "object", "=", "ICONS", "[", "'error'", "]", "raise", "e" ]
Add cat and close panel
[ "Add", "cat", "and", "close", "panel" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/gui/catalog/add.py#L248-L255
229,458
intake/intake
intake/gui/catalog/add.py
CatAdder.tab_change
def tab_change(self, event): """When tab changes remove error, and enable widget if on url tab""" self.remove_error() if event.new == 1: self.widget.disabled = False
python
def tab_change(self, event): """When tab changes remove error, and enable widget if on url tab""" self.remove_error() if event.new == 1: self.widget.disabled = False
[ "def", "tab_change", "(", "self", ",", "event", ")", ":", "self", ".", "remove_error", "(", ")", "if", "event", ".", "new", "==", "1", ":", "self", ".", "widget", ".", "disabled", "=", "False" ]
When tab changes remove error, and enable widget if on url tab
[ "When", "tab", "changes", "remove", "error", "and", "enable", "widget", "if", "on", "url", "tab" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/gui/catalog/add.py#L261-L265
229,459
intake/intake
intake/gui/catalog/gui.py
CatGUI.callback
def callback(self, cats): """When a catalog is selected, enable widgets that depend on that condition and do done_callback""" enable = bool(cats) if not enable: # close search if it is visible self.search.visible = False enable_widget(self.search_widget, enable) enable_widget(self.remove_widget, enable) if self.done_callback: self.done_callback(cats)
python
def callback(self, cats): """When a catalog is selected, enable widgets that depend on that condition and do done_callback""" enable = bool(cats) if not enable: # close search if it is visible self.search.visible = False enable_widget(self.search_widget, enable) enable_widget(self.remove_widget, enable) if self.done_callback: self.done_callback(cats)
[ "def", "callback", "(", "self", ",", "cats", ")", ":", "enable", "=", "bool", "(", "cats", ")", "if", "not", "enable", ":", "# close search if it is visible", "self", ".", "search", ".", "visible", "=", "False", "enable_widget", "(", "self", ".", "search_widget", ",", "enable", ")", "enable_widget", "(", "self", ".", "remove_widget", ",", "enable", ")", "if", "self", ".", "done_callback", ":", "self", ".", "done_callback", "(", "cats", ")" ]
When a catalog is selected, enable widgets that depend on that condition and do done_callback
[ "When", "a", "catalog", "is", "selected", "enable", "widgets", "that", "depend", "on", "that", "condition", "and", "do", "done_callback" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/gui/catalog/gui.py#L119-L130
229,460
intake/intake
intake/gui/catalog/gui.py
CatGUI.on_click_search_widget
def on_click_search_widget(self, event): """ When the search control is toggled, set visibility and hand down cats""" self.search.cats = self.cats self.search.visible = event.new if self.search.visible: self.search.watchers.append( self.select.widget.link(self.search, value='cats'))
python
def on_click_search_widget(self, event): """ When the search control is toggled, set visibility and hand down cats""" self.search.cats = self.cats self.search.visible = event.new if self.search.visible: self.search.watchers.append( self.select.widget.link(self.search, value='cats'))
[ "def", "on_click_search_widget", "(", "self", ",", "event", ")", ":", "self", ".", "search", ".", "cats", "=", "self", ".", "cats", "self", ".", "search", ".", "visible", "=", "event", ".", "new", "if", "self", ".", "search", ".", "visible", ":", "self", ".", "search", ".", "watchers", ".", "append", "(", "self", ".", "select", ".", "widget", ".", "link", "(", "self", ".", "search", ",", "value", "=", "'cats'", ")", ")" ]
When the search control is toggled, set visibility and hand down cats
[ "When", "the", "search", "control", "is", "toggled", "set", "visibility", "and", "hand", "down", "cats" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/gui/catalog/gui.py#L132-L138
229,461
intake/intake
intake/utils.py
no_duplicates_constructor
def no_duplicates_constructor(loader, node, deep=False): """Check for duplicate keys while loading YAML https://gist.github.com/pypt/94d747fe5180851196eb """ mapping = {} for key_node, value_node in node.value: key = loader.construct_object(key_node, deep=deep) value = loader.construct_object(value_node, deep=deep) if key in mapping: from intake.catalog.exceptions import DuplicateKeyError raise DuplicateKeyError("while constructing a mapping", node.start_mark, "found duplicate key (%s)" % key, key_node.start_mark) mapping[key] = value return loader.construct_mapping(node, deep)
python
def no_duplicates_constructor(loader, node, deep=False): """Check for duplicate keys while loading YAML https://gist.github.com/pypt/94d747fe5180851196eb """ mapping = {} for key_node, value_node in node.value: key = loader.construct_object(key_node, deep=deep) value = loader.construct_object(value_node, deep=deep) if key in mapping: from intake.catalog.exceptions import DuplicateKeyError raise DuplicateKeyError("while constructing a mapping", node.start_mark, "found duplicate key (%s)" % key, key_node.start_mark) mapping[key] = value return loader.construct_mapping(node, deep)
[ "def", "no_duplicates_constructor", "(", "loader", ",", "node", ",", "deep", "=", "False", ")", ":", "mapping", "=", "{", "}", "for", "key_node", ",", "value_node", "in", "node", ".", "value", ":", "key", "=", "loader", ".", "construct_object", "(", "key_node", ",", "deep", "=", "deep", ")", "value", "=", "loader", ".", "construct_object", "(", "value_node", ",", "deep", "=", "deep", ")", "if", "key", "in", "mapping", ":", "from", "intake", ".", "catalog", ".", "exceptions", "import", "DuplicateKeyError", "raise", "DuplicateKeyError", "(", "\"while constructing a mapping\"", ",", "node", ".", "start_mark", ",", "\"found duplicate key (%s)\"", "%", "key", ",", "key_node", ".", "start_mark", ")", "mapping", "[", "key", "]", "=", "value", "return", "loader", ".", "construct_mapping", "(", "node", ",", "deep", ")" ]
Check for duplicate keys while loading YAML https://gist.github.com/pypt/94d747fe5180851196eb
[ "Check", "for", "duplicate", "keys", "while", "loading", "YAML" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/utils.py#L20-L39
229,462
intake/intake
intake/utils.py
classname
def classname(ob): """Get the object's class's name as package.module.Class""" import inspect if inspect.isclass(ob): return '.'.join([ob.__module__, ob.__name__]) else: return '.'.join([ob.__class__.__module__, ob.__class__.__name__])
python
def classname(ob): """Get the object's class's name as package.module.Class""" import inspect if inspect.isclass(ob): return '.'.join([ob.__module__, ob.__name__]) else: return '.'.join([ob.__class__.__module__, ob.__class__.__name__])
[ "def", "classname", "(", "ob", ")", ":", "import", "inspect", "if", "inspect", ".", "isclass", "(", "ob", ")", ":", "return", "'.'", ".", "join", "(", "[", "ob", ".", "__module__", ",", "ob", ".", "__name__", "]", ")", "else", ":", "return", "'.'", ".", "join", "(", "[", "ob", ".", "__class__", ".", "__module__", ",", "ob", ".", "__class__", ".", "__name__", "]", ")" ]
Get the object's class's name as package.module.Class
[ "Get", "the", "object", "s", "class", "s", "name", "as", "package", ".", "module", ".", "Class" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/utils.py#L62-L68
229,463
intake/intake
intake/utils.py
pretty_describe
def pretty_describe(object, nestedness=0, indent=2): """Maintain dict ordering - but make string version prettier""" if not isinstance(object, dict): return str(object) sep = f'\n{" " * nestedness * indent}' out = sep.join((f'{k}: {pretty_describe(v, nestedness + 1)}' for k, v in object.items())) if nestedness > 0 and out: return f'{sep}{out}' return out
python
def pretty_describe(object, nestedness=0, indent=2): """Maintain dict ordering - but make string version prettier""" if not isinstance(object, dict): return str(object) sep = f'\n{" " * nestedness * indent}' out = sep.join((f'{k}: {pretty_describe(v, nestedness + 1)}' for k, v in object.items())) if nestedness > 0 and out: return f'{sep}{out}' return out
[ "def", "pretty_describe", "(", "object", ",", "nestedness", "=", "0", ",", "indent", "=", "2", ")", ":", "if", "not", "isinstance", "(", "object", ",", "dict", ")", ":", "return", "str", "(", "object", ")", "sep", "=", "f'\\n{\" \" * nestedness * indent}'", "out", "=", "sep", ".", "join", "(", "(", "f'{k}: {pretty_describe(v, nestedness + 1)}'", "for", "k", ",", "v", "in", "object", ".", "items", "(", ")", ")", ")", "if", "nestedness", ">", "0", "and", "out", ":", "return", "f'{sep}{out}'", "return", "out" ]
Maintain dict ordering - but make string version prettier
[ "Maintain", "dict", "ordering", "-", "but", "make", "string", "version", "prettier" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/utils.py#L125-L133
229,464
intake/intake
intake/gui/gui.py
GUI.add
def add(self, *args, **kwargs): """Add to list of cats""" return self.cat.select.add(*args, **kwargs)
python
def add(self, *args, **kwargs): """Add to list of cats""" return self.cat.select.add(*args, **kwargs)
[ "def", "add", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "cat", ".", "select", ".", "add", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Add to list of cats
[ "Add", "to", "list", "of", "cats" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/gui/gui.py#L74-L76
229,465
intake/intake
intake/gui/base.py
coerce_to_list
def coerce_to_list(items, preprocess=None): """Given an instance or list, coerce to list. With optional preprocessing. """ if not isinstance(items, list): items = [items] if preprocess: items = list(map(preprocess, items)) return items
python
def coerce_to_list(items, preprocess=None): """Given an instance or list, coerce to list. With optional preprocessing. """ if not isinstance(items, list): items = [items] if preprocess: items = list(map(preprocess, items)) return items
[ "def", "coerce_to_list", "(", "items", ",", "preprocess", "=", "None", ")", ":", "if", "not", "isinstance", "(", "items", ",", "list", ")", ":", "items", "=", "[", "items", "]", "if", "preprocess", ":", "items", "=", "list", "(", "map", "(", "preprocess", ",", "items", ")", ")", "return", "items" ]
Given an instance or list, coerce to list. With optional preprocessing.
[ "Given", "an", "instance", "or", "list", "coerce", "to", "list", "." ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/gui/base.py#L25-L34
229,466
intake/intake
intake/gui/base.py
Base._repr_mimebundle_
def _repr_mimebundle_(self, *args, **kwargs): """Display in a notebook or a server""" try: if self.logo: p = pn.Row( self.logo_panel, self.panel, margin=0) return p._repr_mimebundle_(*args, **kwargs) else: return self.panel._repr_mimebundle_(*args, **kwargs) except: raise RuntimeError("Panel does not seem to be set up properly")
python
def _repr_mimebundle_(self, *args, **kwargs): """Display in a notebook or a server""" try: if self.logo: p = pn.Row( self.logo_panel, self.panel, margin=0) return p._repr_mimebundle_(*args, **kwargs) else: return self.panel._repr_mimebundle_(*args, **kwargs) except: raise RuntimeError("Panel does not seem to be set up properly")
[ "def", "_repr_mimebundle_", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "if", "self", ".", "logo", ":", "p", "=", "pn", ".", "Row", "(", "self", ".", "logo_panel", ",", "self", ".", "panel", ",", "margin", "=", "0", ")", "return", "p", ".", "_repr_mimebundle_", "(", "*", "args", ",", "*", "*", "kwargs", ")", "else", ":", "return", "self", ".", "panel", ".", "_repr_mimebundle_", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", ":", "raise", "RuntimeError", "(", "\"Panel does not seem to be set up properly\"", ")" ]
Display in a notebook or a server
[ "Display", "in", "a", "notebook", "or", "a", "server" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/gui/base.py#L78-L90
229,467
intake/intake
intake/gui/base.py
Base.unwatch
def unwatch(self): """Get rid of any lingering watchers and remove from list""" if self.watchers is not None: unwatched = [] for watcher in self.watchers: watcher.inst.param.unwatch(watcher) unwatched.append(watcher) self.watchers = [w for w in self.watchers if w not in unwatched]
python
def unwatch(self): """Get rid of any lingering watchers and remove from list""" if self.watchers is not None: unwatched = [] for watcher in self.watchers: watcher.inst.param.unwatch(watcher) unwatched.append(watcher) self.watchers = [w for w in self.watchers if w not in unwatched]
[ "def", "unwatch", "(", "self", ")", ":", "if", "self", ".", "watchers", "is", "not", "None", ":", "unwatched", "=", "[", "]", "for", "watcher", "in", "self", ".", "watchers", ":", "watcher", ".", "inst", ".", "param", ".", "unwatch", "(", "watcher", ")", "unwatched", ".", "append", "(", "watcher", ")", "self", ".", "watchers", "=", "[", "w", "for", "w", "in", "self", ".", "watchers", "if", "w", "not", "in", "unwatched", "]" ]
Get rid of any lingering watchers and remove from list
[ "Get", "rid", "of", "any", "lingering", "watchers", "and", "remove", "from", "list" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/gui/base.py#L114-L121
229,468
intake/intake
intake/gui/base.py
BaseSelector._create_options
def _create_options(self, items): """Helper method to create options from list, or instance. Applies preprocess method if available to create a uniform output """ return OrderedDict(map(lambda x: (x.name, x), coerce_to_list(items, self.preprocess)))
python
def _create_options(self, items): """Helper method to create options from list, or instance. Applies preprocess method if available to create a uniform output """ return OrderedDict(map(lambda x: (x.name, x), coerce_to_list(items, self.preprocess)))
[ "def", "_create_options", "(", "self", ",", "items", ")", ":", "return", "OrderedDict", "(", "map", "(", "lambda", "x", ":", "(", "x", ".", "name", ",", "x", ")", ",", "coerce_to_list", "(", "items", ",", "self", ".", "preprocess", ")", ")", ")" ]
Helper method to create options from list, or instance. Applies preprocess method if available to create a uniform output
[ "Helper", "method", "to", "create", "options", "from", "list", "or", "instance", "." ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/gui/base.py#L175-L182
229,469
intake/intake
intake/gui/base.py
BaseSelector.options
def options(self, new): """Set options from list, or instance of named item Over-writes old options """ options = self._create_options(new) if self.widget.value: self.widget.set_param(options=options, value=list(options.values())[:1]) else: self.widget.options = options self.widget.value = list(options.values())[:1]
python
def options(self, new): """Set options from list, or instance of named item Over-writes old options """ options = self._create_options(new) if self.widget.value: self.widget.set_param(options=options, value=list(options.values())[:1]) else: self.widget.options = options self.widget.value = list(options.values())[:1]
[ "def", "options", "(", "self", ",", "new", ")", ":", "options", "=", "self", ".", "_create_options", "(", "new", ")", "if", "self", ".", "widget", ".", "value", ":", "self", ".", "widget", ".", "set_param", "(", "options", "=", "options", ",", "value", "=", "list", "(", "options", ".", "values", "(", ")", ")", "[", ":", "1", "]", ")", "else", ":", "self", ".", "widget", ".", "options", "=", "options", "self", ".", "widget", ".", "value", "=", "list", "(", "options", ".", "values", "(", ")", ")", "[", ":", "1", "]" ]
Set options from list, or instance of named item Over-writes old options
[ "Set", "options", "from", "list", "or", "instance", "of", "named", "item" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/gui/base.py#L190-L200
229,470
intake/intake
intake/gui/base.py
BaseSelector.add
def add(self, items): """Add items to options""" options = self._create_options(items) for k, v in options.items(): if k in self.labels and v not in self.items: options.pop(k) count = 0 while f'{k}_{count}' in self.labels: count += 1 options[f'{k}_{count}'] = v self.widget.options.update(options) self.widget.param.trigger('options') self.widget.value = list(options.values())[:1]
python
def add(self, items): """Add items to options""" options = self._create_options(items) for k, v in options.items(): if k in self.labels and v not in self.items: options.pop(k) count = 0 while f'{k}_{count}' in self.labels: count += 1 options[f'{k}_{count}'] = v self.widget.options.update(options) self.widget.param.trigger('options') self.widget.value = list(options.values())[:1]
[ "def", "add", "(", "self", ",", "items", ")", ":", "options", "=", "self", ".", "_create_options", "(", "items", ")", "for", "k", ",", "v", "in", "options", ".", "items", "(", ")", ":", "if", "k", "in", "self", ".", "labels", "and", "v", "not", "in", "self", ".", "items", ":", "options", ".", "pop", "(", "k", ")", "count", "=", "0", "while", "f'{k}_{count}'", "in", "self", ".", "labels", ":", "count", "+=", "1", "options", "[", "f'{k}_{count}'", "]", "=", "v", "self", ".", "widget", ".", "options", ".", "update", "(", "options", ")", "self", ".", "widget", ".", "param", ".", "trigger", "(", "'options'", ")", "self", ".", "widget", ".", "value", "=", "list", "(", "options", ".", "values", "(", ")", ")", "[", ":", "1", "]" ]
Add items to options
[ "Add", "items", "to", "options" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/gui/base.py#L202-L214
229,471
intake/intake
intake/gui/base.py
BaseSelector.remove
def remove(self, items): """Remove items from options""" items = coerce_to_list(items) new_options = {k: v for k, v in self.options.items() if v not in items} self.widget.options = new_options self.widget.param.trigger('options')
python
def remove(self, items): """Remove items from options""" items = coerce_to_list(items) new_options = {k: v for k, v in self.options.items() if v not in items} self.widget.options = new_options self.widget.param.trigger('options')
[ "def", "remove", "(", "self", ",", "items", ")", ":", "items", "=", "coerce_to_list", "(", "items", ")", "new_options", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "self", ".", "options", ".", "items", "(", ")", "if", "v", "not", "in", "items", "}", "self", ".", "widget", ".", "options", "=", "new_options", "self", ".", "widget", ".", "param", ".", "trigger", "(", "'options'", ")" ]
Remove items from options
[ "Remove", "items", "from", "options" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/gui/base.py#L216-L221
229,472
intake/intake
intake/gui/base.py
BaseSelector.selected
def selected(self, new): """Set selected from list or instance of object or name. Over-writes existing selection """ def preprocess(item): if isinstance(item, str): return self.options[item] return item items = coerce_to_list(new, preprocess) self.widget.value = items
python
def selected(self, new): """Set selected from list or instance of object or name. Over-writes existing selection """ def preprocess(item): if isinstance(item, str): return self.options[item] return item items = coerce_to_list(new, preprocess) self.widget.value = items
[ "def", "selected", "(", "self", ",", "new", ")", ":", "def", "preprocess", "(", "item", ")", ":", "if", "isinstance", "(", "item", ",", "str", ")", ":", "return", "self", ".", "options", "[", "item", "]", "return", "item", "items", "=", "coerce_to_list", "(", "new", ",", "preprocess", ")", "self", ".", "widget", ".", "value", "=", "items" ]
Set selected from list or instance of object or name. Over-writes existing selection
[ "Set", "selected", "from", "list", "or", "instance", "of", "object", "or", "name", "." ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/gui/base.py#L229-L239
229,473
intake/intake
intake/gui/base.py
BaseView.source
def source(self, source): """When the source gets updated, update the select widget""" if isinstance(source, list): # if source is a list, get first item or None source = source[0] if len(source) > 0 else None self._source = source
python
def source(self, source): """When the source gets updated, update the select widget""" if isinstance(source, list): # if source is a list, get first item or None source = source[0] if len(source) > 0 else None self._source = source
[ "def", "source", "(", "self", ",", "source", ")", ":", "if", "isinstance", "(", "source", ",", "list", ")", ":", "# if source is a list, get first item or None", "source", "=", "source", "[", "0", "]", "if", "len", "(", "source", ")", ">", "0", "else", "None", "self", ".", "_source", "=", "source" ]
When the source gets updated, update the select widget
[ "When", "the", "source", "gets", "updated", "update", "the", "select", "widget" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/gui/base.py#L268-L273
229,474
intake/intake
intake/gui/source/gui.py
SourceGUI.callback
def callback(self, sources): """When a source is selected, enable widgets that depend on that condition and do done_callback""" enable = bool(sources) if not enable: self.plot_widget.value = False enable_widget(self.plot_widget, enable) if self.done_callback: self.done_callback(sources)
python
def callback(self, sources): """When a source is selected, enable widgets that depend on that condition and do done_callback""" enable = bool(sources) if not enable: self.plot_widget.value = False enable_widget(self.plot_widget, enable) if self.done_callback: self.done_callback(sources)
[ "def", "callback", "(", "self", ",", "sources", ")", ":", "enable", "=", "bool", "(", "sources", ")", "if", "not", "enable", ":", "self", ".", "plot_widget", ".", "value", "=", "False", "enable_widget", "(", "self", ".", "plot_widget", ",", "enable", ")", "if", "self", ".", "done_callback", ":", "self", ".", "done_callback", "(", "sources", ")" ]
When a source is selected, enable widgets that depend on that condition and do done_callback
[ "When", "a", "source", "is", "selected", "enable", "widgets", "that", "depend", "on", "that", "condition", "and", "do", "done_callback" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/gui/source/gui.py#L112-L121
229,475
intake/intake
intake/gui/source/gui.py
SourceGUI.on_click_plot_widget
def on_click_plot_widget(self, event): """ When the plot control is toggled, set visibility and hand down source""" self.plot.source = self.sources self.plot.visible = event.new if self.plot.visible: self.plot.watchers.append( self.select.widget.link(self.plot, value='source'))
python
def on_click_plot_widget(self, event): """ When the plot control is toggled, set visibility and hand down source""" self.plot.source = self.sources self.plot.visible = event.new if self.plot.visible: self.plot.watchers.append( self.select.widget.link(self.plot, value='source'))
[ "def", "on_click_plot_widget", "(", "self", ",", "event", ")", ":", "self", ".", "plot", ".", "source", "=", "self", ".", "sources", "self", ".", "plot", ".", "visible", "=", "event", ".", "new", "if", "self", ".", "plot", ".", "visible", ":", "self", ".", "plot", ".", "watchers", ".", "append", "(", "self", ".", "select", ".", "widget", ".", "link", "(", "self", ".", "plot", ",", "value", "=", "'source'", ")", ")" ]
When the plot control is toggled, set visibility and hand down source
[ "When", "the", "plot", "control", "is", "toggled", "set", "visibility", "and", "hand", "down", "source" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/gui/source/gui.py#L123-L129
229,476
intake/intake
intake/source/cache.py
sanitize_path
def sanitize_path(path): """Utility for cleaning up paths.""" storage_option = infer_storage_options(path) protocol = storage_option['protocol'] if protocol in ('http', 'https'): # Most FSs remove the protocol but not HTTPFS. We need to strip # it to match properly. path = os.path.normpath(path.replace("{}://".format(protocol), '')) elif protocol == 'file': # Remove trailing slashes from file paths. path = os.path.normpath(path) # Remove colons path = path.replace(':', '') # Otherwise we just make sure that path is posix return make_path_posix(path)
python
def sanitize_path(path): """Utility for cleaning up paths.""" storage_option = infer_storage_options(path) protocol = storage_option['protocol'] if protocol in ('http', 'https'): # Most FSs remove the protocol but not HTTPFS. We need to strip # it to match properly. path = os.path.normpath(path.replace("{}://".format(protocol), '')) elif protocol == 'file': # Remove trailing slashes from file paths. path = os.path.normpath(path) # Remove colons path = path.replace(':', '') # Otherwise we just make sure that path is posix return make_path_posix(path)
[ "def", "sanitize_path", "(", "path", ")", ":", "storage_option", "=", "infer_storage_options", "(", "path", ")", "protocol", "=", "storage_option", "[", "'protocol'", "]", "if", "protocol", "in", "(", "'http'", ",", "'https'", ")", ":", "# Most FSs remove the protocol but not HTTPFS. We need to strip", "# it to match properly.", "path", "=", "os", ".", "path", ".", "normpath", "(", "path", ".", "replace", "(", "\"{}://\"", ".", "format", "(", "protocol", ")", ",", "''", ")", ")", "elif", "protocol", "==", "'file'", ":", "# Remove trailing slashes from file paths.", "path", "=", "os", ".", "path", ".", "normpath", "(", "path", ")", "# Remove colons", "path", "=", "path", ".", "replace", "(", "':'", ",", "''", ")", "# Otherwise we just make sure that path is posix", "return", "make_path_posix", "(", "path", ")" ]
Utility for cleaning up paths.
[ "Utility", "for", "cleaning", "up", "paths", "." ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/cache.py#L27-L43
229,477
intake/intake
intake/source/cache.py
_download
def _download(file_in, file_out, blocksize, output=False): """Read from input and write to output file in blocks""" with warnings.catch_warnings(): warnings.filterwarnings('ignore') if output: try: from tqdm.autonotebook import tqdm except ImportError: logger.warn("Cache progress bar requires tqdm to be installed:" " conda/pip install tqdm") output = False if output: try: file_size = file_in.fs.size(file_in.path) pbar_disabled = False except ValueError as err: logger.debug("File system error requesting size: {}".format(err)) file_size = 0 pbar_disabled = True for i in range(100): if i not in display: display.add(i) out = i break pbar = tqdm(total=file_size // 2 ** 20, leave=False, disable=pbar_disabled, position=out, desc=os.path.basename(file_out.path), mininterval=0.1, bar_format=r'{n}/|/{l_bar}') logger.debug("Caching {}".format(file_in.path)) with file_in as f1: with file_out as f2: data = True while data: data = f1.read(blocksize) f2.write(data) if output: pbar.update(len(data) // 2**20) if output: try: pbar.update(pbar.total - pbar.n) # force to full pbar.close() except Exception as e: logger.debug('tqdm exception: %s' % e) finally: display.remove(out)
python
def _download(file_in, file_out, blocksize, output=False): """Read from input and write to output file in blocks""" with warnings.catch_warnings(): warnings.filterwarnings('ignore') if output: try: from tqdm.autonotebook import tqdm except ImportError: logger.warn("Cache progress bar requires tqdm to be installed:" " conda/pip install tqdm") output = False if output: try: file_size = file_in.fs.size(file_in.path) pbar_disabled = False except ValueError as err: logger.debug("File system error requesting size: {}".format(err)) file_size = 0 pbar_disabled = True for i in range(100): if i not in display: display.add(i) out = i break pbar = tqdm(total=file_size // 2 ** 20, leave=False, disable=pbar_disabled, position=out, desc=os.path.basename(file_out.path), mininterval=0.1, bar_format=r'{n}/|/{l_bar}') logger.debug("Caching {}".format(file_in.path)) with file_in as f1: with file_out as f2: data = True while data: data = f1.read(blocksize) f2.write(data) if output: pbar.update(len(data) // 2**20) if output: try: pbar.update(pbar.total - pbar.n) # force to full pbar.close() except Exception as e: logger.debug('tqdm exception: %s' % e) finally: display.remove(out)
[ "def", "_download", "(", "file_in", ",", "file_out", ",", "blocksize", ",", "output", "=", "False", ")", ":", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "filterwarnings", "(", "'ignore'", ")", "if", "output", ":", "try", ":", "from", "tqdm", ".", "autonotebook", "import", "tqdm", "except", "ImportError", ":", "logger", ".", "warn", "(", "\"Cache progress bar requires tqdm to be installed:\"", "\" conda/pip install tqdm\"", ")", "output", "=", "False", "if", "output", ":", "try", ":", "file_size", "=", "file_in", ".", "fs", ".", "size", "(", "file_in", ".", "path", ")", "pbar_disabled", "=", "False", "except", "ValueError", "as", "err", ":", "logger", ".", "debug", "(", "\"File system error requesting size: {}\"", ".", "format", "(", "err", ")", ")", "file_size", "=", "0", "pbar_disabled", "=", "True", "for", "i", "in", "range", "(", "100", ")", ":", "if", "i", "not", "in", "display", ":", "display", ".", "add", "(", "i", ")", "out", "=", "i", "break", "pbar", "=", "tqdm", "(", "total", "=", "file_size", "//", "2", "**", "20", ",", "leave", "=", "False", ",", "disable", "=", "pbar_disabled", ",", "position", "=", "out", ",", "desc", "=", "os", ".", "path", ".", "basename", "(", "file_out", ".", "path", ")", ",", "mininterval", "=", "0.1", ",", "bar_format", "=", "r'{n}/|/{l_bar}'", ")", "logger", ".", "debug", "(", "\"Caching {}\"", ".", "format", "(", "file_in", ".", "path", ")", ")", "with", "file_in", "as", "f1", ":", "with", "file_out", "as", "f2", ":", "data", "=", "True", "while", "data", ":", "data", "=", "f1", ".", "read", "(", "blocksize", ")", "f2", ".", "write", "(", "data", ")", "if", "output", ":", "pbar", ".", "update", "(", "len", "(", "data", ")", "//", "2", "**", "20", ")", "if", "output", ":", "try", ":", "pbar", ".", "update", "(", "pbar", ".", "total", "-", "pbar", ".", "n", ")", "# force to full", "pbar", ".", "close", "(", ")", "except", "Exception", "as", "e", ":", "logger", ".", "debug", "(", "'tqdm exception: %s'", "%", "e", ")", "finally", ":", "display", ".", "remove", "(", "out", ")" ]
Read from input and write to output file in blocks
[ "Read", "from", "input", "and", "write", "to", "output", "file", "in", "blocks" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/cache.py#L259-L306
229,478
intake/intake
intake/source/cache.py
make_caches
def make_caches(driver, specs, catdir=None, cache_dir=None, storage_options={}): """ Creates Cache objects from the cache_specs provided in the catalog yaml file Parameters ---------- driver: str Name of the plugin that can load catalog entry specs: list Specification for caching the data source. """ if specs is None: return [] return [registry.get(spec['type'], FileCache)( driver, spec, catdir=catdir, cache_dir=cache_dir, storage_options=storage_options) for spec in specs]
python
def make_caches(driver, specs, catdir=None, cache_dir=None, storage_options={}): """ Creates Cache objects from the cache_specs provided in the catalog yaml file Parameters ---------- driver: str Name of the plugin that can load catalog entry specs: list Specification for caching the data source. """ if specs is None: return [] return [registry.get(spec['type'], FileCache)( driver, spec, catdir=catdir, cache_dir=cache_dir, storage_options=storage_options) for spec in specs]
[ "def", "make_caches", "(", "driver", ",", "specs", ",", "catdir", "=", "None", ",", "cache_dir", "=", "None", ",", "storage_options", "=", "{", "}", ")", ":", "if", "specs", "is", "None", ":", "return", "[", "]", "return", "[", "registry", ".", "get", "(", "spec", "[", "'type'", "]", ",", "FileCache", ")", "(", "driver", ",", "spec", ",", "catdir", "=", "catdir", ",", "cache_dir", "=", "cache_dir", ",", "storage_options", "=", "storage_options", ")", "for", "spec", "in", "specs", "]" ]
Creates Cache objects from the cache_specs provided in the catalog yaml file Parameters ---------- driver: str Name of the plugin that can load catalog entry specs: list Specification for caching the data source.
[ "Creates", "Cache", "objects", "from", "the", "cache_specs", "provided", "in", "the", "catalog", "yaml", "file" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/cache.py#L540-L557
229,479
intake/intake
intake/source/cache.py
BaseCache.load
def load(self, urlpath, output=None, **kwargs): """ Downloads data from a given url, generates a hashed filename, logs metadata, and caches it locally. Parameters ---------- urlpath: str, location of data May be a local path, or remote path if including a protocol specifier such as ``'s3://'``. May include glob wildcards. output: bool Whether to show progress bars; turn off for testing Returns ------- List of local cache_paths to be opened instead of the remote file(s). If caching is disable, the urlpath is returned. """ if conf.get('cache_disabled', False): return [urlpath] self.output = output if output is not None else conf.get( 'cache_download_progress', True) cache_paths = self._from_metadata(urlpath) if cache_paths is None: files_in, files_out = self._make_files(urlpath) self._load(files_in, files_out, urlpath) cache_paths = self._from_metadata(urlpath) return cache_paths
python
def load(self, urlpath, output=None, **kwargs): """ Downloads data from a given url, generates a hashed filename, logs metadata, and caches it locally. Parameters ---------- urlpath: str, location of data May be a local path, or remote path if including a protocol specifier such as ``'s3://'``. May include glob wildcards. output: bool Whether to show progress bars; turn off for testing Returns ------- List of local cache_paths to be opened instead of the remote file(s). If caching is disable, the urlpath is returned. """ if conf.get('cache_disabled', False): return [urlpath] self.output = output if output is not None else conf.get( 'cache_download_progress', True) cache_paths = self._from_metadata(urlpath) if cache_paths is None: files_in, files_out = self._make_files(urlpath) self._load(files_in, files_out, urlpath) cache_paths = self._from_metadata(urlpath) return cache_paths
[ "def", "load", "(", "self", ",", "urlpath", ",", "output", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "conf", ".", "get", "(", "'cache_disabled'", ",", "False", ")", ":", "return", "[", "urlpath", "]", "self", ".", "output", "=", "output", "if", "output", "is", "not", "None", "else", "conf", ".", "get", "(", "'cache_download_progress'", ",", "True", ")", "cache_paths", "=", "self", ".", "_from_metadata", "(", "urlpath", ")", "if", "cache_paths", "is", "None", ":", "files_in", ",", "files_out", "=", "self", ".", "_make_files", "(", "urlpath", ")", "self", ".", "_load", "(", "files_in", ",", "files_out", ",", "urlpath", ")", "cache_paths", "=", "self", ".", "_from_metadata", "(", "urlpath", ")", "return", "cache_paths" ]
Downloads data from a given url, generates a hashed filename, logs metadata, and caches it locally. Parameters ---------- urlpath: str, location of data May be a local path, or remote path if including a protocol specifier such as ``'s3://'``. May include glob wildcards. output: bool Whether to show progress bars; turn off for testing Returns ------- List of local cache_paths to be opened instead of the remote file(s). If caching is disable, the urlpath is returned.
[ "Downloads", "data", "from", "a", "given", "url", "generates", "a", "hashed", "filename", "logs", "metadata", "and", "caches", "it", "locally", "." ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/cache.py#L133-L162
229,480
intake/intake
intake/source/cache.py
BaseCache._load
def _load(self, files_in, files_out, urlpath, meta=True): """Download a set of files""" import dask out = [] outnames = [] for file_in, file_out in zip(files_in, files_out): cache_path = file_out.path outnames.append(cache_path) # If `_munge_path` did not find a match we want to avoid # writing to the urlpath. if cache_path == urlpath: continue if not os.path.isfile(cache_path): logger.debug("Caching file: {}".format(file_in.path)) logger.debug("Original path: {}".format(urlpath)) logger.debug("Cached at: {}".format(cache_path)) if meta: self._log_metadata(urlpath, file_in.path, cache_path) ddown = dask.delayed(_download) out.append(ddown(file_in, file_out, self.blocksize, self.output)) dask.compute(*out) return outnames
python
def _load(self, files_in, files_out, urlpath, meta=True): """Download a set of files""" import dask out = [] outnames = [] for file_in, file_out in zip(files_in, files_out): cache_path = file_out.path outnames.append(cache_path) # If `_munge_path` did not find a match we want to avoid # writing to the urlpath. if cache_path == urlpath: continue if not os.path.isfile(cache_path): logger.debug("Caching file: {}".format(file_in.path)) logger.debug("Original path: {}".format(urlpath)) logger.debug("Cached at: {}".format(cache_path)) if meta: self._log_metadata(urlpath, file_in.path, cache_path) ddown = dask.delayed(_download) out.append(ddown(file_in, file_out, self.blocksize, self.output)) dask.compute(*out) return outnames
[ "def", "_load", "(", "self", ",", "files_in", ",", "files_out", ",", "urlpath", ",", "meta", "=", "True", ")", ":", "import", "dask", "out", "=", "[", "]", "outnames", "=", "[", "]", "for", "file_in", ",", "file_out", "in", "zip", "(", "files_in", ",", "files_out", ")", ":", "cache_path", "=", "file_out", ".", "path", "outnames", ".", "append", "(", "cache_path", ")", "# If `_munge_path` did not find a match we want to avoid", "# writing to the urlpath.", "if", "cache_path", "==", "urlpath", ":", "continue", "if", "not", "os", ".", "path", ".", "isfile", "(", "cache_path", ")", ":", "logger", ".", "debug", "(", "\"Caching file: {}\"", ".", "format", "(", "file_in", ".", "path", ")", ")", "logger", ".", "debug", "(", "\"Original path: {}\"", ".", "format", "(", "urlpath", ")", ")", "logger", ".", "debug", "(", "\"Cached at: {}\"", ".", "format", "(", "cache_path", ")", ")", "if", "meta", ":", "self", ".", "_log_metadata", "(", "urlpath", ",", "file_in", ".", "path", ",", "cache_path", ")", "ddown", "=", "dask", ".", "delayed", "(", "_download", ")", "out", ".", "append", "(", "ddown", "(", "file_in", ",", "file_out", ",", "self", ".", "blocksize", ",", "self", ".", "output", ")", ")", "dask", ".", "compute", "(", "*", "out", ")", "return", "outnames" ]
Download a set of files
[ "Download", "a", "set", "of", "files" ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/cache.py#L170-L194
229,481
intake/intake
intake/source/cache.py
BaseCache.clear_cache
def clear_cache(self, urlpath): """ Clears cache and metadata for a given urlpath. Parameters ---------- urlpath: str, location of data May be a local path, or remote path if including a protocol specifier such as ``'s3://'``. May include glob wildcards. """ cache_entries = self._metadata.pop(urlpath, []) # ignore if missing for cache_entry in cache_entries: try: os.remove(cache_entry['cache_path']) except (OSError, IOError): pass try: fn = os.path.dirname(cache_entry['cache_path']) os.rmdir(fn) except (OSError, IOError): logger.debug("Failed to remove cache directory: %s" % fn)
python
def clear_cache(self, urlpath): """ Clears cache and metadata for a given urlpath. Parameters ---------- urlpath: str, location of data May be a local path, or remote path if including a protocol specifier such as ``'s3://'``. May include glob wildcards. """ cache_entries = self._metadata.pop(urlpath, []) # ignore if missing for cache_entry in cache_entries: try: os.remove(cache_entry['cache_path']) except (OSError, IOError): pass try: fn = os.path.dirname(cache_entry['cache_path']) os.rmdir(fn) except (OSError, IOError): logger.debug("Failed to remove cache directory: %s" % fn)
[ "def", "clear_cache", "(", "self", ",", "urlpath", ")", ":", "cache_entries", "=", "self", ".", "_metadata", ".", "pop", "(", "urlpath", ",", "[", "]", ")", "# ignore if missing", "for", "cache_entry", "in", "cache_entries", ":", "try", ":", "os", ".", "remove", "(", "cache_entry", "[", "'cache_path'", "]", ")", "except", "(", "OSError", ",", "IOError", ")", ":", "pass", "try", ":", "fn", "=", "os", ".", "path", ".", "dirname", "(", "cache_entry", "[", "'cache_path'", "]", ")", "os", ".", "rmdir", "(", "fn", ")", "except", "(", "OSError", ",", "IOError", ")", ":", "logger", ".", "debug", "(", "\"Failed to remove cache directory: %s\"", "%", "fn", ")" ]
Clears cache and metadata for a given urlpath. Parameters ---------- urlpath: str, location of data May be a local path, or remote path if including a protocol specifier such as ``'s3://'``. May include glob wildcards.
[ "Clears", "cache", "and", "metadata", "for", "a", "given", "urlpath", "." ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/cache.py#L215-L236
229,482
intake/intake
intake/source/cache.py
BaseCache.clear_all
def clear_all(self): """ Clears all cache and metadata. """ for urlpath in self._metadata.keys(): self.clear_cache(urlpath) # Safely clean up anything else. if not os.path.isdir(self._cache_dir): return for subdir in os.listdir(self._cache_dir): try: fn = posixpath.join(self._cache_dir, subdir) if os.path.isdir(fn): shutil.rmtree(fn) if os.path.isfile(fn): os.remove(fn) except (OSError, IOError) as e: logger.warning(str(e))
python
def clear_all(self): """ Clears all cache and metadata. """ for urlpath in self._metadata.keys(): self.clear_cache(urlpath) # Safely clean up anything else. if not os.path.isdir(self._cache_dir): return for subdir in os.listdir(self._cache_dir): try: fn = posixpath.join(self._cache_dir, subdir) if os.path.isdir(fn): shutil.rmtree(fn) if os.path.isfile(fn): os.remove(fn) except (OSError, IOError) as e: logger.warning(str(e))
[ "def", "clear_all", "(", "self", ")", ":", "for", "urlpath", "in", "self", ".", "_metadata", ".", "keys", "(", ")", ":", "self", ".", "clear_cache", "(", "urlpath", ")", "# Safely clean up anything else.", "if", "not", "os", ".", "path", ".", "isdir", "(", "self", ".", "_cache_dir", ")", ":", "return", "for", "subdir", "in", "os", ".", "listdir", "(", "self", ".", "_cache_dir", ")", ":", "try", ":", "fn", "=", "posixpath", ".", "join", "(", "self", ".", "_cache_dir", ",", "subdir", ")", "if", "os", ".", "path", ".", "isdir", "(", "fn", ")", ":", "shutil", ".", "rmtree", "(", "fn", ")", "if", "os", ".", "path", ".", "isfile", "(", "fn", ")", ":", "os", ".", "remove", "(", "fn", ")", "except", "(", "OSError", ",", "IOError", ")", "as", "e", ":", "logger", ".", "warning", "(", "str", "(", "e", ")", ")" ]
Clears all cache and metadata.
[ "Clears", "all", "cache", "and", "metadata", "." ]
277b96bfdee39d8a3048ea5408c6d6716d568336
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/cache.py#L238-L256
229,483
mottosso/Qt.py
membership.py
write_json
def write_json(dictionary, filename): """Write dictionary to JSON""" with open(filename, 'w') as data_file: json.dump(dictionary, data_file, indent=4, sort_keys=True) print('--> Wrote ' + os.path.basename(filename))
python
def write_json(dictionary, filename): """Write dictionary to JSON""" with open(filename, 'w') as data_file: json.dump(dictionary, data_file, indent=4, sort_keys=True) print('--> Wrote ' + os.path.basename(filename))
[ "def", "write_json", "(", "dictionary", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "data_file", ":", "json", ".", "dump", "(", "dictionary", ",", "data_file", ",", "indent", "=", "4", ",", "sort_keys", "=", "True", ")", "print", "(", "'--> Wrote '", "+", "os", ".", "path", ".", "basename", "(", "filename", ")", ")" ]
Write dictionary to JSON
[ "Write", "dictionary", "to", "JSON" ]
d88a0c1762ad90d1965008cc14c53504bbcc0061
https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/membership.py#L35-L39
229,484
mottosso/Qt.py
membership.py
compare
def compare(dicts): """Compare by iteration""" common_members = {} common_keys = reduce(lambda x, y: x & y, map(dict.keys, dicts)) for k in common_keys: common_members[k] = list( reduce(lambda x, y: x & y, [set(d[k]) for d in dicts])) return common_members
python
def compare(dicts): """Compare by iteration""" common_members = {} common_keys = reduce(lambda x, y: x & y, map(dict.keys, dicts)) for k in common_keys: common_members[k] = list( reduce(lambda x, y: x & y, [set(d[k]) for d in dicts])) return common_members
[ "def", "compare", "(", "dicts", ")", ":", "common_members", "=", "{", "}", "common_keys", "=", "reduce", "(", "lambda", "x", ",", "y", ":", "x", "&", "y", ",", "map", "(", "dict", ".", "keys", ",", "dicts", ")", ")", "for", "k", "in", "common_keys", ":", "common_members", "[", "k", "]", "=", "list", "(", "reduce", "(", "lambda", "x", ",", "y", ":", "x", "&", "y", ",", "[", "set", "(", "d", "[", "k", "]", ")", "for", "d", "in", "dicts", "]", ")", ")", "return", "common_members" ]
Compare by iteration
[ "Compare", "by", "iteration" ]
d88a0c1762ad90d1965008cc14c53504bbcc0061
https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/membership.py#L42-L51
229,485
mottosso/Qt.py
membership.py
sort_common_members
def sort_common_members(): """Sorts the keys and members""" filename = PREFIX + '/common_members.json' sorted_json_data = {} json_data = read_json(filename) all_keys = [] for key, value in json_data.items(): all_keys.append(key) sorted_keys = sorted(all_keys) for key in sorted_keys: if len(json_data[key]) > 0: # Only add modules which have common members sorted_json_data[key] = sorted(json_data[key]) print('--> Sorted/cleaned ' + os.path.basename(filename)) write_json(sorted_json_data, filename)
python
def sort_common_members(): """Sorts the keys and members""" filename = PREFIX + '/common_members.json' sorted_json_data = {} json_data = read_json(filename) all_keys = [] for key, value in json_data.items(): all_keys.append(key) sorted_keys = sorted(all_keys) for key in sorted_keys: if len(json_data[key]) > 0: # Only add modules which have common members sorted_json_data[key] = sorted(json_data[key]) print('--> Sorted/cleaned ' + os.path.basename(filename)) write_json(sorted_json_data, filename)
[ "def", "sort_common_members", "(", ")", ":", "filename", "=", "PREFIX", "+", "'/common_members.json'", "sorted_json_data", "=", "{", "}", "json_data", "=", "read_json", "(", "filename", ")", "all_keys", "=", "[", "]", "for", "key", ",", "value", "in", "json_data", ".", "items", "(", ")", ":", "all_keys", ".", "append", "(", "key", ")", "sorted_keys", "=", "sorted", "(", "all_keys", ")", "for", "key", "in", "sorted_keys", ":", "if", "len", "(", "json_data", "[", "key", "]", ")", ">", "0", ":", "# Only add modules which have common members", "sorted_json_data", "[", "key", "]", "=", "sorted", "(", "json_data", "[", "key", "]", ")", "print", "(", "'--> Sorted/cleaned '", "+", "os", ".", "path", ".", "basename", "(", "filename", ")", ")", "write_json", "(", "sorted_json_data", ",", "filename", ")" ]
Sorts the keys and members
[ "Sorts", "the", "keys", "and", "members" ]
d88a0c1762ad90d1965008cc14c53504bbcc0061
https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/membership.py#L77-L96
229,486
mottosso/Qt.py
membership.py
generate_common_members
def generate_common_members(): """Generate JSON with commonly shared members""" pyside = read_json(PREFIX + '/PySide.json') pyside2 = read_json(PREFIX + '/PySide2.json') pyqt4 = read_json(PREFIX + '/PyQt4.json') pyqt5 = read_json(PREFIX + '/PyQt5.json') dicts = [pyside, pyside2, pyqt4, pyqt5] common_members = compare(dicts) write_json(common_members, PREFIX + '/common_members.json')
python
def generate_common_members(): """Generate JSON with commonly shared members""" pyside = read_json(PREFIX + '/PySide.json') pyside2 = read_json(PREFIX + '/PySide2.json') pyqt4 = read_json(PREFIX + '/PyQt4.json') pyqt5 = read_json(PREFIX + '/PyQt5.json') dicts = [pyside, pyside2, pyqt4, pyqt5] common_members = compare(dicts) write_json(common_members, PREFIX + '/common_members.json')
[ "def", "generate_common_members", "(", ")", ":", "pyside", "=", "read_json", "(", "PREFIX", "+", "'/PySide.json'", ")", "pyside2", "=", "read_json", "(", "PREFIX", "+", "'/PySide2.json'", ")", "pyqt4", "=", "read_json", "(", "PREFIX", "+", "'/PyQt4.json'", ")", "pyqt5", "=", "read_json", "(", "PREFIX", "+", "'/PyQt5.json'", ")", "dicts", "=", "[", "pyside", ",", "pyside2", ",", "pyqt4", ",", "pyqt5", "]", "common_members", "=", "compare", "(", "dicts", ")", "write_json", "(", "common_members", ",", "PREFIX", "+", "'/common_members.json'", ")" ]
Generate JSON with commonly shared members
[ "Generate", "JSON", "with", "commonly", "shared", "members" ]
d88a0c1762ad90d1965008cc14c53504bbcc0061
https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/membership.py#L99-L109
229,487
mottosso/Qt.py
caveats.py
parse
def parse(fname): """Return blocks of code as list of dicts Arguments: fname (str): Relative name of caveats file """ blocks = list() with io.open(fname, "r", encoding="utf-8") as f: in_block = False current_block = None current_header = "" for line in f: # Doctests are within a quadruple hashtag header. if line.startswith("#### "): current_header = line.rstrip() # The actuat test is within a fenced block. if line.startswith("```"): in_block = False if in_block: current_block.append(line) if line.startswith("```python"): in_block = True current_block = list() current_block.append(current_header) blocks.append(current_block) tests = list() for block in blocks: header = ( block[0].strip("# ") # Remove Markdown .rstrip() # Remove newline .lower() # PEP08 ) # Remove unsupported characters header = re.sub(r"\W", "_", header) # Adding "untested" anywhere in the first line of # the doctest excludes it from the test. if "untested" in block[1].lower(): continue data = re.sub(" ", "", block[1]) # Remove spaces data = ( data.strip("#") .rstrip() # Remove newline .split(",") ) binding, doctest_version = (data + [None])[:2] # Run tests on both Python 2 and 3, unless explicitly stated if doctest_version is not None: if doctest_version not in ("Python2", "Python3"): raise SyntaxError( "Invalid Python version:\n%s\n" "Python version must follow binding, e.g.\n" "# PyQt5, Python3" % doctest_version) active_version = "Python%i" % sys.version_info[0] if doctest_version != active_version: continue tests.append({ "header": header, "binding": binding, "body": block[2:] }) return tests
python
def parse(fname): """Return blocks of code as list of dicts Arguments: fname (str): Relative name of caveats file """ blocks = list() with io.open(fname, "r", encoding="utf-8") as f: in_block = False current_block = None current_header = "" for line in f: # Doctests are within a quadruple hashtag header. if line.startswith("#### "): current_header = line.rstrip() # The actuat test is within a fenced block. if line.startswith("```"): in_block = False if in_block: current_block.append(line) if line.startswith("```python"): in_block = True current_block = list() current_block.append(current_header) blocks.append(current_block) tests = list() for block in blocks: header = ( block[0].strip("# ") # Remove Markdown .rstrip() # Remove newline .lower() # PEP08 ) # Remove unsupported characters header = re.sub(r"\W", "_", header) # Adding "untested" anywhere in the first line of # the doctest excludes it from the test. if "untested" in block[1].lower(): continue data = re.sub(" ", "", block[1]) # Remove spaces data = ( data.strip("#") .rstrip() # Remove newline .split(",") ) binding, doctest_version = (data + [None])[:2] # Run tests on both Python 2 and 3, unless explicitly stated if doctest_version is not None: if doctest_version not in ("Python2", "Python3"): raise SyntaxError( "Invalid Python version:\n%s\n" "Python version must follow binding, e.g.\n" "# PyQt5, Python3" % doctest_version) active_version = "Python%i" % sys.version_info[0] if doctest_version != active_version: continue tests.append({ "header": header, "binding": binding, "body": block[2:] }) return tests
[ "def", "parse", "(", "fname", ")", ":", "blocks", "=", "list", "(", ")", "with", "io", ".", "open", "(", "fname", ",", "\"r\"", ",", "encoding", "=", "\"utf-8\"", ")", "as", "f", ":", "in_block", "=", "False", "current_block", "=", "None", "current_header", "=", "\"\"", "for", "line", "in", "f", ":", "# Doctests are within a quadruple hashtag header.", "if", "line", ".", "startswith", "(", "\"#### \"", ")", ":", "current_header", "=", "line", ".", "rstrip", "(", ")", "# The actuat test is within a fenced block.", "if", "line", ".", "startswith", "(", "\"```\"", ")", ":", "in_block", "=", "False", "if", "in_block", ":", "current_block", ".", "append", "(", "line", ")", "if", "line", ".", "startswith", "(", "\"```python\"", ")", ":", "in_block", "=", "True", "current_block", "=", "list", "(", ")", "current_block", ".", "append", "(", "current_header", ")", "blocks", ".", "append", "(", "current_block", ")", "tests", "=", "list", "(", ")", "for", "block", "in", "blocks", ":", "header", "=", "(", "block", "[", "0", "]", ".", "strip", "(", "\"# \"", ")", "# Remove Markdown", ".", "rstrip", "(", ")", "# Remove newline", ".", "lower", "(", ")", "# PEP08", ")", "# Remove unsupported characters", "header", "=", "re", ".", "sub", "(", "r\"\\W\"", ",", "\"_\"", ",", "header", ")", "# Adding \"untested\" anywhere in the first line of", "# the doctest excludes it from the test.", "if", "\"untested\"", "in", "block", "[", "1", "]", ".", "lower", "(", ")", ":", "continue", "data", "=", "re", ".", "sub", "(", "\" \"", ",", "\"\"", ",", "block", "[", "1", "]", ")", "# Remove spaces", "data", "=", "(", "data", ".", "strip", "(", "\"#\"", ")", ".", "rstrip", "(", ")", "# Remove newline", ".", "split", "(", "\",\"", ")", ")", "binding", ",", "doctest_version", "=", "(", "data", "+", "[", "None", "]", ")", "[", ":", "2", "]", "# Run tests on both Python 2 and 3, unless explicitly stated", "if", "doctest_version", "is", "not", "None", ":", "if", "doctest_version", "not", "in", "(", "\"Python2\"", ",", "\"Python3\"", ")", ":", "raise", "SyntaxError", "(", "\"Invalid Python version:\\n%s\\n\"", "\"Python version must follow binding, e.g.\\n\"", "\"# PyQt5, Python3\"", "%", "doctest_version", ")", "active_version", "=", "\"Python%i\"", "%", "sys", ".", "version_info", "[", "0", "]", "if", "doctest_version", "!=", "active_version", ":", "continue", "tests", ".", "append", "(", "{", "\"header\"", ":", "header", ",", "\"binding\"", ":", "binding", ",", "\"body\"", ":", "block", "[", "2", ":", "]", "}", ")", "return", "tests" ]
Return blocks of code as list of dicts Arguments: fname (str): Relative name of caveats file
[ "Return", "blocks", "of", "code", "as", "list", "of", "dicts" ]
d88a0c1762ad90d1965008cc14c53504bbcc0061
https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/caveats.py#L6-L82
229,488
mottosso/Qt.py
Qt.py
_qInstallMessageHandler
def _qInstallMessageHandler(handler): """Install a message handler that works in all bindings Args: handler: A function that takes 3 arguments, or None """ def messageOutputHandler(*args): # In Qt4 bindings, message handlers are passed 2 arguments # In Qt5 bindings, message handlers are passed 3 arguments # The first argument is a QtMsgType # The last argument is the message to be printed # The Middle argument (if passed) is a QMessageLogContext if len(args) == 3: msgType, logContext, msg = args elif len(args) == 2: msgType, msg = args logContext = None else: raise TypeError( "handler expected 2 or 3 arguments, got {0}".format(len(args))) if isinstance(msg, bytes): # In python 3, some bindings pass a bytestring, which cannot be # used elsewhere. Decoding a python 2 or 3 bytestring object will # consistently return a unicode object. msg = msg.decode() handler(msgType, logContext, msg) passObject = messageOutputHandler if handler else handler if Qt.IsPySide or Qt.IsPyQt4: return Qt._QtCore.qInstallMsgHandler(passObject) elif Qt.IsPySide2 or Qt.IsPyQt5: return Qt._QtCore.qInstallMessageHandler(passObject)
python
def _qInstallMessageHandler(handler): """Install a message handler that works in all bindings Args: handler: A function that takes 3 arguments, or None """ def messageOutputHandler(*args): # In Qt4 bindings, message handlers are passed 2 arguments # In Qt5 bindings, message handlers are passed 3 arguments # The first argument is a QtMsgType # The last argument is the message to be printed # The Middle argument (if passed) is a QMessageLogContext if len(args) == 3: msgType, logContext, msg = args elif len(args) == 2: msgType, msg = args logContext = None else: raise TypeError( "handler expected 2 or 3 arguments, got {0}".format(len(args))) if isinstance(msg, bytes): # In python 3, some bindings pass a bytestring, which cannot be # used elsewhere. Decoding a python 2 or 3 bytestring object will # consistently return a unicode object. msg = msg.decode() handler(msgType, logContext, msg) passObject = messageOutputHandler if handler else handler if Qt.IsPySide or Qt.IsPyQt4: return Qt._QtCore.qInstallMsgHandler(passObject) elif Qt.IsPySide2 or Qt.IsPyQt5: return Qt._QtCore.qInstallMessageHandler(passObject)
[ "def", "_qInstallMessageHandler", "(", "handler", ")", ":", "def", "messageOutputHandler", "(", "*", "args", ")", ":", "# In Qt4 bindings, message handlers are passed 2 arguments", "# In Qt5 bindings, message handlers are passed 3 arguments", "# The first argument is a QtMsgType", "# The last argument is the message to be printed", "# The Middle argument (if passed) is a QMessageLogContext", "if", "len", "(", "args", ")", "==", "3", ":", "msgType", ",", "logContext", ",", "msg", "=", "args", "elif", "len", "(", "args", ")", "==", "2", ":", "msgType", ",", "msg", "=", "args", "logContext", "=", "None", "else", ":", "raise", "TypeError", "(", "\"handler expected 2 or 3 arguments, got {0}\"", ".", "format", "(", "len", "(", "args", ")", ")", ")", "if", "isinstance", "(", "msg", ",", "bytes", ")", ":", "# In python 3, some bindings pass a bytestring, which cannot be", "# used elsewhere. Decoding a python 2 or 3 bytestring object will", "# consistently return a unicode object.", "msg", "=", "msg", ".", "decode", "(", ")", "handler", "(", "msgType", ",", "logContext", ",", "msg", ")", "passObject", "=", "messageOutputHandler", "if", "handler", "else", "handler", "if", "Qt", ".", "IsPySide", "or", "Qt", ".", "IsPyQt4", ":", "return", "Qt", ".", "_QtCore", ".", "qInstallMsgHandler", "(", "passObject", ")", "elif", "Qt", ".", "IsPySide2", "or", "Qt", ".", "IsPyQt5", ":", "return", "Qt", ".", "_QtCore", ".", "qInstallMessageHandler", "(", "passObject", ")" ]
Install a message handler that works in all bindings Args: handler: A function that takes 3 arguments, or None
[ "Install", "a", "message", "handler", "that", "works", "in", "all", "bindings" ]
d88a0c1762ad90d1965008cc14c53504bbcc0061
https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/Qt.py#L683-L716
229,489
mottosso/Qt.py
Qt.py
_import_sub_module
def _import_sub_module(module, name): """import_sub_module will mimic the function of importlib.import_module""" module = __import__(module.__name__ + "." + name) for level in name.split("."): module = getattr(module, level) return module
python
def _import_sub_module(module, name): """import_sub_module will mimic the function of importlib.import_module""" module = __import__(module.__name__ + "." + name) for level in name.split("."): module = getattr(module, level) return module
[ "def", "_import_sub_module", "(", "module", ",", "name", ")", ":", "module", "=", "__import__", "(", "module", ".", "__name__", "+", "\".\"", "+", "name", ")", "for", "level", "in", "name", ".", "split", "(", "\".\"", ")", ":", "module", "=", "getattr", "(", "module", ",", "level", ")", "return", "module" ]
import_sub_module will mimic the function of importlib.import_module
[ "import_sub_module", "will", "mimic", "the", "function", "of", "importlib", ".", "import_module" ]
d88a0c1762ad90d1965008cc14c53504bbcc0061
https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/Qt.py#L1191-L1196
229,490
mottosso/Qt.py
Qt.py
_setup
def _setup(module, extras): """Install common submodules""" Qt.__binding__ = module.__name__ for name in list(_common_members) + extras: try: submodule = _import_sub_module( module, name) except ImportError: try: # For extra modules like sip and shiboken that may not be # children of the binding. submodule = __import__(name) except ImportError: continue setattr(Qt, "_" + name, submodule) if name not in extras: # Store reference to original binding, # but don't store speciality modules # such as uic or QtUiTools setattr(Qt, name, _new_module(name))
python
def _setup(module, extras): """Install common submodules""" Qt.__binding__ = module.__name__ for name in list(_common_members) + extras: try: submodule = _import_sub_module( module, name) except ImportError: try: # For extra modules like sip and shiboken that may not be # children of the binding. submodule = __import__(name) except ImportError: continue setattr(Qt, "_" + name, submodule) if name not in extras: # Store reference to original binding, # but don't store speciality modules # such as uic or QtUiTools setattr(Qt, name, _new_module(name))
[ "def", "_setup", "(", "module", ",", "extras", ")", ":", "Qt", ".", "__binding__", "=", "module", ".", "__name__", "for", "name", "in", "list", "(", "_common_members", ")", "+", "extras", ":", "try", ":", "submodule", "=", "_import_sub_module", "(", "module", ",", "name", ")", "except", "ImportError", ":", "try", ":", "# For extra modules like sip and shiboken that may not be", "# children of the binding.", "submodule", "=", "__import__", "(", "name", ")", "except", "ImportError", ":", "continue", "setattr", "(", "Qt", ",", "\"_\"", "+", "name", ",", "submodule", ")", "if", "name", "not", "in", "extras", ":", "# Store reference to original binding,", "# but don't store speciality modules", "# such as uic or QtUiTools", "setattr", "(", "Qt", ",", "name", ",", "_new_module", "(", "name", ")", ")" ]
Install common submodules
[ "Install", "common", "submodules" ]
d88a0c1762ad90d1965008cc14c53504bbcc0061
https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/Qt.py#L1199-L1222
229,491
mottosso/Qt.py
Qt.py
_build_compatibility_members
def _build_compatibility_members(binding, decorators=None): """Apply `binding` to QtCompat Arguments: binding (str): Top level binding in _compatibility_members. decorators (dict, optional): Provides the ability to decorate the original Qt methods when needed by a binding. This can be used to change the returned value to a standard value. The key should be the classname, the value is a dict where the keys are the target method names, and the values are the decorator functions. """ decorators = decorators or dict() # Allow optional site-level customization of the compatibility members. # This method does not need to be implemented in QtSiteConfig. try: import QtSiteConfig except ImportError: pass else: if hasattr(QtSiteConfig, 'update_compatibility_decorators'): QtSiteConfig.update_compatibility_decorators(binding, decorators) _QtCompat = type("QtCompat", (object,), {}) for classname, bindings in _compatibility_members[binding].items(): attrs = {} for target, binding in bindings.items(): namespaces = binding.split('.') try: src_object = getattr(Qt, "_" + namespaces[0]) except AttributeError as e: _log("QtCompat: AttributeError: %s" % e) # Skip reassignment of non-existing members. # This can happen if a request was made to # rename a member that didn't exist, for example # if QtWidgets isn't available on the target platform. continue # Walk down any remaining namespace getting the object assuming # that if the first namespace exists the rest will exist. for namespace in namespaces[1:]: src_object = getattr(src_object, namespace) # decorate the Qt method if a decorator was provided. if target in decorators.get(classname, []): # staticmethod must be called on the decorated method to # prevent a TypeError being raised when the decorated method # is called. src_object = staticmethod( decorators[classname][target](src_object)) attrs[target] = src_object # Create the QtCompat class and install it into the namespace compat_class = type(classname, (_QtCompat,), attrs) setattr(Qt.QtCompat, classname, compat_class)
python
def _build_compatibility_members(binding, decorators=None): """Apply `binding` to QtCompat Arguments: binding (str): Top level binding in _compatibility_members. decorators (dict, optional): Provides the ability to decorate the original Qt methods when needed by a binding. This can be used to change the returned value to a standard value. The key should be the classname, the value is a dict where the keys are the target method names, and the values are the decorator functions. """ decorators = decorators or dict() # Allow optional site-level customization of the compatibility members. # This method does not need to be implemented in QtSiteConfig. try: import QtSiteConfig except ImportError: pass else: if hasattr(QtSiteConfig, 'update_compatibility_decorators'): QtSiteConfig.update_compatibility_decorators(binding, decorators) _QtCompat = type("QtCompat", (object,), {}) for classname, bindings in _compatibility_members[binding].items(): attrs = {} for target, binding in bindings.items(): namespaces = binding.split('.') try: src_object = getattr(Qt, "_" + namespaces[0]) except AttributeError as e: _log("QtCompat: AttributeError: %s" % e) # Skip reassignment of non-existing members. # This can happen if a request was made to # rename a member that didn't exist, for example # if QtWidgets isn't available on the target platform. continue # Walk down any remaining namespace getting the object assuming # that if the first namespace exists the rest will exist. for namespace in namespaces[1:]: src_object = getattr(src_object, namespace) # decorate the Qt method if a decorator was provided. if target in decorators.get(classname, []): # staticmethod must be called on the decorated method to # prevent a TypeError being raised when the decorated method # is called. src_object = staticmethod( decorators[classname][target](src_object)) attrs[target] = src_object # Create the QtCompat class and install it into the namespace compat_class = type(classname, (_QtCompat,), attrs) setattr(Qt.QtCompat, classname, compat_class)
[ "def", "_build_compatibility_members", "(", "binding", ",", "decorators", "=", "None", ")", ":", "decorators", "=", "decorators", "or", "dict", "(", ")", "# Allow optional site-level customization of the compatibility members.", "# This method does not need to be implemented in QtSiteConfig.", "try", ":", "import", "QtSiteConfig", "except", "ImportError", ":", "pass", "else", ":", "if", "hasattr", "(", "QtSiteConfig", ",", "'update_compatibility_decorators'", ")", ":", "QtSiteConfig", ".", "update_compatibility_decorators", "(", "binding", ",", "decorators", ")", "_QtCompat", "=", "type", "(", "\"QtCompat\"", ",", "(", "object", ",", ")", ",", "{", "}", ")", "for", "classname", ",", "bindings", "in", "_compatibility_members", "[", "binding", "]", ".", "items", "(", ")", ":", "attrs", "=", "{", "}", "for", "target", ",", "binding", "in", "bindings", ".", "items", "(", ")", ":", "namespaces", "=", "binding", ".", "split", "(", "'.'", ")", "try", ":", "src_object", "=", "getattr", "(", "Qt", ",", "\"_\"", "+", "namespaces", "[", "0", "]", ")", "except", "AttributeError", "as", "e", ":", "_log", "(", "\"QtCompat: AttributeError: %s\"", "%", "e", ")", "# Skip reassignment of non-existing members.", "# This can happen if a request was made to", "# rename a member that didn't exist, for example", "# if QtWidgets isn't available on the target platform.", "continue", "# Walk down any remaining namespace getting the object assuming", "# that if the first namespace exists the rest will exist.", "for", "namespace", "in", "namespaces", "[", "1", ":", "]", ":", "src_object", "=", "getattr", "(", "src_object", ",", "namespace", ")", "# decorate the Qt method if a decorator was provided.", "if", "target", "in", "decorators", ".", "get", "(", "classname", ",", "[", "]", ")", ":", "# staticmethod must be called on the decorated method to", "# prevent a TypeError being raised when the decorated method", "# is called.", "src_object", "=", "staticmethod", "(", "decorators", "[", "classname", "]", "[", "target", "]", "(", "src_object", ")", ")", "attrs", "[", "target", "]", "=", "src_object", "# Create the QtCompat class and install it into the namespace", "compat_class", "=", "type", "(", "classname", ",", "(", "_QtCompat", ",", ")", ",", "attrs", ")", "setattr", "(", "Qt", ".", "QtCompat", ",", "classname", ",", "compat_class", ")" ]
Apply `binding` to QtCompat Arguments: binding (str): Top level binding in _compatibility_members. decorators (dict, optional): Provides the ability to decorate the original Qt methods when needed by a binding. This can be used to change the returned value to a standard value. The key should be the classname, the value is a dict where the keys are the target method names, and the values are the decorator functions.
[ "Apply", "binding", "to", "QtCompat" ]
d88a0c1762ad90d1965008cc14c53504bbcc0061
https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/Qt.py#L1297-L1355
229,492
mottosso/Qt.py
Qt.py
_convert
def _convert(lines): """Convert compiled .ui file from PySide2 to Qt.py Arguments: lines (list): Each line of of .ui file Usage: >> with open("myui.py") as f: .. lines = _convert(f.readlines()) """ def parse(line): line = line.replace("from PySide2 import", "from Qt import QtCompat,") line = line.replace("QtWidgets.QApplication.translate", "QtCompat.translate") if "QtCore.SIGNAL" in line: raise NotImplementedError("QtCore.SIGNAL is missing from PyQt5 " "and so Qt.py does not support it: you " "should avoid defining signals inside " "your ui files.") return line parsed = list() for line in lines: line = parse(line) parsed.append(line) return parsed
python
def _convert(lines): """Convert compiled .ui file from PySide2 to Qt.py Arguments: lines (list): Each line of of .ui file Usage: >> with open("myui.py") as f: .. lines = _convert(f.readlines()) """ def parse(line): line = line.replace("from PySide2 import", "from Qt import QtCompat,") line = line.replace("QtWidgets.QApplication.translate", "QtCompat.translate") if "QtCore.SIGNAL" in line: raise NotImplementedError("QtCore.SIGNAL is missing from PyQt5 " "and so Qt.py does not support it: you " "should avoid defining signals inside " "your ui files.") return line parsed = list() for line in lines: line = parse(line) parsed.append(line) return parsed
[ "def", "_convert", "(", "lines", ")", ":", "def", "parse", "(", "line", ")", ":", "line", "=", "line", ".", "replace", "(", "\"from PySide2 import\"", ",", "\"from Qt import QtCompat,\"", ")", "line", "=", "line", ".", "replace", "(", "\"QtWidgets.QApplication.translate\"", ",", "\"QtCompat.translate\"", ")", "if", "\"QtCore.SIGNAL\"", "in", "line", ":", "raise", "NotImplementedError", "(", "\"QtCore.SIGNAL is missing from PyQt5 \"", "\"and so Qt.py does not support it: you \"", "\"should avoid defining signals inside \"", "\"your ui files.\"", ")", "return", "line", "parsed", "=", "list", "(", ")", "for", "line", "in", "lines", ":", "line", "=", "parse", "(", "line", ")", "parsed", ".", "append", "(", "line", ")", "return", "parsed" ]
Convert compiled .ui file from PySide2 to Qt.py Arguments: lines (list): Each line of of .ui file Usage: >> with open("myui.py") as f: .. lines = _convert(f.readlines())
[ "Convert", "compiled", ".", "ui", "file", "from", "PySide2", "to", "Qt", ".", "py" ]
d88a0c1762ad90d1965008cc14c53504bbcc0061
https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/Qt.py#L1595-L1623
229,493
mottosso/Qt.py
examples/QtSiteConfig/QtSiteConfig.py
update_compatibility_decorators
def update_compatibility_decorators(binding, decorators): """ This optional function is called by Qt.py to modify the decorators applied to QtCompat namespace objects. Arguments: binding (str): The Qt binding being wrapped by Qt.py decorators (dict): Maps specific decorator functions to QtCompat namespace methods. See Qt._build_compatibility_members for more info. """ def _widgetDecorator(some_function): def wrapper(*args, **kwargs): ret = some_function(*args, **kwargs) # Modifies the returned value so we can test that the # decorator works. return "Test: {}".format(ret) # preserve docstring and name of original function wrapper.__doc__ = some_function.__doc__ wrapper.__name__ = some_function.__name__ return wrapper # Assign a different decorator for the same method name on each class def _mainWindowDecorator(some_function): def wrapper(*args, **kwargs): ret = some_function(*args, **kwargs) # Modifies the returned value so we can test that the # decorator works. return "QMainWindow Test: {}".format(ret) # preserve docstring and name of original function wrapper.__doc__ = some_function.__doc__ wrapper.__name__ = some_function.__name__ return wrapper decorators.setdefault("QWidget", {})["windowTitleDecorator"] = ( _widgetDecorator ) decorators.setdefault("QMainWindow", {})["windowTitleDecorator"] = ( _mainWindowDecorator )
python
def update_compatibility_decorators(binding, decorators): """ This optional function is called by Qt.py to modify the decorators applied to QtCompat namespace objects. Arguments: binding (str): The Qt binding being wrapped by Qt.py decorators (dict): Maps specific decorator functions to QtCompat namespace methods. See Qt._build_compatibility_members for more info. """ def _widgetDecorator(some_function): def wrapper(*args, **kwargs): ret = some_function(*args, **kwargs) # Modifies the returned value so we can test that the # decorator works. return "Test: {}".format(ret) # preserve docstring and name of original function wrapper.__doc__ = some_function.__doc__ wrapper.__name__ = some_function.__name__ return wrapper # Assign a different decorator for the same method name on each class def _mainWindowDecorator(some_function): def wrapper(*args, **kwargs): ret = some_function(*args, **kwargs) # Modifies the returned value so we can test that the # decorator works. return "QMainWindow Test: {}".format(ret) # preserve docstring and name of original function wrapper.__doc__ = some_function.__doc__ wrapper.__name__ = some_function.__name__ return wrapper decorators.setdefault("QWidget", {})["windowTitleDecorator"] = ( _widgetDecorator ) decorators.setdefault("QMainWindow", {})["windowTitleDecorator"] = ( _mainWindowDecorator )
[ "def", "update_compatibility_decorators", "(", "binding", ",", "decorators", ")", ":", "def", "_widgetDecorator", "(", "some_function", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "some_function", "(", "*", "args", ",", "*", "*", "kwargs", ")", "# Modifies the returned value so we can test that the", "# decorator works.", "return", "\"Test: {}\"", ".", "format", "(", "ret", ")", "# preserve docstring and name of original function", "wrapper", ".", "__doc__", "=", "some_function", ".", "__doc__", "wrapper", ".", "__name__", "=", "some_function", ".", "__name__", "return", "wrapper", "# Assign a different decorator for the same method name on each class", "def", "_mainWindowDecorator", "(", "some_function", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "some_function", "(", "*", "args", ",", "*", "*", "kwargs", ")", "# Modifies the returned value so we can test that the", "# decorator works.", "return", "\"QMainWindow Test: {}\"", ".", "format", "(", "ret", ")", "# preserve docstring and name of original function", "wrapper", ".", "__doc__", "=", "some_function", ".", "__doc__", "wrapper", ".", "__name__", "=", "some_function", ".", "__name__", "return", "wrapper", "decorators", ".", "setdefault", "(", "\"QWidget\"", ",", "{", "}", ")", "[", "\"windowTitleDecorator\"", "]", "=", "(", "_widgetDecorator", ")", "decorators", ".", "setdefault", "(", "\"QMainWindow\"", ",", "{", "}", ")", "[", "\"windowTitleDecorator\"", "]", "=", "(", "_mainWindowDecorator", ")" ]
This optional function is called by Qt.py to modify the decorators applied to QtCompat namespace objects. Arguments: binding (str): The Qt binding being wrapped by Qt.py decorators (dict): Maps specific decorator functions to QtCompat namespace methods. See Qt._build_compatibility_members for more info.
[ "This", "optional", "function", "is", "called", "by", "Qt", ".", "py", "to", "modify", "the", "decorators", "applied", "to", "QtCompat", "namespace", "objects", "." ]
d88a0c1762ad90d1965008cc14c53504bbcc0061
https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/examples/QtSiteConfig/QtSiteConfig.py#L53-L91
229,494
mottosso/Qt.py
examples/loadUi/baseinstance2.py
load_ui_type
def load_ui_type(uifile): """Pyside equivalent for the loadUiType function in PyQt. From the PyQt4 documentation: Load a Qt Designer .ui file and return a tuple of the generated form class and the Qt base class. These can then be used to create any number of instances of the user interface without having to parse the .ui file more than once. Note: Pyside lacks the "loadUiType" command, so we have to convert the ui file to py code in-memory first and then execute it in a special frame to retrieve the form_class. Args: uifile (str): Absolute path to .ui file Returns: tuple: the generated form class, the Qt base class """ import pysideuic import xml.etree.ElementTree as ElementTree from cStringIO import StringIO parsed = ElementTree.parse(uifile) widget_class = parsed.find('widget').get('class') form_class = parsed.find('class').text with open(uifile, 'r') as f: o = StringIO() frame = {} pysideuic.compileUi(f, o, indent=0) pyc = compile(o.getvalue(), '<string>', 'exec') exec(pyc) in frame # Fetch the base_class and form class based on their type in # the xml from designer form_class = frame['Ui_%s' % form_class] base_class = eval('QtWidgets.%s' % widget_class) return form_class, base_class
python
def load_ui_type(uifile): """Pyside equivalent for the loadUiType function in PyQt. From the PyQt4 documentation: Load a Qt Designer .ui file and return a tuple of the generated form class and the Qt base class. These can then be used to create any number of instances of the user interface without having to parse the .ui file more than once. Note: Pyside lacks the "loadUiType" command, so we have to convert the ui file to py code in-memory first and then execute it in a special frame to retrieve the form_class. Args: uifile (str): Absolute path to .ui file Returns: tuple: the generated form class, the Qt base class """ import pysideuic import xml.etree.ElementTree as ElementTree from cStringIO import StringIO parsed = ElementTree.parse(uifile) widget_class = parsed.find('widget').get('class') form_class = parsed.find('class').text with open(uifile, 'r') as f: o = StringIO() frame = {} pysideuic.compileUi(f, o, indent=0) pyc = compile(o.getvalue(), '<string>', 'exec') exec(pyc) in frame # Fetch the base_class and form class based on their type in # the xml from designer form_class = frame['Ui_%s' % form_class] base_class = eval('QtWidgets.%s' % widget_class) return form_class, base_class
[ "def", "load_ui_type", "(", "uifile", ")", ":", "import", "pysideuic", "import", "xml", ".", "etree", ".", "ElementTree", "as", "ElementTree", "from", "cStringIO", "import", "StringIO", "parsed", "=", "ElementTree", ".", "parse", "(", "uifile", ")", "widget_class", "=", "parsed", ".", "find", "(", "'widget'", ")", ".", "get", "(", "'class'", ")", "form_class", "=", "parsed", ".", "find", "(", "'class'", ")", ".", "text", "with", "open", "(", "uifile", ",", "'r'", ")", "as", "f", ":", "o", "=", "StringIO", "(", ")", "frame", "=", "{", "}", "pysideuic", ".", "compileUi", "(", "f", ",", "o", ",", "indent", "=", "0", ")", "pyc", "=", "compile", "(", "o", ".", "getvalue", "(", ")", ",", "'<string>'", ",", "'exec'", ")", "exec", "(", "pyc", ")", "in", "frame", "# Fetch the base_class and form class based on their type in", "# the xml from designer", "form_class", "=", "frame", "[", "'Ui_%s'", "%", "form_class", "]", "base_class", "=", "eval", "(", "'QtWidgets.%s'", "%", "widget_class", ")", "return", "form_class", ",", "base_class" ]
Pyside equivalent for the loadUiType function in PyQt. From the PyQt4 documentation: Load a Qt Designer .ui file and return a tuple of the generated form class and the Qt base class. These can then be used to create any number of instances of the user interface without having to parse the .ui file more than once. Note: Pyside lacks the "loadUiType" command, so we have to convert the ui file to py code in-memory first and then execute it in a special frame to retrieve the form_class. Args: uifile (str): Absolute path to .ui file Returns: tuple: the generated form class, the Qt base class
[ "Pyside", "equivalent", "for", "the", "loadUiType", "function", "in", "PyQt", "." ]
d88a0c1762ad90d1965008cc14c53504bbcc0061
https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/examples/loadUi/baseinstance2.py#L10-L51
229,495
mottosso/Qt.py
examples/loadUi/baseinstance2.py
pyside_load_ui
def pyside_load_ui(uifile, base_instance=None): """Provide PyQt4.uic.loadUi functionality to PySide Args: uifile (str): Absolute path to .ui file base_instance (QWidget): The widget into which UI widgets are loaded Note: pysideuic is required for this to work with PySide. This seems to work correctly in Maya as well as outside of it as opposed to other implementations which involve overriding QUiLoader. Returns: QWidget: the base instance """ form_class, base_class = load_ui_type(uifile) if not base_instance: typeName = form_class.__name__ finalType = type(typeName, (form_class, base_class), {}) base_instance = finalType() else: if not isinstance(base_instance, base_class): raise RuntimeError( 'The base_instance passed to loadUi does not inherit from' ' needed base type (%s)' % type(base_class)) typeName = type(base_instance).__name__ base_instance.__class__ = type(typeName, (form_class, type(base_instance)), {}) base_instance.setupUi(base_instance) return base_instance
python
def pyside_load_ui(uifile, base_instance=None): """Provide PyQt4.uic.loadUi functionality to PySide Args: uifile (str): Absolute path to .ui file base_instance (QWidget): The widget into which UI widgets are loaded Note: pysideuic is required for this to work with PySide. This seems to work correctly in Maya as well as outside of it as opposed to other implementations which involve overriding QUiLoader. Returns: QWidget: the base instance """ form_class, base_class = load_ui_type(uifile) if not base_instance: typeName = form_class.__name__ finalType = type(typeName, (form_class, base_class), {}) base_instance = finalType() else: if not isinstance(base_instance, base_class): raise RuntimeError( 'The base_instance passed to loadUi does not inherit from' ' needed base type (%s)' % type(base_class)) typeName = type(base_instance).__name__ base_instance.__class__ = type(typeName, (form_class, type(base_instance)), {}) base_instance.setupUi(base_instance) return base_instance
[ "def", "pyside_load_ui", "(", "uifile", ",", "base_instance", "=", "None", ")", ":", "form_class", ",", "base_class", "=", "load_ui_type", "(", "uifile", ")", "if", "not", "base_instance", ":", "typeName", "=", "form_class", ".", "__name__", "finalType", "=", "type", "(", "typeName", ",", "(", "form_class", ",", "base_class", ")", ",", "{", "}", ")", "base_instance", "=", "finalType", "(", ")", "else", ":", "if", "not", "isinstance", "(", "base_instance", ",", "base_class", ")", ":", "raise", "RuntimeError", "(", "'The base_instance passed to loadUi does not inherit from'", "' needed base type (%s)'", "%", "type", "(", "base_class", ")", ")", "typeName", "=", "type", "(", "base_instance", ")", ".", "__name__", "base_instance", ".", "__class__", "=", "type", "(", "typeName", ",", "(", "form_class", ",", "type", "(", "base_instance", ")", ")", ",", "{", "}", ")", "base_instance", ".", "setupUi", "(", "base_instance", ")", "return", "base_instance" ]
Provide PyQt4.uic.loadUi functionality to PySide Args: uifile (str): Absolute path to .ui file base_instance (QWidget): The widget into which UI widgets are loaded Note: pysideuic is required for this to work with PySide. This seems to work correctly in Maya as well as outside of it as opposed to other implementations which involve overriding QUiLoader. Returns: QWidget: the base instance
[ "Provide", "PyQt4", ".", "uic", ".", "loadUi", "functionality", "to", "PySide" ]
d88a0c1762ad90d1965008cc14c53504bbcc0061
https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/examples/loadUi/baseinstance2.py#L54-L89
229,496
Azure/azure-cosmos-python
samples/IndexManagement/Program.py
ExplicitlyExcludeFromIndex
def ExplicitlyExcludeFromIndex(client, database_id): """ The default index policy on a DocumentContainer will AUTOMATICALLY index ALL documents added. There may be scenarios where you want to exclude a specific doc from the index even though all other documents are being indexed automatically. This method demonstrates how to use an index directive to control this """ try: DeleteContainerIfExists(client, database_id, COLLECTION_ID) database_link = GetDatabaseLink(database_id) # collections = Query_Entities(client, 'collection', parent_link = database_link) # print(collections) # Create a collection with default index policy (i.e. automatic = true) created_Container = client.CreateContainer(database_link, {"id" : COLLECTION_ID}) print(created_Container) print("\n" + "-" * 25 + "\n1. Collection created with index policy") print_dictionary_items(created_Container["indexingPolicy"]) # Create a document and query on it immediately. # Will work as automatic indexing is still True collection_link = GetContainerLink(database_id, COLLECTION_ID) doc = client.CreateItem(collection_link, { "id" : "doc1", "orderId" : "order1" }) print("\n" + "-" * 25 + "Document doc1 created with order1" + "-" * 25) print(doc) query = { "query": "SELECT * FROM r WHERE r.orderId=@orderNo", "parameters": [ { "name":"@orderNo", "value": "order1" } ] } QueryDocumentsWithCustomQuery(client, collection_link, query) # Now, create a document but this time explictly exclude it from the collection using IndexingDirective # Then query for that document # Shoud NOT find it, because we excluded it from the index # BUT, the document is there and doing a ReadDocument by Id will prove it doc2 = client.CreateItem(collection_link, { "id" : "doc2", "orderId" : "order2" }, {'indexingDirective' : documents.IndexingDirective.Exclude}) print("\n" + "-" * 25 + "Document doc2 created with order2" + "-" * 25) print(doc2) query = { "query": "SELECT * FROM r WHERE r.orderId=@orderNo", "parameters": [ { "name":"@orderNo", "value": "order2" } ] } QueryDocumentsWithCustomQuery(client, collection_link, query) docRead = client.ReadItem(GetDocumentLink(database_id, COLLECTION_ID, "doc2")) print("Document read by ID: \n", docRead["id"]) # Cleanup client.DeleteContainer(collection_link) print("\n") except errors.HTTPFailure as e: if e.status_code == 409: print("Entity already exists") elif e.status_code == 404: print("Entity doesn't exist") else: raise
python
def ExplicitlyExcludeFromIndex(client, database_id): """ The default index policy on a DocumentContainer will AUTOMATICALLY index ALL documents added. There may be scenarios where you want to exclude a specific doc from the index even though all other documents are being indexed automatically. This method demonstrates how to use an index directive to control this """ try: DeleteContainerIfExists(client, database_id, COLLECTION_ID) database_link = GetDatabaseLink(database_id) # collections = Query_Entities(client, 'collection', parent_link = database_link) # print(collections) # Create a collection with default index policy (i.e. automatic = true) created_Container = client.CreateContainer(database_link, {"id" : COLLECTION_ID}) print(created_Container) print("\n" + "-" * 25 + "\n1. Collection created with index policy") print_dictionary_items(created_Container["indexingPolicy"]) # Create a document and query on it immediately. # Will work as automatic indexing is still True collection_link = GetContainerLink(database_id, COLLECTION_ID) doc = client.CreateItem(collection_link, { "id" : "doc1", "orderId" : "order1" }) print("\n" + "-" * 25 + "Document doc1 created with order1" + "-" * 25) print(doc) query = { "query": "SELECT * FROM r WHERE r.orderId=@orderNo", "parameters": [ { "name":"@orderNo", "value": "order1" } ] } QueryDocumentsWithCustomQuery(client, collection_link, query) # Now, create a document but this time explictly exclude it from the collection using IndexingDirective # Then query for that document # Shoud NOT find it, because we excluded it from the index # BUT, the document is there and doing a ReadDocument by Id will prove it doc2 = client.CreateItem(collection_link, { "id" : "doc2", "orderId" : "order2" }, {'indexingDirective' : documents.IndexingDirective.Exclude}) print("\n" + "-" * 25 + "Document doc2 created with order2" + "-" * 25) print(doc2) query = { "query": "SELECT * FROM r WHERE r.orderId=@orderNo", "parameters": [ { "name":"@orderNo", "value": "order2" } ] } QueryDocumentsWithCustomQuery(client, collection_link, query) docRead = client.ReadItem(GetDocumentLink(database_id, COLLECTION_ID, "doc2")) print("Document read by ID: \n", docRead["id"]) # Cleanup client.DeleteContainer(collection_link) print("\n") except errors.HTTPFailure as e: if e.status_code == 409: print("Entity already exists") elif e.status_code == 404: print("Entity doesn't exist") else: raise
[ "def", "ExplicitlyExcludeFromIndex", "(", "client", ",", "database_id", ")", ":", "try", ":", "DeleteContainerIfExists", "(", "client", ",", "database_id", ",", "COLLECTION_ID", ")", "database_link", "=", "GetDatabaseLink", "(", "database_id", ")", "# collections = Query_Entities(client, 'collection', parent_link = database_link)", "# print(collections)", "# Create a collection with default index policy (i.e. automatic = true)", "created_Container", "=", "client", ".", "CreateContainer", "(", "database_link", ",", "{", "\"id\"", ":", "COLLECTION_ID", "}", ")", "print", "(", "created_Container", ")", "print", "(", "\"\\n\"", "+", "\"-\"", "*", "25", "+", "\"\\n1. Collection created with index policy\"", ")", "print_dictionary_items", "(", "created_Container", "[", "\"indexingPolicy\"", "]", ")", "# Create a document and query on it immediately.", "# Will work as automatic indexing is still True", "collection_link", "=", "GetContainerLink", "(", "database_id", ",", "COLLECTION_ID", ")", "doc", "=", "client", ".", "CreateItem", "(", "collection_link", ",", "{", "\"id\"", ":", "\"doc1\"", ",", "\"orderId\"", ":", "\"order1\"", "}", ")", "print", "(", "\"\\n\"", "+", "\"-\"", "*", "25", "+", "\"Document doc1 created with order1\"", "+", "\"-\"", "*", "25", ")", "print", "(", "doc", ")", "query", "=", "{", "\"query\"", ":", "\"SELECT * FROM r WHERE r.orderId=@orderNo\"", ",", "\"parameters\"", ":", "[", "{", "\"name\"", ":", "\"@orderNo\"", ",", "\"value\"", ":", "\"order1\"", "}", "]", "}", "QueryDocumentsWithCustomQuery", "(", "client", ",", "collection_link", ",", "query", ")", "# Now, create a document but this time explictly exclude it from the collection using IndexingDirective", "# Then query for that document", "# Shoud NOT find it, because we excluded it from the index", "# BUT, the document is there and doing a ReadDocument by Id will prove it", "doc2", "=", "client", ".", "CreateItem", "(", "collection_link", ",", "{", "\"id\"", ":", "\"doc2\"", ",", "\"orderId\"", ":", "\"order2\"", "}", ",", "{", "'indexingDirective'", ":", "documents", ".", "IndexingDirective", ".", "Exclude", "}", ")", "print", "(", "\"\\n\"", "+", "\"-\"", "*", "25", "+", "\"Document doc2 created with order2\"", "+", "\"-\"", "*", "25", ")", "print", "(", "doc2", ")", "query", "=", "{", "\"query\"", ":", "\"SELECT * FROM r WHERE r.orderId=@orderNo\"", ",", "\"parameters\"", ":", "[", "{", "\"name\"", ":", "\"@orderNo\"", ",", "\"value\"", ":", "\"order2\"", "}", "]", "}", "QueryDocumentsWithCustomQuery", "(", "client", ",", "collection_link", ",", "query", ")", "docRead", "=", "client", ".", "ReadItem", "(", "GetDocumentLink", "(", "database_id", ",", "COLLECTION_ID", ",", "\"doc2\"", ")", ")", "print", "(", "\"Document read by ID: \\n\"", ",", "docRead", "[", "\"id\"", "]", ")", "# Cleanup", "client", ".", "DeleteContainer", "(", "collection_link", ")", "print", "(", "\"\\n\"", ")", "except", "errors", ".", "HTTPFailure", "as", "e", ":", "if", "e", ".", "status_code", "==", "409", ":", "print", "(", "\"Entity already exists\"", ")", "elif", "e", ".", "status_code", "==", "404", ":", "print", "(", "\"Entity doesn't exist\"", ")", "else", ":", "raise" ]
The default index policy on a DocumentContainer will AUTOMATICALLY index ALL documents added. There may be scenarios where you want to exclude a specific doc from the index even though all other documents are being indexed automatically. This method demonstrates how to use an index directive to control this
[ "The", "default", "index", "policy", "on", "a", "DocumentContainer", "will", "AUTOMATICALLY", "index", "ALL", "documents", "added", ".", "There", "may", "be", "scenarios", "where", "you", "want", "to", "exclude", "a", "specific", "doc", "from", "the", "index", "even", "though", "all", "other", "documents", "are", "being", "indexed", "automatically", ".", "This", "method", "demonstrates", "how", "to", "use", "an", "index", "directive", "to", "control", "this" ]
dd01b3c5d308c6da83cfcaa0ab7083351a476353
https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/samples/IndexManagement/Program.py#L171-L231
229,497
Azure/azure-cosmos-python
samples/IndexManagement/Program.py
ExcludePathsFromIndex
def ExcludePathsFromIndex(client, database_id): """The default behavior is for Cosmos to index every attribute in every document automatically. There are times when a document contains large amounts of information, in deeply nested structures that you know you will never search on. In extreme cases like this, you can exclude paths from the index to save on storage cost, improve write performance and also improve read performance because the index is smaller This method demonstrates how to set excludedPaths within indexingPolicy """ try: DeleteContainerIfExists(client, database_id, COLLECTION_ID) database_link = GetDatabaseLink(database_id) # collections = Query_Entities(client, 'collection', parent_link = database_link) # print(collections) doc_with_nested_structures = { "id" : "doc1", "foo" : "bar", "metaData" : "meta", "subDoc" : { "searchable" : "searchable", "nonSearchable" : "value" }, "excludedNode" : { "subExcluded" : "something", "subExcludedNode" : { "someProperty" : "value" } } } collection_to_create = { "id" : COLLECTION_ID , "indexingPolicy" : { "includedPaths" : [ {'path' : "/*"} ], # Special mandatory path of "/*" required to denote include entire tree "excludedPaths" : [ {'path' : "/metaData/*"}, # exclude metaData node, and anything under it {'path' : "/subDoc/nonSearchable/*"}, # exclude ONLY a part of subDoc {'path' : "/\"excludedNode\"/*"} # exclude excludedNode node, and anything under it ] } } print(collection_to_create) print(doc_with_nested_structures) # Create a collection with the defined properties # The effect of the above IndexingPolicy is that only id, foo, and the subDoc/searchable are indexed created_Container = client.CreateContainer(database_link, collection_to_create) print(created_Container) print("\n" + "-" * 25 + "\n4. Collection created with index policy") print_dictionary_items(created_Container["indexingPolicy"]) # The effect of the above IndexingPolicy is that only id, foo, and the subDoc/searchable are indexed collection_link = GetContainerLink(database_id, COLLECTION_ID) doc = client.CreateItem(collection_link, doc_with_nested_structures) print("\n" + "-" * 25 + "Document doc1 created with nested structures" + "-" * 25) print(doc) # Querying for a document on either metaData or /subDoc/subSubDoc/someProperty > fail because these paths were excluded and they raise a BadRequest(400) Exception query = {"query": "SELECT * FROM r WHERE r.metaData=@desiredValue", "parameters" : [{ "name":"@desiredValue", "value": "meta" }]} QueryDocumentsWithCustomQuery(client, collection_link, query) query = {"query": "SELECT * FROM r WHERE r.subDoc.nonSearchable=@desiredValue", "parameters" : [{ "name":"@desiredValue", "value": "value" }]} QueryDocumentsWithCustomQuery(client, collection_link, query) query = {"query": "SELECT * FROM r WHERE r.excludedNode.subExcludedNode.someProperty=@desiredValue", "parameters" : [{ "name":"@desiredValue", "value": "value" }]} QueryDocumentsWithCustomQuery(client, collection_link, query) # Querying for a document using foo, or even subDoc/searchable > succeed because they were not excluded query = {"query": "SELECT * FROM r WHERE r.foo=@desiredValue", "parameters" : [{ "name":"@desiredValue", "value": "bar" }]} QueryDocumentsWithCustomQuery(client, collection_link, query) query = {"query": "SELECT * FROM r WHERE r.subDoc.searchable=@desiredValue", "parameters" : [{ "name":"@desiredValue", "value": "searchable" }]} QueryDocumentsWithCustomQuery(client, collection_link, query) # Cleanup client.DeleteContainer(collection_link) print("\n") except errors.HTTPFailure as e: if e.status_code == 409: print("Entity already exists") elif e.status_code == 404: print("Entity doesn't exist") else: raise
python
def ExcludePathsFromIndex(client, database_id): """The default behavior is for Cosmos to index every attribute in every document automatically. There are times when a document contains large amounts of information, in deeply nested structures that you know you will never search on. In extreme cases like this, you can exclude paths from the index to save on storage cost, improve write performance and also improve read performance because the index is smaller This method demonstrates how to set excludedPaths within indexingPolicy """ try: DeleteContainerIfExists(client, database_id, COLLECTION_ID) database_link = GetDatabaseLink(database_id) # collections = Query_Entities(client, 'collection', parent_link = database_link) # print(collections) doc_with_nested_structures = { "id" : "doc1", "foo" : "bar", "metaData" : "meta", "subDoc" : { "searchable" : "searchable", "nonSearchable" : "value" }, "excludedNode" : { "subExcluded" : "something", "subExcludedNode" : { "someProperty" : "value" } } } collection_to_create = { "id" : COLLECTION_ID , "indexingPolicy" : { "includedPaths" : [ {'path' : "/*"} ], # Special mandatory path of "/*" required to denote include entire tree "excludedPaths" : [ {'path' : "/metaData/*"}, # exclude metaData node, and anything under it {'path' : "/subDoc/nonSearchable/*"}, # exclude ONLY a part of subDoc {'path' : "/\"excludedNode\"/*"} # exclude excludedNode node, and anything under it ] } } print(collection_to_create) print(doc_with_nested_structures) # Create a collection with the defined properties # The effect of the above IndexingPolicy is that only id, foo, and the subDoc/searchable are indexed created_Container = client.CreateContainer(database_link, collection_to_create) print(created_Container) print("\n" + "-" * 25 + "\n4. Collection created with index policy") print_dictionary_items(created_Container["indexingPolicy"]) # The effect of the above IndexingPolicy is that only id, foo, and the subDoc/searchable are indexed collection_link = GetContainerLink(database_id, COLLECTION_ID) doc = client.CreateItem(collection_link, doc_with_nested_structures) print("\n" + "-" * 25 + "Document doc1 created with nested structures" + "-" * 25) print(doc) # Querying for a document on either metaData or /subDoc/subSubDoc/someProperty > fail because these paths were excluded and they raise a BadRequest(400) Exception query = {"query": "SELECT * FROM r WHERE r.metaData=@desiredValue", "parameters" : [{ "name":"@desiredValue", "value": "meta" }]} QueryDocumentsWithCustomQuery(client, collection_link, query) query = {"query": "SELECT * FROM r WHERE r.subDoc.nonSearchable=@desiredValue", "parameters" : [{ "name":"@desiredValue", "value": "value" }]} QueryDocumentsWithCustomQuery(client, collection_link, query) query = {"query": "SELECT * FROM r WHERE r.excludedNode.subExcludedNode.someProperty=@desiredValue", "parameters" : [{ "name":"@desiredValue", "value": "value" }]} QueryDocumentsWithCustomQuery(client, collection_link, query) # Querying for a document using foo, or even subDoc/searchable > succeed because they were not excluded query = {"query": "SELECT * FROM r WHERE r.foo=@desiredValue", "parameters" : [{ "name":"@desiredValue", "value": "bar" }]} QueryDocumentsWithCustomQuery(client, collection_link, query) query = {"query": "SELECT * FROM r WHERE r.subDoc.searchable=@desiredValue", "parameters" : [{ "name":"@desiredValue", "value": "searchable" }]} QueryDocumentsWithCustomQuery(client, collection_link, query) # Cleanup client.DeleteContainer(collection_link) print("\n") except errors.HTTPFailure as e: if e.status_code == 409: print("Entity already exists") elif e.status_code == 404: print("Entity doesn't exist") else: raise
[ "def", "ExcludePathsFromIndex", "(", "client", ",", "database_id", ")", ":", "try", ":", "DeleteContainerIfExists", "(", "client", ",", "database_id", ",", "COLLECTION_ID", ")", "database_link", "=", "GetDatabaseLink", "(", "database_id", ")", "# collections = Query_Entities(client, 'collection', parent_link = database_link)", "# print(collections)", "doc_with_nested_structures", "=", "{", "\"id\"", ":", "\"doc1\"", ",", "\"foo\"", ":", "\"bar\"", ",", "\"metaData\"", ":", "\"meta\"", ",", "\"subDoc\"", ":", "{", "\"searchable\"", ":", "\"searchable\"", ",", "\"nonSearchable\"", ":", "\"value\"", "}", ",", "\"excludedNode\"", ":", "{", "\"subExcluded\"", ":", "\"something\"", ",", "\"subExcludedNode\"", ":", "{", "\"someProperty\"", ":", "\"value\"", "}", "}", "}", "collection_to_create", "=", "{", "\"id\"", ":", "COLLECTION_ID", ",", "\"indexingPolicy\"", ":", "{", "\"includedPaths\"", ":", "[", "{", "'path'", ":", "\"/*\"", "}", "]", ",", "# Special mandatory path of \"/*\" required to denote include entire tree", "\"excludedPaths\"", ":", "[", "{", "'path'", ":", "\"/metaData/*\"", "}", ",", "# exclude metaData node, and anything under it", "{", "'path'", ":", "\"/subDoc/nonSearchable/*\"", "}", ",", "# exclude ONLY a part of subDoc ", "{", "'path'", ":", "\"/\\\"excludedNode\\\"/*\"", "}", "# exclude excludedNode node, and anything under it", "]", "}", "}", "print", "(", "collection_to_create", ")", "print", "(", "doc_with_nested_structures", ")", "# Create a collection with the defined properties", "# The effect of the above IndexingPolicy is that only id, foo, and the subDoc/searchable are indexed", "created_Container", "=", "client", ".", "CreateContainer", "(", "database_link", ",", "collection_to_create", ")", "print", "(", "created_Container", ")", "print", "(", "\"\\n\"", "+", "\"-\"", "*", "25", "+", "\"\\n4. Collection created with index policy\"", ")", "print_dictionary_items", "(", "created_Container", "[", "\"indexingPolicy\"", "]", ")", "# The effect of the above IndexingPolicy is that only id, foo, and the subDoc/searchable are indexed", "collection_link", "=", "GetContainerLink", "(", "database_id", ",", "COLLECTION_ID", ")", "doc", "=", "client", ".", "CreateItem", "(", "collection_link", ",", "doc_with_nested_structures", ")", "print", "(", "\"\\n\"", "+", "\"-\"", "*", "25", "+", "\"Document doc1 created with nested structures\"", "+", "\"-\"", "*", "25", ")", "print", "(", "doc", ")", "# Querying for a document on either metaData or /subDoc/subSubDoc/someProperty > fail because these paths were excluded and they raise a BadRequest(400) Exception", "query", "=", "{", "\"query\"", ":", "\"SELECT * FROM r WHERE r.metaData=@desiredValue\"", ",", "\"parameters\"", ":", "[", "{", "\"name\"", ":", "\"@desiredValue\"", ",", "\"value\"", ":", "\"meta\"", "}", "]", "}", "QueryDocumentsWithCustomQuery", "(", "client", ",", "collection_link", ",", "query", ")", "query", "=", "{", "\"query\"", ":", "\"SELECT * FROM r WHERE r.subDoc.nonSearchable=@desiredValue\"", ",", "\"parameters\"", ":", "[", "{", "\"name\"", ":", "\"@desiredValue\"", ",", "\"value\"", ":", "\"value\"", "}", "]", "}", "QueryDocumentsWithCustomQuery", "(", "client", ",", "collection_link", ",", "query", ")", "query", "=", "{", "\"query\"", ":", "\"SELECT * FROM r WHERE r.excludedNode.subExcludedNode.someProperty=@desiredValue\"", ",", "\"parameters\"", ":", "[", "{", "\"name\"", ":", "\"@desiredValue\"", ",", "\"value\"", ":", "\"value\"", "}", "]", "}", "QueryDocumentsWithCustomQuery", "(", "client", ",", "collection_link", ",", "query", ")", "# Querying for a document using foo, or even subDoc/searchable > succeed because they were not excluded", "query", "=", "{", "\"query\"", ":", "\"SELECT * FROM r WHERE r.foo=@desiredValue\"", ",", "\"parameters\"", ":", "[", "{", "\"name\"", ":", "\"@desiredValue\"", ",", "\"value\"", ":", "\"bar\"", "}", "]", "}", "QueryDocumentsWithCustomQuery", "(", "client", ",", "collection_link", ",", "query", ")", "query", "=", "{", "\"query\"", ":", "\"SELECT * FROM r WHERE r.subDoc.searchable=@desiredValue\"", ",", "\"parameters\"", ":", "[", "{", "\"name\"", ":", "\"@desiredValue\"", ",", "\"value\"", ":", "\"searchable\"", "}", "]", "}", "QueryDocumentsWithCustomQuery", "(", "client", ",", "collection_link", ",", "query", ")", "# Cleanup", "client", ".", "DeleteContainer", "(", "collection_link", ")", "print", "(", "\"\\n\"", ")", "except", "errors", ".", "HTTPFailure", "as", "e", ":", "if", "e", ".", "status_code", "==", "409", ":", "print", "(", "\"Entity already exists\"", ")", "elif", "e", ".", "status_code", "==", "404", ":", "print", "(", "\"Entity doesn't exist\"", ")", "else", ":", "raise" ]
The default behavior is for Cosmos to index every attribute in every document automatically. There are times when a document contains large amounts of information, in deeply nested structures that you know you will never search on. In extreme cases like this, you can exclude paths from the index to save on storage cost, improve write performance and also improve read performance because the index is smaller This method demonstrates how to set excludedPaths within indexingPolicy
[ "The", "default", "behavior", "is", "for", "Cosmos", "to", "index", "every", "attribute", "in", "every", "document", "automatically", ".", "There", "are", "times", "when", "a", "document", "contains", "large", "amounts", "of", "information", "in", "deeply", "nested", "structures", "that", "you", "know", "you", "will", "never", "search", "on", ".", "In", "extreme", "cases", "like", "this", "you", "can", "exclude", "paths", "from", "the", "index", "to", "save", "on", "storage", "cost", "improve", "write", "performance", "and", "also", "improve", "read", "performance", "because", "the", "index", "is", "smaller", "This", "method", "demonstrates", "how", "to", "set", "excludedPaths", "within", "indexingPolicy" ]
dd01b3c5d308c6da83cfcaa0ab7083351a476353
https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/samples/IndexManagement/Program.py#L294-L367
229,498
Azure/azure-cosmos-python
samples/IndexManagement/Program.py
UseRangeIndexesOnStrings
def UseRangeIndexesOnStrings(client, database_id): """Showing how range queries can be performed even on strings. """ try: DeleteContainerIfExists(client, database_id, COLLECTION_ID) database_link = GetDatabaseLink(database_id) # collections = Query_Entities(client, 'collection', parent_link = database_link) # print(collections) # Use range indexes on strings # This is how you can specify a range index on strings (and numbers) for all properties. # This is the recommended indexing policy for collections. i.e. precision -1 #indexingPolicy = { # 'indexingPolicy': { # 'includedPaths': [ # { # 'indexes': [ # { # 'kind': documents.IndexKind.Range, # 'dataType': documents.DataType.String, # 'precision': -1 # } # ] # } # ] # } #} # For demo purposes, we are going to use the default (range on numbers, hash on strings) for the whole document (/* ) # and just include a range index on strings for the "region". collection_definition = { 'id': COLLECTION_ID, 'indexingPolicy': { 'includedPaths': [ { 'path': '/region/?', 'indexes': [ { 'kind': documents.IndexKind.Range, 'dataType': documents.DataType.String, 'precision': -1 } ] }, { 'path': '/*' } ] } } created_Container = client.CreateContainer(database_link, collection_definition) print(created_Container) print("\n" + "-" * 25 + "\n6. Collection created with index policy") print_dictionary_items(created_Container["indexingPolicy"]) collection_link = GetContainerLink(database_id, COLLECTION_ID) client.CreateItem(collection_link, { "id" : "doc1", "region" : "USA" }) client.CreateItem(collection_link, { "id" : "doc2", "region" : "UK" }) client.CreateItem(collection_link, { "id" : "doc3", "region" : "Armenia" }) client.CreateItem(collection_link, { "id" : "doc4", "region" : "Egypt" }) # Now ordering against region is allowed. You can run the following query query = { "query" : "SELECT * FROM r ORDER BY r.region" } message = "Documents ordered by region" QueryDocumentsWithCustomQuery(client, collection_link, query, message) # You can also perform filters against string comparison like >= 'UK'. Note that you can perform a prefix query, # the equivalent of LIKE 'U%' (is >= 'U' AND < 'U') query = { "query" : "SELECT * FROM r WHERE r.region >= 'U'" } message = "Documents with region begining with U" QueryDocumentsWithCustomQuery(client, collection_link, query, message) # Cleanup client.DeleteContainer(collection_link) print("\n") except errors.HTTPFailure as e: if e.status_code == 409: print("Entity already exists") elif e.status_code == 404: print("Entity doesn't exist") else: raise
python
def UseRangeIndexesOnStrings(client, database_id): """Showing how range queries can be performed even on strings. """ try: DeleteContainerIfExists(client, database_id, COLLECTION_ID) database_link = GetDatabaseLink(database_id) # collections = Query_Entities(client, 'collection', parent_link = database_link) # print(collections) # Use range indexes on strings # This is how you can specify a range index on strings (and numbers) for all properties. # This is the recommended indexing policy for collections. i.e. precision -1 #indexingPolicy = { # 'indexingPolicy': { # 'includedPaths': [ # { # 'indexes': [ # { # 'kind': documents.IndexKind.Range, # 'dataType': documents.DataType.String, # 'precision': -1 # } # ] # } # ] # } #} # For demo purposes, we are going to use the default (range on numbers, hash on strings) for the whole document (/* ) # and just include a range index on strings for the "region". collection_definition = { 'id': COLLECTION_ID, 'indexingPolicy': { 'includedPaths': [ { 'path': '/region/?', 'indexes': [ { 'kind': documents.IndexKind.Range, 'dataType': documents.DataType.String, 'precision': -1 } ] }, { 'path': '/*' } ] } } created_Container = client.CreateContainer(database_link, collection_definition) print(created_Container) print("\n" + "-" * 25 + "\n6. Collection created with index policy") print_dictionary_items(created_Container["indexingPolicy"]) collection_link = GetContainerLink(database_id, COLLECTION_ID) client.CreateItem(collection_link, { "id" : "doc1", "region" : "USA" }) client.CreateItem(collection_link, { "id" : "doc2", "region" : "UK" }) client.CreateItem(collection_link, { "id" : "doc3", "region" : "Armenia" }) client.CreateItem(collection_link, { "id" : "doc4", "region" : "Egypt" }) # Now ordering against region is allowed. You can run the following query query = { "query" : "SELECT * FROM r ORDER BY r.region" } message = "Documents ordered by region" QueryDocumentsWithCustomQuery(client, collection_link, query, message) # You can also perform filters against string comparison like >= 'UK'. Note that you can perform a prefix query, # the equivalent of LIKE 'U%' (is >= 'U' AND < 'U') query = { "query" : "SELECT * FROM r WHERE r.region >= 'U'" } message = "Documents with region begining with U" QueryDocumentsWithCustomQuery(client, collection_link, query, message) # Cleanup client.DeleteContainer(collection_link) print("\n") except errors.HTTPFailure as e: if e.status_code == 409: print("Entity already exists") elif e.status_code == 404: print("Entity doesn't exist") else: raise
[ "def", "UseRangeIndexesOnStrings", "(", "client", ",", "database_id", ")", ":", "try", ":", "DeleteContainerIfExists", "(", "client", ",", "database_id", ",", "COLLECTION_ID", ")", "database_link", "=", "GetDatabaseLink", "(", "database_id", ")", "# collections = Query_Entities(client, 'collection', parent_link = database_link)", "# print(collections)", "# Use range indexes on strings", "# This is how you can specify a range index on strings (and numbers) for all properties.", "# This is the recommended indexing policy for collections. i.e. precision -1", "#indexingPolicy = { ", "# 'indexingPolicy': {", "# 'includedPaths': [", "# {", "# 'indexes': [", "# {", "# 'kind': documents.IndexKind.Range,", "# 'dataType': documents.DataType.String,", "# 'precision': -1", "# }", "# ]", "# }", "# ]", "# }", "#}", "# For demo purposes, we are going to use the default (range on numbers, hash on strings) for the whole document (/* )", "# and just include a range index on strings for the \"region\".", "collection_definition", "=", "{", "'id'", ":", "COLLECTION_ID", ",", "'indexingPolicy'", ":", "{", "'includedPaths'", ":", "[", "{", "'path'", ":", "'/region/?'", ",", "'indexes'", ":", "[", "{", "'kind'", ":", "documents", ".", "IndexKind", ".", "Range", ",", "'dataType'", ":", "documents", ".", "DataType", ".", "String", ",", "'precision'", ":", "-", "1", "}", "]", "}", ",", "{", "'path'", ":", "'/*'", "}", "]", "}", "}", "created_Container", "=", "client", ".", "CreateContainer", "(", "database_link", ",", "collection_definition", ")", "print", "(", "created_Container", ")", "print", "(", "\"\\n\"", "+", "\"-\"", "*", "25", "+", "\"\\n6. Collection created with index policy\"", ")", "print_dictionary_items", "(", "created_Container", "[", "\"indexingPolicy\"", "]", ")", "collection_link", "=", "GetContainerLink", "(", "database_id", ",", "COLLECTION_ID", ")", "client", ".", "CreateItem", "(", "collection_link", ",", "{", "\"id\"", ":", "\"doc1\"", ",", "\"region\"", ":", "\"USA\"", "}", ")", "client", ".", "CreateItem", "(", "collection_link", ",", "{", "\"id\"", ":", "\"doc2\"", ",", "\"region\"", ":", "\"UK\"", "}", ")", "client", ".", "CreateItem", "(", "collection_link", ",", "{", "\"id\"", ":", "\"doc3\"", ",", "\"region\"", ":", "\"Armenia\"", "}", ")", "client", ".", "CreateItem", "(", "collection_link", ",", "{", "\"id\"", ":", "\"doc4\"", ",", "\"region\"", ":", "\"Egypt\"", "}", ")", "# Now ordering against region is allowed. You can run the following query", "query", "=", "{", "\"query\"", ":", "\"SELECT * FROM r ORDER BY r.region\"", "}", "message", "=", "\"Documents ordered by region\"", "QueryDocumentsWithCustomQuery", "(", "client", ",", "collection_link", ",", "query", ",", "message", ")", "# You can also perform filters against string comparison like >= 'UK'. Note that you can perform a prefix query, ", "# the equivalent of LIKE 'U%' (is >= 'U' AND < 'U')", "query", "=", "{", "\"query\"", ":", "\"SELECT * FROM r WHERE r.region >= 'U'\"", "}", "message", "=", "\"Documents with region begining with U\"", "QueryDocumentsWithCustomQuery", "(", "client", ",", "collection_link", ",", "query", ",", "message", ")", "# Cleanup", "client", ".", "DeleteContainer", "(", "collection_link", ")", "print", "(", "\"\\n\"", ")", "except", "errors", ".", "HTTPFailure", "as", "e", ":", "if", "e", ".", "status_code", "==", "409", ":", "print", "(", "\"Entity already exists\"", ")", "elif", "e", ".", "status_code", "==", "404", ":", "print", "(", "\"Entity doesn't exist\"", ")", "else", ":", "raise" ]
Showing how range queries can be performed even on strings.
[ "Showing", "how", "range", "queries", "can", "be", "performed", "even", "on", "strings", "." ]
dd01b3c5d308c6da83cfcaa0ab7083351a476353
https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/samples/IndexManagement/Program.py#L428-L512
229,499
Azure/azure-cosmos-python
azure/cosmos/range_partition_resolver.py
RangePartitionResolver.ResolveForCreate
def ResolveForCreate(self, document): """Resolves the collection for creating the document based on the partition key. :param dict document: The document to be created. :return: Collection Self link or Name based link which should handle the Create operation. :rtype: str """ if document is None: raise ValueError("document is None.") partition_key = self.partition_key_extractor(document) containing_range = self._GetContainingRange(partition_key) if containing_range is None: raise ValueError("A containing range for " + str(partition_key) + " doesn't exist in the partition map.") return self.partition_map.get(containing_range)
python
def ResolveForCreate(self, document): """Resolves the collection for creating the document based on the partition key. :param dict document: The document to be created. :return: Collection Self link or Name based link which should handle the Create operation. :rtype: str """ if document is None: raise ValueError("document is None.") partition_key = self.partition_key_extractor(document) containing_range = self._GetContainingRange(partition_key) if containing_range is None: raise ValueError("A containing range for " + str(partition_key) + " doesn't exist in the partition map.") return self.partition_map.get(containing_range)
[ "def", "ResolveForCreate", "(", "self", ",", "document", ")", ":", "if", "document", "is", "None", ":", "raise", "ValueError", "(", "\"document is None.\"", ")", "partition_key", "=", "self", ".", "partition_key_extractor", "(", "document", ")", "containing_range", "=", "self", ".", "_GetContainingRange", "(", "partition_key", ")", "if", "containing_range", "is", "None", ":", "raise", "ValueError", "(", "\"A containing range for \"", "+", "str", "(", "partition_key", ")", "+", "\" doesn't exist in the partition map.\"", ")", "return", "self", ".", "partition_map", ".", "get", "(", "containing_range", ")" ]
Resolves the collection for creating the document based on the partition key. :param dict document: The document to be created. :return: Collection Self link or Name based link which should handle the Create operation. :rtype: str
[ "Resolves", "the", "collection", "for", "creating", "the", "document", "based", "on", "the", "partition", "key", "." ]
dd01b3c5d308c6da83cfcaa0ab7083351a476353
https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/range_partition_resolver.py#L46-L66