file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
cache.py
""" Caching utilities for zipline """ from collections import MutableMapping import errno import os import pickle from distutils import dir_util from shutil import rmtree, move from tempfile import mkdtemp, NamedTemporaryFile import pandas as pd from .context_tricks import nop_context from .paths import ensure_directory from .sentinel import sentinel class Expired(Exception): """Marks that a :class:`CachedObject` has expired. """ ExpiredCachedObject = sentinel('ExpiredCachedObject') AlwaysExpired = sentinel('AlwaysExpired') class CachedObject(object): """ A simple struct for maintaining a cached object with an expiration date. Parameters ---------- value : object The object to cache. expires : datetime-like Expiration date of `value`. The cache is considered invalid for dates **strictly greater** than `expires`. Examples -------- >>> from pandas import Timestamp, Timedelta >>> expires = Timestamp('2014', tz='UTC') >>> obj = CachedObject(1, expires) >>> obj.unwrap(expires - Timedelta('1 minute')) 1 >>> obj.unwrap(expires) 1 >>> obj.unwrap(expires + Timedelta('1 minute')) ... # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... Expired: 2014-01-01 00:00:00+00:00 """ def __init__(self, value, expires): self._value = value self._expires = expires @classmethod def expired(cls): """Construct a CachedObject that's expired at any time. """ return cls(ExpiredCachedObject, expires=AlwaysExpired) def unwrap(self, dt): """ Get the cached value. Returns ------- value : object The cached value. Raises ------ Expired Raised when `dt` is greater than self.expires. """ expires = self._expires if expires is AlwaysExpired or expires < dt: raise Expired(self._expires) return self._value def _unsafe_get_value(self): """You almost certainly shouldn't use this.""" return self._value class ExpiringCache(object): """ A cache of multiple CachedObjects, which returns the wrapped the value or raises and deletes the CachedObject if the value has expired. Parameters ---------- cache : dict-like, optional An instance of a dict-like object which needs to support at least: `__del__`, `__getitem__`, `__setitem__` If `None`, than a dict is used as a default. Examples -------- >>> from pandas import Timestamp, Timedelta >>> expires = Timestamp('2014', tz='UTC') >>> value = 1 >>> cache = ExpiringCache() >>> cache.set('foo', value, expires) >>> cache.get('foo', expires - Timedelta('1 minute')) 1 >>> cache.get('foo', expires + Timedelta('1 minute')) Traceback (most recent call last): ... KeyError: 'foo' """ def __init__(self, cache=None): if cache is not None: self._cache = cache else: self._cache = {} def get(self, key, dt): """Get the value of a cached object. Parameters ---------- key : any The key to lookup. dt : datetime The time of the lookup. Returns ------- result : any The value for ``key``. Raises ------ KeyError Raised if the key is not in the cache or the value for the key has expired. """ try: return self._cache[key].unwrap(dt) except Expired: del self._cache[key] raise KeyError(key) def set(self, key, value, expiration_dt): """Adds a new key value pair to the cache. Parameters ---------- key : any The key to use for the pair. value : any The value to store under the name ``key``. expiration_dt : datetime When should this mapping expire? The cache is considered invalid for dates **strictly greater** than ``expiration_dt``. """ self._cache[key] = CachedObject(value, expiration_dt) class dataframe_cache(MutableMapping): """A disk-backed cache for dataframes. ``dataframe_cache`` is a mutable mapping from string names to pandas DataFrame objects. This object may be used as a context manager to delete the cache directory on exit. Parameters ---------- path : str, optional The directory path to the cache. Files will be written as ``path/<keyname>``. lock : Lock, optional Thread lock for multithreaded/multiprocessed access to the cache. If not provided no locking will be used. clean_on_failure : bool, optional Should the directory be cleaned up if an exception is raised in the context manager. serialize : {'msgpack', 'pickle:<n>'}, optional How should the data be serialized. If ``'pickle'`` is passed, an optional pickle protocol can be passed like: ``'pickle:3'`` which says to use pickle protocol 3. Notes ----- The syntax ``cache[:]`` will load all key:value pairs into memory as a dictionary. The cache uses a temporary file format that is subject to change between versions of zipline. """ def __init__(self, path=None, lock=None, clean_on_failure=True, serialization='msgpack'): self.path = path if path is not None else mkdtemp() self.lock = lock if lock is not None else nop_context self.clean_on_failure = clean_on_failure if serialization == 'msgpack': self.serialize = pd.DataFrame.to_msgpack self.deserialize = pd.read_msgpack self._protocol = None else: s = serialization.split(':', 1) if s[0] != 'pickle': raise ValueError( "'serialization' must be either 'msgpack' or 'pickle[:n]'", ) self._protocol = int(s[1]) if len(s) == 2 else None self.serialize = self._serialize_pickle self.deserialize = pickle.load ensure_directory(self.path) def _serialize_pickle(self, df, path): with open(path, 'wb') as f: pickle.dump(df, f, protocol=self._protocol) def _keypath(self, key): return os.path.join(self.path, key) def __enter__(self): return self def __exit__(self, type_, value, tb): if not (self.clean_on_failure or value is None): # we are not cleaning up after a failure and there was an exception return with self.lock: rmtree(self.path) def __getitem__(self, key): if key == slice(None): return dict(self.items()) with self.lock: try: with open(self._keypath(key), 'rb') as f: return self.deserialize(f) except IOError as e: if e.errno != errno.ENOENT: raise raise KeyError(key) def __setitem__(self, key, value): with self.lock: self.serialize(value, self._keypath(key)) def __delitem__(self, key): with self.lock: try: os.remove(self._keypath(key)) except OSError as e: if e.errno == errno.ENOENT: # raise a keyerror if this directory did not exist raise KeyError(key) # reraise the actual oserror otherwise raise def __iter__(self): return iter(os.listdir(self.path)) def __len__(self): return len(os.listdir(self.path)) def __repr__(self): return '<%s: keys={%s}>' % ( type(self).__name__, ', '.join(map(repr, sorted(self))), ) class working_file(object): """A context manager for managing a temporary file that will be moved to a non-temporary location if no exceptions are raised in the context. Parameters ---------- final_path : str The location to move the file when committing. *args, **kwargs Forwarded to NamedTemporaryFile. Notes ----- The file is moved on __exit__ if there are no exceptions. ``working_file`` uses :func:`shutil.move` to move the actual files, meaning it has as strong of guarantees as :func:`shutil.move`. """ def __init__(self, final_path, *args, **kwargs): self._tmpfile = NamedTemporaryFile(delete=False, *args, **kwargs) self._final_path = final_path @property def path(self): """Alias for ``name`` to be consistent with :class:`~zipline.utils.cache.working_dir`. """ return self._tmpfile.name def _commit(self): """Sync the temporary file to the final path. """ move(self.path, self._final_path) def __enter__(self): self._tmpfile.__enter__() return self def __exit__(self, *exc_info): self._tmpfile.__exit__(*exc_info) if exc_info[0] is None: self._commit() class working_dir(object): """A context manager for managing a temporary directory that will be moved to a non-temporary location if no exceptions are raised in the context. Parameters ---------- final_path : str The location to move the file when committing. *args, **kwargs Forwarded to tmp_dir. Notes ----- The file is moved on __exit__ if there are no exceptions. ``working_dir`` uses :func:`dir_util.copy_tree` to move the actual files, meaning it has as strong of guarantees as :func:`dir_util.copy_tree`. """ def __init__(self, final_path, *args, **kwargs): self.path = mkdtemp() self._final_path = final_path def ensure_dir(self, *path_parts): """Ensures a subdirectory of the working directory. Parameters ---------- path_parts : iterable[str] The parts of the path after the working directory. """ path = self.getpath(*path_parts) ensure_directory(path) return path def
(self, *path_parts): """Get a path relative to the working directory. Parameters ---------- path_parts : iterable[str] The parts of the path after the working directory. """ return os.path.join(self.path, *path_parts) def _commit(self): """Sync the temporary directory to the final path. """ dir_util.copy_tree(self.path, self._final_path) def __enter__(self): return self def __exit__(self, *exc_info): if exc_info[0] is None: self._commit() rmtree(self.path)
getpath
identifier_name
cache.py
""" Caching utilities for zipline """ from collections import MutableMapping import errno import os import pickle from distutils import dir_util from shutil import rmtree, move from tempfile import mkdtemp, NamedTemporaryFile import pandas as pd from .context_tricks import nop_context from .paths import ensure_directory from .sentinel import sentinel class Expired(Exception): """Marks that a :class:`CachedObject` has expired. """ ExpiredCachedObject = sentinel('ExpiredCachedObject') AlwaysExpired = sentinel('AlwaysExpired') class CachedObject(object): """ A simple struct for maintaining a cached object with an expiration date. Parameters ---------- value : object The object to cache. expires : datetime-like Expiration date of `value`. The cache is considered invalid for dates **strictly greater** than `expires`. Examples -------- >>> from pandas import Timestamp, Timedelta >>> expires = Timestamp('2014', tz='UTC') >>> obj = CachedObject(1, expires) >>> obj.unwrap(expires - Timedelta('1 minute')) 1 >>> obj.unwrap(expires) 1 >>> obj.unwrap(expires + Timedelta('1 minute')) ... # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... Expired: 2014-01-01 00:00:00+00:00 """ def __init__(self, value, expires): self._value = value self._expires = expires @classmethod def expired(cls): """Construct a CachedObject that's expired at any time. """ return cls(ExpiredCachedObject, expires=AlwaysExpired) def unwrap(self, dt): """ Get the cached value. Returns ------- value : object The cached value. Raises ------ Expired Raised when `dt` is greater than self.expires. """ expires = self._expires if expires is AlwaysExpired or expires < dt: raise Expired(self._expires) return self._value def _unsafe_get_value(self): """You almost certainly shouldn't use this.""" return self._value class ExpiringCache(object): """ A cache of multiple CachedObjects, which returns the wrapped the value or raises and deletes the CachedObject if the value has expired. Parameters ---------- cache : dict-like, optional An instance of a dict-like object which needs to support at least: `__del__`, `__getitem__`, `__setitem__` If `None`, than a dict is used as a default. Examples -------- >>> from pandas import Timestamp, Timedelta >>> expires = Timestamp('2014', tz='UTC') >>> value = 1 >>> cache = ExpiringCache() >>> cache.set('foo', value, expires) >>> cache.get('foo', expires - Timedelta('1 minute')) 1 >>> cache.get('foo', expires + Timedelta('1 minute')) Traceback (most recent call last): ... KeyError: 'foo' """ def __init__(self, cache=None): if cache is not None: self._cache = cache else: self._cache = {} def get(self, key, dt): """Get the value of a cached object. Parameters ---------- key : any The key to lookup. dt : datetime The time of the lookup. Returns ------- result : any The value for ``key``. Raises ------ KeyError Raised if the key is not in the cache or the value for the key
has expired. """ try: return self._cache[key].unwrap(dt) except Expired: del self._cache[key] raise KeyError(key) def set(self, key, value, expiration_dt): """Adds a new key value pair to the cache. Parameters ---------- key : any The key to use for the pair. value : any The value to store under the name ``key``. expiration_dt : datetime When should this mapping expire? The cache is considered invalid for dates **strictly greater** than ``expiration_dt``. """ self._cache[key] = CachedObject(value, expiration_dt) class dataframe_cache(MutableMapping): """A disk-backed cache for dataframes. ``dataframe_cache`` is a mutable mapping from string names to pandas DataFrame objects. This object may be used as a context manager to delete the cache directory on exit. Parameters ---------- path : str, optional The directory path to the cache. Files will be written as ``path/<keyname>``. lock : Lock, optional Thread lock for multithreaded/multiprocessed access to the cache. If not provided no locking will be used. clean_on_failure : bool, optional Should the directory be cleaned up if an exception is raised in the context manager. serialize : {'msgpack', 'pickle:<n>'}, optional How should the data be serialized. If ``'pickle'`` is passed, an optional pickle protocol can be passed like: ``'pickle:3'`` which says to use pickle protocol 3. Notes ----- The syntax ``cache[:]`` will load all key:value pairs into memory as a dictionary. The cache uses a temporary file format that is subject to change between versions of zipline. """ def __init__(self, path=None, lock=None, clean_on_failure=True, serialization='msgpack'): self.path = path if path is not None else mkdtemp() self.lock = lock if lock is not None else nop_context self.clean_on_failure = clean_on_failure if serialization == 'msgpack': self.serialize = pd.DataFrame.to_msgpack self.deserialize = pd.read_msgpack self._protocol = None else: s = serialization.split(':', 1) if s[0] != 'pickle': raise ValueError( "'serialization' must be either 'msgpack' or 'pickle[:n]'", ) self._protocol = int(s[1]) if len(s) == 2 else None self.serialize = self._serialize_pickle self.deserialize = pickle.load ensure_directory(self.path) def _serialize_pickle(self, df, path): with open(path, 'wb') as f: pickle.dump(df, f, protocol=self._protocol) def _keypath(self, key): return os.path.join(self.path, key) def __enter__(self): return self def __exit__(self, type_, value, tb): if not (self.clean_on_failure or value is None): # we are not cleaning up after a failure and there was an exception return with self.lock: rmtree(self.path) def __getitem__(self, key): if key == slice(None): return dict(self.items()) with self.lock: try: with open(self._keypath(key), 'rb') as f: return self.deserialize(f) except IOError as e: if e.errno != errno.ENOENT: raise raise KeyError(key) def __setitem__(self, key, value): with self.lock: self.serialize(value, self._keypath(key)) def __delitem__(self, key): with self.lock: try: os.remove(self._keypath(key)) except OSError as e: if e.errno == errno.ENOENT: # raise a keyerror if this directory did not exist raise KeyError(key) # reraise the actual oserror otherwise raise def __iter__(self): return iter(os.listdir(self.path)) def __len__(self): return len(os.listdir(self.path)) def __repr__(self): return '<%s: keys={%s}>' % ( type(self).__name__, ', '.join(map(repr, sorted(self))), ) class working_file(object): """A context manager for managing a temporary file that will be moved to a non-temporary location if no exceptions are raised in the context. Parameters ---------- final_path : str The location to move the file when committing. *args, **kwargs Forwarded to NamedTemporaryFile. Notes ----- The file is moved on __exit__ if there are no exceptions. ``working_file`` uses :func:`shutil.move` to move the actual files, meaning it has as strong of guarantees as :func:`shutil.move`. """ def __init__(self, final_path, *args, **kwargs): self._tmpfile = NamedTemporaryFile(delete=False, *args, **kwargs) self._final_path = final_path @property def path(self): """Alias for ``name`` to be consistent with :class:`~zipline.utils.cache.working_dir`. """ return self._tmpfile.name def _commit(self): """Sync the temporary file to the final path. """ move(self.path, self._final_path) def __enter__(self): self._tmpfile.__enter__() return self def __exit__(self, *exc_info): self._tmpfile.__exit__(*exc_info) if exc_info[0] is None: self._commit() class working_dir(object): """A context manager for managing a temporary directory that will be moved to a non-temporary location if no exceptions are raised in the context. Parameters ---------- final_path : str The location to move the file when committing. *args, **kwargs Forwarded to tmp_dir. Notes ----- The file is moved on __exit__ if there are no exceptions. ``working_dir`` uses :func:`dir_util.copy_tree` to move the actual files, meaning it has as strong of guarantees as :func:`dir_util.copy_tree`. """ def __init__(self, final_path, *args, **kwargs): self.path = mkdtemp() self._final_path = final_path def ensure_dir(self, *path_parts): """Ensures a subdirectory of the working directory. Parameters ---------- path_parts : iterable[str] The parts of the path after the working directory. """ path = self.getpath(*path_parts) ensure_directory(path) return path def getpath(self, *path_parts): """Get a path relative to the working directory. Parameters ---------- path_parts : iterable[str] The parts of the path after the working directory. """ return os.path.join(self.path, *path_parts) def _commit(self): """Sync the temporary directory to the final path. """ dir_util.copy_tree(self.path, self._final_path) def __enter__(self): return self def __exit__(self, *exc_info): if exc_info[0] is None: self._commit() rmtree(self.path)
random_line_split
cache.py
""" Caching utilities for zipline """ from collections import MutableMapping import errno import os import pickle from distutils import dir_util from shutil import rmtree, move from tempfile import mkdtemp, NamedTemporaryFile import pandas as pd from .context_tricks import nop_context from .paths import ensure_directory from .sentinel import sentinel class Expired(Exception): """Marks that a :class:`CachedObject` has expired. """ ExpiredCachedObject = sentinel('ExpiredCachedObject') AlwaysExpired = sentinel('AlwaysExpired') class CachedObject(object): """ A simple struct for maintaining a cached object with an expiration date. Parameters ---------- value : object The object to cache. expires : datetime-like Expiration date of `value`. The cache is considered invalid for dates **strictly greater** than `expires`. Examples -------- >>> from pandas import Timestamp, Timedelta >>> expires = Timestamp('2014', tz='UTC') >>> obj = CachedObject(1, expires) >>> obj.unwrap(expires - Timedelta('1 minute')) 1 >>> obj.unwrap(expires) 1 >>> obj.unwrap(expires + Timedelta('1 minute')) ... # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... Expired: 2014-01-01 00:00:00+00:00 """ def __init__(self, value, expires): self._value = value self._expires = expires @classmethod def expired(cls): """Construct a CachedObject that's expired at any time. """ return cls(ExpiredCachedObject, expires=AlwaysExpired) def unwrap(self, dt): """ Get the cached value. Returns ------- value : object The cached value. Raises ------ Expired Raised when `dt` is greater than self.expires. """ expires = self._expires if expires is AlwaysExpired or expires < dt: raise Expired(self._expires) return self._value def _unsafe_get_value(self): """You almost certainly shouldn't use this.""" return self._value class ExpiringCache(object): """ A cache of multiple CachedObjects, which returns the wrapped the value or raises and deletes the CachedObject if the value has expired. Parameters ---------- cache : dict-like, optional An instance of a dict-like object which needs to support at least: `__del__`, `__getitem__`, `__setitem__` If `None`, than a dict is used as a default. Examples -------- >>> from pandas import Timestamp, Timedelta >>> expires = Timestamp('2014', tz='UTC') >>> value = 1 >>> cache = ExpiringCache() >>> cache.set('foo', value, expires) >>> cache.get('foo', expires - Timedelta('1 minute')) 1 >>> cache.get('foo', expires + Timedelta('1 minute')) Traceback (most recent call last): ... KeyError: 'foo' """ def __init__(self, cache=None): if cache is not None: self._cache = cache else: self._cache = {} def get(self, key, dt): """Get the value of a cached object. Parameters ---------- key : any The key to lookup. dt : datetime The time of the lookup. Returns ------- result : any The value for ``key``. Raises ------ KeyError Raised if the key is not in the cache or the value for the key has expired. """ try: return self._cache[key].unwrap(dt) except Expired: del self._cache[key] raise KeyError(key) def set(self, key, value, expiration_dt): """Adds a new key value pair to the cache. Parameters ---------- key : any The key to use for the pair. value : any The value to store under the name ``key``. expiration_dt : datetime When should this mapping expire? The cache is considered invalid for dates **strictly greater** than ``expiration_dt``. """ self._cache[key] = CachedObject(value, expiration_dt) class dataframe_cache(MutableMapping): """A disk-backed cache for dataframes. ``dataframe_cache`` is a mutable mapping from string names to pandas DataFrame objects. This object may be used as a context manager to delete the cache directory on exit. Parameters ---------- path : str, optional The directory path to the cache. Files will be written as ``path/<keyname>``. lock : Lock, optional Thread lock for multithreaded/multiprocessed access to the cache. If not provided no locking will be used. clean_on_failure : bool, optional Should the directory be cleaned up if an exception is raised in the context manager. serialize : {'msgpack', 'pickle:<n>'}, optional How should the data be serialized. If ``'pickle'`` is passed, an optional pickle protocol can be passed like: ``'pickle:3'`` which says to use pickle protocol 3. Notes ----- The syntax ``cache[:]`` will load all key:value pairs into memory as a dictionary. The cache uses a temporary file format that is subject to change between versions of zipline. """ def __init__(self, path=None, lock=None, clean_on_failure=True, serialization='msgpack'): self.path = path if path is not None else mkdtemp() self.lock = lock if lock is not None else nop_context self.clean_on_failure = clean_on_failure if serialization == 'msgpack': self.serialize = pd.DataFrame.to_msgpack self.deserialize = pd.read_msgpack self._protocol = None else: s = serialization.split(':', 1) if s[0] != 'pickle': raise ValueError( "'serialization' must be either 'msgpack' or 'pickle[:n]'", ) self._protocol = int(s[1]) if len(s) == 2 else None self.serialize = self._serialize_pickle self.deserialize = pickle.load ensure_directory(self.path) def _serialize_pickle(self, df, path): with open(path, 'wb') as f: pickle.dump(df, f, protocol=self._protocol) def _keypath(self, key): return os.path.join(self.path, key) def __enter__(self): return self def __exit__(self, type_, value, tb): if not (self.clean_on_failure or value is None): # we are not cleaning up after a failure and there was an exception return with self.lock: rmtree(self.path) def __getitem__(self, key): if key == slice(None):
with self.lock: try: with open(self._keypath(key), 'rb') as f: return self.deserialize(f) except IOError as e: if e.errno != errno.ENOENT: raise raise KeyError(key) def __setitem__(self, key, value): with self.lock: self.serialize(value, self._keypath(key)) def __delitem__(self, key): with self.lock: try: os.remove(self._keypath(key)) except OSError as e: if e.errno == errno.ENOENT: # raise a keyerror if this directory did not exist raise KeyError(key) # reraise the actual oserror otherwise raise def __iter__(self): return iter(os.listdir(self.path)) def __len__(self): return len(os.listdir(self.path)) def __repr__(self): return '<%s: keys={%s}>' % ( type(self).__name__, ', '.join(map(repr, sorted(self))), ) class working_file(object): """A context manager for managing a temporary file that will be moved to a non-temporary location if no exceptions are raised in the context. Parameters ---------- final_path : str The location to move the file when committing. *args, **kwargs Forwarded to NamedTemporaryFile. Notes ----- The file is moved on __exit__ if there are no exceptions. ``working_file`` uses :func:`shutil.move` to move the actual files, meaning it has as strong of guarantees as :func:`shutil.move`. """ def __init__(self, final_path, *args, **kwargs): self._tmpfile = NamedTemporaryFile(delete=False, *args, **kwargs) self._final_path = final_path @property def path(self): """Alias for ``name`` to be consistent with :class:`~zipline.utils.cache.working_dir`. """ return self._tmpfile.name def _commit(self): """Sync the temporary file to the final path. """ move(self.path, self._final_path) def __enter__(self): self._tmpfile.__enter__() return self def __exit__(self, *exc_info): self._tmpfile.__exit__(*exc_info) if exc_info[0] is None: self._commit() class working_dir(object): """A context manager for managing a temporary directory that will be moved to a non-temporary location if no exceptions are raised in the context. Parameters ---------- final_path : str The location to move the file when committing. *args, **kwargs Forwarded to tmp_dir. Notes ----- The file is moved on __exit__ if there are no exceptions. ``working_dir`` uses :func:`dir_util.copy_tree` to move the actual files, meaning it has as strong of guarantees as :func:`dir_util.copy_tree`. """ def __init__(self, final_path, *args, **kwargs): self.path = mkdtemp() self._final_path = final_path def ensure_dir(self, *path_parts): """Ensures a subdirectory of the working directory. Parameters ---------- path_parts : iterable[str] The parts of the path after the working directory. """ path = self.getpath(*path_parts) ensure_directory(path) return path def getpath(self, *path_parts): """Get a path relative to the working directory. Parameters ---------- path_parts : iterable[str] The parts of the path after the working directory. """ return os.path.join(self.path, *path_parts) def _commit(self): """Sync the temporary directory to the final path. """ dir_util.copy_tree(self.path, self._final_path) def __enter__(self): return self def __exit__(self, *exc_info): if exc_info[0] is None: self._commit() rmtree(self.path)
return dict(self.items())
conditional_block
cache.py
""" Caching utilities for zipline """ from collections import MutableMapping import errno import os import pickle from distutils import dir_util from shutil import rmtree, move from tempfile import mkdtemp, NamedTemporaryFile import pandas as pd from .context_tricks import nop_context from .paths import ensure_directory from .sentinel import sentinel class Expired(Exception): """Marks that a :class:`CachedObject` has expired. """ ExpiredCachedObject = sentinel('ExpiredCachedObject') AlwaysExpired = sentinel('AlwaysExpired') class CachedObject(object): """ A simple struct for maintaining a cached object with an expiration date. Parameters ---------- value : object The object to cache. expires : datetime-like Expiration date of `value`. The cache is considered invalid for dates **strictly greater** than `expires`. Examples -------- >>> from pandas import Timestamp, Timedelta >>> expires = Timestamp('2014', tz='UTC') >>> obj = CachedObject(1, expires) >>> obj.unwrap(expires - Timedelta('1 minute')) 1 >>> obj.unwrap(expires) 1 >>> obj.unwrap(expires + Timedelta('1 minute')) ... # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... Expired: 2014-01-01 00:00:00+00:00 """ def __init__(self, value, expires): self._value = value self._expires = expires @classmethod def expired(cls): """Construct a CachedObject that's expired at any time. """ return cls(ExpiredCachedObject, expires=AlwaysExpired) def unwrap(self, dt): """ Get the cached value. Returns ------- value : object The cached value. Raises ------ Expired Raised when `dt` is greater than self.expires. """ expires = self._expires if expires is AlwaysExpired or expires < dt: raise Expired(self._expires) return self._value def _unsafe_get_value(self): """You almost certainly shouldn't use this.""" return self._value class ExpiringCache(object): """ A cache of multiple CachedObjects, which returns the wrapped the value or raises and deletes the CachedObject if the value has expired. Parameters ---------- cache : dict-like, optional An instance of a dict-like object which needs to support at least: `__del__`, `__getitem__`, `__setitem__` If `None`, than a dict is used as a default. Examples -------- >>> from pandas import Timestamp, Timedelta >>> expires = Timestamp('2014', tz='UTC') >>> value = 1 >>> cache = ExpiringCache() >>> cache.set('foo', value, expires) >>> cache.get('foo', expires - Timedelta('1 minute')) 1 >>> cache.get('foo', expires + Timedelta('1 minute')) Traceback (most recent call last): ... KeyError: 'foo' """ def __init__(self, cache=None): if cache is not None: self._cache = cache else: self._cache = {} def get(self, key, dt): """Get the value of a cached object. Parameters ---------- key : any The key to lookup. dt : datetime The time of the lookup. Returns ------- result : any The value for ``key``. Raises ------ KeyError Raised if the key is not in the cache or the value for the key has expired. """ try: return self._cache[key].unwrap(dt) except Expired: del self._cache[key] raise KeyError(key) def set(self, key, value, expiration_dt): """Adds a new key value pair to the cache. Parameters ---------- key : any The key to use for the pair. value : any The value to store under the name ``key``. expiration_dt : datetime When should this mapping expire? The cache is considered invalid for dates **strictly greater** than ``expiration_dt``. """ self._cache[key] = CachedObject(value, expiration_dt) class dataframe_cache(MutableMapping): """A disk-backed cache for dataframes. ``dataframe_cache`` is a mutable mapping from string names to pandas DataFrame objects. This object may be used as a context manager to delete the cache directory on exit. Parameters ---------- path : str, optional The directory path to the cache. Files will be written as ``path/<keyname>``. lock : Lock, optional Thread lock for multithreaded/multiprocessed access to the cache. If not provided no locking will be used. clean_on_failure : bool, optional Should the directory be cleaned up if an exception is raised in the context manager. serialize : {'msgpack', 'pickle:<n>'}, optional How should the data be serialized. If ``'pickle'`` is passed, an optional pickle protocol can be passed like: ``'pickle:3'`` which says to use pickle protocol 3. Notes ----- The syntax ``cache[:]`` will load all key:value pairs into memory as a dictionary. The cache uses a temporary file format that is subject to change between versions of zipline. """ def __init__(self, path=None, lock=None, clean_on_failure=True, serialization='msgpack'): self.path = path if path is not None else mkdtemp() self.lock = lock if lock is not None else nop_context self.clean_on_failure = clean_on_failure if serialization == 'msgpack': self.serialize = pd.DataFrame.to_msgpack self.deserialize = pd.read_msgpack self._protocol = None else: s = serialization.split(':', 1) if s[0] != 'pickle': raise ValueError( "'serialization' must be either 'msgpack' or 'pickle[:n]'", ) self._protocol = int(s[1]) if len(s) == 2 else None self.serialize = self._serialize_pickle self.deserialize = pickle.load ensure_directory(self.path) def _serialize_pickle(self, df, path): with open(path, 'wb') as f: pickle.dump(df, f, protocol=self._protocol) def _keypath(self, key): return os.path.join(self.path, key) def __enter__(self): return self def __exit__(self, type_, value, tb): if not (self.clean_on_failure or value is None): # we are not cleaning up after a failure and there was an exception return with self.lock: rmtree(self.path) def __getitem__(self, key): if key == slice(None): return dict(self.items()) with self.lock: try: with open(self._keypath(key), 'rb') as f: return self.deserialize(f) except IOError as e: if e.errno != errno.ENOENT: raise raise KeyError(key) def __setitem__(self, key, value): with self.lock: self.serialize(value, self._keypath(key)) def __delitem__(self, key): with self.lock: try: os.remove(self._keypath(key)) except OSError as e: if e.errno == errno.ENOENT: # raise a keyerror if this directory did not exist raise KeyError(key) # reraise the actual oserror otherwise raise def __iter__(self): return iter(os.listdir(self.path)) def __len__(self): return len(os.listdir(self.path)) def __repr__(self): return '<%s: keys={%s}>' % ( type(self).__name__, ', '.join(map(repr, sorted(self))), ) class working_file(object): """A context manager for managing a temporary file that will be moved to a non-temporary location if no exceptions are raised in the context. Parameters ---------- final_path : str The location to move the file when committing. *args, **kwargs Forwarded to NamedTemporaryFile. Notes ----- The file is moved on __exit__ if there are no exceptions. ``working_file`` uses :func:`shutil.move` to move the actual files, meaning it has as strong of guarantees as :func:`shutil.move`. """ def __init__(self, final_path, *args, **kwargs): self._tmpfile = NamedTemporaryFile(delete=False, *args, **kwargs) self._final_path = final_path @property def path(self): """Alias for ``name`` to be consistent with :class:`~zipline.utils.cache.working_dir`. """ return self._tmpfile.name def _commit(self): """Sync the temporary file to the final path. """ move(self.path, self._final_path) def __enter__(self): self._tmpfile.__enter__() return self def __exit__(self, *exc_info): self._tmpfile.__exit__(*exc_info) if exc_info[0] is None: self._commit() class working_dir(object): """A context manager for managing a temporary directory that will be moved to a non-temporary location if no exceptions are raised in the context. Parameters ---------- final_path : str The location to move the file when committing. *args, **kwargs Forwarded to tmp_dir. Notes ----- The file is moved on __exit__ if there are no exceptions. ``working_dir`` uses :func:`dir_util.copy_tree` to move the actual files, meaning it has as strong of guarantees as :func:`dir_util.copy_tree`. """ def __init__(self, final_path, *args, **kwargs): self.path = mkdtemp() self._final_path = final_path def ensure_dir(self, *path_parts):
def getpath(self, *path_parts): """Get a path relative to the working directory. Parameters ---------- path_parts : iterable[str] The parts of the path after the working directory. """ return os.path.join(self.path, *path_parts) def _commit(self): """Sync the temporary directory to the final path. """ dir_util.copy_tree(self.path, self._final_path) def __enter__(self): return self def __exit__(self, *exc_info): if exc_info[0] is None: self._commit() rmtree(self.path)
"""Ensures a subdirectory of the working directory. Parameters ---------- path_parts : iterable[str] The parts of the path after the working directory. """ path = self.getpath(*path_parts) ensure_directory(path) return path
identifier_body
caddi2018_e.py
def main() -> None:
if __name__ == '__main__': main()
N = int(input()) A = [int(x) for x in input().split()] rev_A = A[:] left = [-1] * N left_cnt = [0] * N A_left = [A[0]] for i in range(1, N): if rev_A[i-1] < rev_A[i]: cnt = 0 while rev_A[i-1] pass elif rev_A[i-1] < rev_A[i] * 4: now = i-1 while left[now] != -1: now = left[now] left[i] = now A_left.append(A[i]) left[i] = i-1 else: pass ans = 10 ** 9 for i in range(N + 1): A = AA[:] cnt = 0 if i > 0: A[i-1] *= -2 cnt += 1 for j in reversed(range(i-1)): A[j] *= -2 cnt += 1 while A[j] > A[j+1]: A[j] *= 4 cnt += 2 for j in range(i+1, N): while A[j-1] > A[j]: A[j] *= 4 cnt += 2 print(i, cnt, A) ans = min(ans, cnt) print(ans)
identifier_body
caddi2018_e.py
def main() -> None: N = int(input()) A = [int(x) for x in input().split()] rev_A = A[:] left = [-1] * N left_cnt = [0] * N A_left = [A[0]] for i in range(1, N): if rev_A[i-1] < rev_A[i]: cnt = 0 while rev_A[i-1] pass elif rev_A[i-1] < rev_A[i] * 4: now = i-1 while left[now] != -1: now = left[now] left[i] = now A_left.append(A[i]) left[i] = i-1 else: pass ans = 10 ** 9 for i in range(N + 1): A = AA[:] cnt = 0 if i > 0: A[i-1] *= -2 cnt += 1 for j in reversed(range(i-1)): A[j] *= -2 cnt += 1 while A[j] > A[j+1]: A[j] *= 4 cnt += 2 for j in range(i+1, N): while A[j-1] > A[j]:
print(i, cnt, A) ans = min(ans, cnt) print(ans) if __name__ == '__main__': main()
A[j] *= 4 cnt += 2
conditional_block
caddi2018_e.py
def
() -> None: N = int(input()) A = [int(x) for x in input().split()] rev_A = A[:] left = [-1] * N left_cnt = [0] * N A_left = [A[0]] for i in range(1, N): if rev_A[i-1] < rev_A[i]: cnt = 0 while rev_A[i-1] pass elif rev_A[i-1] < rev_A[i] * 4: now = i-1 while left[now] != -1: now = left[now] left[i] = now A_left.append(A[i]) left[i] = i-1 else: pass ans = 10 ** 9 for i in range(N + 1): A = AA[:] cnt = 0 if i > 0: A[i-1] *= -2 cnt += 1 for j in reversed(range(i-1)): A[j] *= -2 cnt += 1 while A[j] > A[j+1]: A[j] *= 4 cnt += 2 for j in range(i+1, N): while A[j-1] > A[j]: A[j] *= 4 cnt += 2 print(i, cnt, A) ans = min(ans, cnt) print(ans) if __name__ == '__main__': main()
main
identifier_name
caddi2018_e.py
def main() -> None: N = int(input()) A = [int(x) for x in input().split()] rev_A = A[:] left = [-1] * N left_cnt = [0] * N A_left = [A[0]] for i in range(1, N): if rev_A[i-1] < rev_A[i]:
while rev_A[i-1] pass elif rev_A[i-1] < rev_A[i] * 4: now = i-1 while left[now] != -1: now = left[now] left[i] = now A_left.append(A[i]) left[i] = i-1 else: pass ans = 10 ** 9 for i in range(N + 1): A = AA[:] cnt = 0 if i > 0: A[i-1] *= -2 cnt += 1 for j in reversed(range(i-1)): A[j] *= -2 cnt += 1 while A[j] > A[j+1]: A[j] *= 4 cnt += 2 for j in range(i+1, N): while A[j-1] > A[j]: A[j] *= 4 cnt += 2 print(i, cnt, A) ans = min(ans, cnt) print(ans) if __name__ == '__main__': main()
cnt = 0
random_line_split
pants_daemon.py
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import logging import os import sys import threading from contextlib import contextmanager from dataclasses import dataclass from setproctitle import setproctitle as set_process_title from pants.base.build_environment import get_buildroot from pants.base.exception_sink import ExceptionSink, SignalHandler from pants.base.exiter import Exiter from pants.bin.daemon_pants_runner import DaemonPantsRunner from pants.engine.native import Native from pants.engine.rules import UnionMembership from pants.init.engine_initializer import EngineInitializer from pants.init.logging import init_rust_logger, setup_logging from pants.init.options_initializer import BuildConfigInitializer, OptionsInitializer from pants.option.options_bootstrapper import OptionsBootstrapper from pants.option.options_fingerprinter import OptionsFingerprinter from pants.option.scope import GLOBAL_SCOPE from pants.pantsd.process_manager import FingerprintedProcessManager from pants.pantsd.service.fs_event_service import FSEventService from pants.pantsd.service.pailgun_service import PailgunService from pants.pantsd.service.pants_service import PantsServices from pants.pantsd.service.scheduler_service import SchedulerService from pants.pantsd.service.store_gc_service import StoreGCService from pants.pantsd.watchman_launcher import WatchmanLauncher from pants.util.contextutil import stdio_as from pants.util.memo import memoized_property from pants.util.strutil import ensure_text class _LoggerStream(object): """A sys.std{out,err} replacement that pipes output to a logger. N.B. `logging.Logger` expects unicode. However, most of our outstream logic, such as in `exiter.py`, will use `sys.std{out,err}.buffer` and thus a bytes interface. So, we must provide a `buffer` property, and change the semantics of the buffer to always convert the message to unicode. This is an unfortunate code smell, as `logging` does not expose a bytes interface so this is the best solution we could think of. """ def __init__(self, logger, log_level, handler): """ :param logging.Logger logger: The logger instance to emit writes to. :param int log_level: The log level to use for the given logger. :param Handler handler: The underlying log handler, for determining the fileno to support faulthandler logging. """ self._logger = logger self._log_level = log_level self._handler = handler def write(self, msg): msg = ensure_text(msg) for line in msg.rstrip().splitlines(): # The log only accepts text, and will raise a decoding error if the default encoding is ascii # if provided a bytes input for unicode text. line = ensure_text(line)
def isatty(self): return False def fileno(self): return self._handler.stream.fileno() @property def buffer(self): return self class PantsDaemonSignalHandler(SignalHandler): def __init__(self, daemon): super().__init__() self._daemon = daemon def handle_sigint(self, signum, _frame): self._daemon.terminate(include_watchman=False) class PantsDaemon(FingerprintedProcessManager): """A daemon that manages PantsService instances.""" JOIN_TIMEOUT_SECONDS = 1 LOG_NAME = "pantsd.log" class StartupFailure(Exception): """Represents a failure to start pantsd.""" class RuntimeFailure(Exception): """Represents a pantsd failure at runtime, usually from an underlying service failure.""" @dataclass(frozen=True) class Handle: """A handle to a "probably running" pantsd instance. We attempt to verify that the pantsd instance is still running when we create a Handle, but after it has been created it is entirely process that the pantsd instance perishes. """ pid: int port: int metadata_base_dir: str class Factory: @classmethod def maybe_launch(cls, options_bootstrapper): """Creates and launches a daemon instance if one does not already exist. :param OptionsBootstrapper options_bootstrapper: The bootstrap options. :returns: A Handle for the running pantsd instance. :rtype: PantsDaemon.Handle """ stub_pantsd = cls.create(options_bootstrapper, full_init=False) with stub_pantsd._services.lifecycle_lock: if stub_pantsd.needs_restart(stub_pantsd.options_fingerprint): # Once we determine we actually need to launch, recreate with full initialization. pantsd = cls.create(options_bootstrapper) return pantsd.launch() else: # We're already launched. return PantsDaemon.Handle( stub_pantsd.await_pid(10), stub_pantsd.read_named_socket("pailgun", int), stub_pantsd._metadata_base_dir, ) @classmethod def restart(cls, options_bootstrapper): """Restarts a running daemon instance. :param OptionsBootstrapper options_bootstrapper: The bootstrap options. :returns: A Handle for the pantsd instance. :rtype: PantsDaemon.Handle """ pantsd = cls.create(options_bootstrapper) with pantsd._services.lifecycle_lock: # N.B. This will call `pantsd.terminate()` before starting. return pantsd.launch() @classmethod def create(cls, options_bootstrapper, full_init=True): """ :param OptionsBootstrapper options_bootstrapper: The bootstrap options. :param bool full_init: Whether or not to fully initialize an engine et al for the purposes of spawning a new daemon. `full_init=False` is intended primarily for lightweight lifecycle checks (since there is a ~1s overhead to initialize the engine). See the impl of `maybe_launch` for an example of the intended usage. """ bootstrap_options = options_bootstrapper.bootstrap_options bootstrap_options_values = bootstrap_options.for_global_scope() # TODO: https://github.com/pantsbuild/pants/issues/3479 watchman = WatchmanLauncher.create(bootstrap_options_values).watchman if full_init: build_root = get_buildroot() native = Native() build_config = BuildConfigInitializer.get(options_bootstrapper) legacy_graph_scheduler = EngineInitializer.setup_legacy_graph( native, options_bootstrapper, build_config ) services = cls._setup_services( build_root, bootstrap_options_values, legacy_graph_scheduler, watchman, union_membership=UnionMembership(build_config.union_rules()), ) else: build_root = None native = None services = PantsServices() return PantsDaemon( native=native, build_root=build_root, work_dir=bootstrap_options_values.pants_workdir, log_level=bootstrap_options_values.level.upper(), services=services, metadata_base_dir=bootstrap_options_values.pants_subprocessdir, bootstrap_options=bootstrap_options, ) @staticmethod def _setup_services( build_root, bootstrap_options, legacy_graph_scheduler, watchman, union_membership: UnionMembership, ): """Initialize pantsd services. :returns: A PantsServices instance. """ should_shutdown_after_run = bootstrap_options.shutdown_pantsd_after_run fs_event_service = FSEventService(watchman, build_root,) pidfile_absolute = PantsDaemon.metadata_file_path( "pantsd", "pid", bootstrap_options.pants_subprocessdir ) if pidfile_absolute.startswith(build_root): pidfile = os.path.relpath(pidfile_absolute, build_root) else: pidfile = None logging.getLogger(__name__).warning( "Not watching pantsd pidfile because subprocessdir is outside of buildroot. Having " "subprocessdir be a child of buildroot (as it is by default) may help avoid stray " "pantsd processes." ) scheduler_service = SchedulerService( fs_event_service=fs_event_service, legacy_graph_scheduler=legacy_graph_scheduler, build_root=build_root, invalidation_globs=OptionsInitializer.compute_pantsd_invalidation_globs( build_root, bootstrap_options ), pantsd_pidfile=pidfile, union_membership=union_membership, ) pailgun_service = PailgunService( (bootstrap_options.pantsd_pailgun_host, bootstrap_options.pantsd_pailgun_port), DaemonPantsRunner, scheduler_service, should_shutdown_after_run, ) store_gc_service = StoreGCService(legacy_graph_scheduler.scheduler) return PantsServices( services=(fs_event_service, scheduler_service, pailgun_service, store_gc_service), port_map=dict(pailgun=pailgun_service.pailgun_port), ) def __init__( self, native, build_root, work_dir, log_level, services, metadata_base_dir, bootstrap_options=None, ): """ :param Native native: A `Native` instance. :param string build_root: The pants build root. :param string work_dir: The pants work directory. :param string log_level: The log level to use for daemon logging. :param PantsServices services: A registry of services to use in this run. :param string metadata_base_dir: The ProcessManager metadata base dir. :param Options bootstrap_options: The bootstrap options, if available. """ super().__init__(name="pantsd", metadata_base_dir=metadata_base_dir) self._native = native self._build_root = build_root self._work_dir = work_dir self._log_level = log_level self._services = services self._bootstrap_options = bootstrap_options self._log_show_rust_3rdparty = ( bootstrap_options.for_global_scope().log_show_rust_3rdparty if bootstrap_options else True ) self._log_dir = os.path.join(work_dir, self.name) self._logger = logging.getLogger(__name__) # N.B. This Event is used as nothing more than a convenient atomic flag - nothing waits on it. self._kill_switch = threading.Event() @memoized_property def watchman_launcher(self): return WatchmanLauncher.create(self._bootstrap_options.for_global_scope()) @property def is_killed(self): return self._kill_switch.is_set() @property def options_fingerprint(self): return OptionsFingerprinter.combined_options_fingerprint_for_scope( GLOBAL_SCOPE, self._bootstrap_options, fingerprint_key="daemon", invert=True ) def shutdown(self, service_thread_map): """Gracefully terminate all services and kill the main PantsDaemon loop.""" with self._services.lifecycle_lock: for service, service_thread in service_thread_map.items(): self._logger.info(f"terminating pantsd service: {service}") service.terminate() service_thread.join(self.JOIN_TIMEOUT_SECONDS) self._logger.info("terminating pantsd") self._kill_switch.set() @staticmethod def _close_stdio(): """Close stdio streams to avoid output in the tty that launched pantsd.""" for fd in (sys.stdin, sys.stdout, sys.stderr): file_no = fd.fileno() fd.flush() fd.close() os.close(file_no) @contextmanager def _pantsd_logging(self): """A context manager that runs with pantsd logging. Asserts that stdio (represented by file handles 0, 1, 2) is closed to ensure that we can safely reuse those fd numbers. """ # Ensure that stdio is closed so that we can safely reuse those file descriptors. for fd in (0, 1, 2): try: os.fdopen(fd) raise AssertionError(f"pantsd logging cannot initialize while stdio is open: {fd}") except OSError: pass # Redirect stdio to /dev/null for the rest of the run, to reserve those file descriptors # for further forks. with stdio_as(stdin_fd=-1, stdout_fd=-1, stderr_fd=-1): # Reinitialize logging for the daemon context. init_rust_logger(self._log_level, self._log_show_rust_3rdparty) result = setup_logging( self._log_level, log_dir=self._log_dir, log_name=self.LOG_NAME, native=self._native, warnings_filter_regexes=self._bootstrap_options.for_global_scope(), ) self._native.override_thread_logging_destination_to_just_pantsd() # Do a python-level redirect of stdout/stderr, which will not disturb `0,1,2`. # TODO: Consider giving these pipes/actual fds, in order to make them "deep" replacements # for `1,2`, and allow them to be used via `stdio_as`. sys.stdout = _LoggerStream(logging.getLogger(), logging.INFO, result.log_handler) sys.stderr = _LoggerStream(logging.getLogger(), logging.WARN, result.log_handler) self._logger.debug("logging initialized") yield (result.log_handler.stream, result.log_handler.native_filename) def _setup_services(self, pants_services): for service in pants_services.services: self._logger.info(f"setting up service {service}") service.setup(self._services) @staticmethod def _make_thread(service): name = f"{service.__class__.__name__}Thread" def target(): Native().override_thread_logging_destination_to_just_pantsd() service.run() t = threading.Thread(target=target, name=name) t.daemon = True return t def _run_services(self, pants_services): """Service runner main loop.""" if not pants_services.services: self._logger.critical("no services to run, bailing!") return service_thread_map = { service: self._make_thread(service) for service in pants_services.services } # Start services. for service, service_thread in service_thread_map.items(): self._logger.info(f"starting service {service}") try: service_thread.start() except (RuntimeError, FSEventService.ServiceError): self.shutdown(service_thread_map) raise PantsDaemon.StartupFailure( f"service {service} failed to start, shutting down!" ) # Once all services are started, write our pid. self.write_pid() self.write_metadata_by_name( "pantsd", self.FINGERPRINT_KEY, ensure_text(self.options_fingerprint) ) # Monitor services. while not self.is_killed: for service, service_thread in service_thread_map.items(): if not service_thread.is_alive(): self.shutdown(service_thread_map) raise PantsDaemon.RuntimeFailure( f"service failure for {service}, shutting down!" ) else: # Avoid excessive CPU utilization. service_thread.join(self.JOIN_TIMEOUT_SECONDS) def _write_named_sockets(self, socket_map): """Write multiple named sockets using a socket mapping.""" for socket_name, socket_info in socket_map.items(): self.write_named_socket(socket_name, socket_info) def run_sync(self): """Synchronously run pantsd.""" os.environ.pop("PYTHONPATH") # Switch log output to the daemon's log stream from here forward. # Also, register an exiter using os._exit to ensure we only close stdio streams once. self._close_stdio() with self._pantsd_logging() as (log_stream, log_filename), ExceptionSink.exiter_as( lambda _: Exiter(exiter=os._exit) ): # We don't have any stdio streams to log to anymore, so we log to a file. # We don't override the faulthandler destination because the stream we get will proxy things # via the rust logging code, and faulthandler needs to be writing directly to a real file # descriptor. When pantsd logging was originally initialised, we already set up faulthandler # to log to the correct file descriptor, so don't override it. # # We can get tracebacks of the pantsd process by tailing the pantsd log and sending it # SIGUSR2. ExceptionSink.reset_interactive_output_stream( log_stream, override_faulthandler_destination=False, ) # Reset the log location and the backtrace preference from the global bootstrap options. global_bootstrap_options = self._bootstrap_options.for_global_scope() ExceptionSink.reset_should_print_backtrace_to_terminal( global_bootstrap_options.print_exception_stacktrace ) ExceptionSink.reset_log_location(global_bootstrap_options.pants_workdir) self._native.set_panic_handler() # Set the process name in ps output to 'pantsd' vs './pants compile src/etc:: -ldebug'. set_process_title(f"pantsd [{self._build_root}]") # Write service socket information to .pids. self._write_named_sockets(self._services.port_map) # Enter the main service runner loop. self._setup_services(self._services) self._run_services(self._services) def post_fork_child(self): """Post-fork() child callback for ProcessManager.daemon_spawn().""" spawn_control_env = dict( PANTS_ENTRYPOINT=f"{__name__}:launch", # The daemon should run under the same sys.path as us; so we ensure # this. NB: It will scrub PYTHONPATH once started to avoid infecting # its own unrelated subprocesses. PYTHONPATH=os.pathsep.join(sys.path), ) exec_env = {**os.environ, **spawn_control_env} # Pass all of sys.argv so that we can proxy arg flags e.g. `-ldebug`. cmd = [sys.executable] + sys.argv spawn_control_env_vars = " ".join(f"{k}={v}" for k, v in spawn_control_env.items()) cmd_line = " ".join(cmd) self._logger.debug(f"cmd is: {spawn_control_env_vars} {cmd_line}") # TODO: Improve error handling on launch failures. os.spawnve(os.P_NOWAIT, sys.executable, cmd, env=exec_env) def needs_launch(self): """Determines if pantsd needs to be launched. N.B. This should always be called under care of the `lifecycle_lock`. :returns: True if the daemon needs launching, False otherwise. :rtype: bool """ new_fingerprint = self.options_fingerprint self._logger.debug( "pantsd: is_alive={self.is_alive()} new_fingerprint={new_fingerprint} current_fingerprint={self.fingerprint}" ) return self.needs_restart(new_fingerprint) def launch(self): """Launches pantsd in a subprocess. N.B. This should always be called under care of the `lifecycle_lock`. :returns: A Handle for the pantsd instance. :rtype: PantsDaemon.Handle """ self.terminate(include_watchman=False) self.watchman_launcher.maybe_launch() self._logger.debug("launching pantsd") self.daemon_spawn() # Wait up to 60 seconds for pantsd to write its pidfile. pantsd_pid = self.await_pid(60) listening_port = self.read_named_socket("pailgun", int) self._logger.debug(f"pantsd is running at pid {self.pid}, pailgun port is {listening_port}") return self.Handle(pantsd_pid, listening_port, self._metadata_base_dir) def terminate(self, include_watchman=True): """Terminates pantsd and watchman. N.B. This should always be called under care of the `lifecycle_lock`. """ super().terminate() if include_watchman: self.watchman_launcher.terminate() def needs_restart(self, option_fingerprint): """Overrides ProcessManager.needs_restart, to account for the case where pantsd is running but we want to shutdown after this run. :param option_fingerprint: A fingeprint of the global bootstrap options. :return: True if the daemon needs to restart. """ should_shutdown_after_run = ( self._bootstrap_options.for_global_scope().shutdown_pantsd_after_run ) return super().needs_restart(option_fingerprint) or ( self.is_alive() and should_shutdown_after_run ) def launch(): """An external entrypoint that spawns a new pantsd instance.""" PantsDaemon.Factory.create(OptionsBootstrapper.create()).run_sync()
self._logger.log(self._log_level, line.rstrip()) def flush(self): return
random_line_split
pants_daemon.py
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import logging import os import sys import threading from contextlib import contextmanager from dataclasses import dataclass from setproctitle import setproctitle as set_process_title from pants.base.build_environment import get_buildroot from pants.base.exception_sink import ExceptionSink, SignalHandler from pants.base.exiter import Exiter from pants.bin.daemon_pants_runner import DaemonPantsRunner from pants.engine.native import Native from pants.engine.rules import UnionMembership from pants.init.engine_initializer import EngineInitializer from pants.init.logging import init_rust_logger, setup_logging from pants.init.options_initializer import BuildConfigInitializer, OptionsInitializer from pants.option.options_bootstrapper import OptionsBootstrapper from pants.option.options_fingerprinter import OptionsFingerprinter from pants.option.scope import GLOBAL_SCOPE from pants.pantsd.process_manager import FingerprintedProcessManager from pants.pantsd.service.fs_event_service import FSEventService from pants.pantsd.service.pailgun_service import PailgunService from pants.pantsd.service.pants_service import PantsServices from pants.pantsd.service.scheduler_service import SchedulerService from pants.pantsd.service.store_gc_service import StoreGCService from pants.pantsd.watchman_launcher import WatchmanLauncher from pants.util.contextutil import stdio_as from pants.util.memo import memoized_property from pants.util.strutil import ensure_text class _LoggerStream(object): """A sys.std{out,err} replacement that pipes output to a logger. N.B. `logging.Logger` expects unicode. However, most of our outstream logic, such as in `exiter.py`, will use `sys.std{out,err}.buffer` and thus a bytes interface. So, we must provide a `buffer` property, and change the semantics of the buffer to always convert the message to unicode. This is an unfortunate code smell, as `logging` does not expose a bytes interface so this is the best solution we could think of. """ def __init__(self, logger, log_level, handler): """ :param logging.Logger logger: The logger instance to emit writes to. :param int log_level: The log level to use for the given logger. :param Handler handler: The underlying log handler, for determining the fileno to support faulthandler logging. """ self._logger = logger self._log_level = log_level self._handler = handler def write(self, msg): msg = ensure_text(msg) for line in msg.rstrip().splitlines(): # The log only accepts text, and will raise a decoding error if the default encoding is ascii # if provided a bytes input for unicode text. line = ensure_text(line) self._logger.log(self._log_level, line.rstrip()) def flush(self): return def
(self): return False def fileno(self): return self._handler.stream.fileno() @property def buffer(self): return self class PantsDaemonSignalHandler(SignalHandler): def __init__(self, daemon): super().__init__() self._daemon = daemon def handle_sigint(self, signum, _frame): self._daemon.terminate(include_watchman=False) class PantsDaemon(FingerprintedProcessManager): """A daemon that manages PantsService instances.""" JOIN_TIMEOUT_SECONDS = 1 LOG_NAME = "pantsd.log" class StartupFailure(Exception): """Represents a failure to start pantsd.""" class RuntimeFailure(Exception): """Represents a pantsd failure at runtime, usually from an underlying service failure.""" @dataclass(frozen=True) class Handle: """A handle to a "probably running" pantsd instance. We attempt to verify that the pantsd instance is still running when we create a Handle, but after it has been created it is entirely process that the pantsd instance perishes. """ pid: int port: int metadata_base_dir: str class Factory: @classmethod def maybe_launch(cls, options_bootstrapper): """Creates and launches a daemon instance if one does not already exist. :param OptionsBootstrapper options_bootstrapper: The bootstrap options. :returns: A Handle for the running pantsd instance. :rtype: PantsDaemon.Handle """ stub_pantsd = cls.create(options_bootstrapper, full_init=False) with stub_pantsd._services.lifecycle_lock: if stub_pantsd.needs_restart(stub_pantsd.options_fingerprint): # Once we determine we actually need to launch, recreate with full initialization. pantsd = cls.create(options_bootstrapper) return pantsd.launch() else: # We're already launched. return PantsDaemon.Handle( stub_pantsd.await_pid(10), stub_pantsd.read_named_socket("pailgun", int), stub_pantsd._metadata_base_dir, ) @classmethod def restart(cls, options_bootstrapper): """Restarts a running daemon instance. :param OptionsBootstrapper options_bootstrapper: The bootstrap options. :returns: A Handle for the pantsd instance. :rtype: PantsDaemon.Handle """ pantsd = cls.create(options_bootstrapper) with pantsd._services.lifecycle_lock: # N.B. This will call `pantsd.terminate()` before starting. return pantsd.launch() @classmethod def create(cls, options_bootstrapper, full_init=True): """ :param OptionsBootstrapper options_bootstrapper: The bootstrap options. :param bool full_init: Whether or not to fully initialize an engine et al for the purposes of spawning a new daemon. `full_init=False` is intended primarily for lightweight lifecycle checks (since there is a ~1s overhead to initialize the engine). See the impl of `maybe_launch` for an example of the intended usage. """ bootstrap_options = options_bootstrapper.bootstrap_options bootstrap_options_values = bootstrap_options.for_global_scope() # TODO: https://github.com/pantsbuild/pants/issues/3479 watchman = WatchmanLauncher.create(bootstrap_options_values).watchman if full_init: build_root = get_buildroot() native = Native() build_config = BuildConfigInitializer.get(options_bootstrapper) legacy_graph_scheduler = EngineInitializer.setup_legacy_graph( native, options_bootstrapper, build_config ) services = cls._setup_services( build_root, bootstrap_options_values, legacy_graph_scheduler, watchman, union_membership=UnionMembership(build_config.union_rules()), ) else: build_root = None native = None services = PantsServices() return PantsDaemon( native=native, build_root=build_root, work_dir=bootstrap_options_values.pants_workdir, log_level=bootstrap_options_values.level.upper(), services=services, metadata_base_dir=bootstrap_options_values.pants_subprocessdir, bootstrap_options=bootstrap_options, ) @staticmethod def _setup_services( build_root, bootstrap_options, legacy_graph_scheduler, watchman, union_membership: UnionMembership, ): """Initialize pantsd services. :returns: A PantsServices instance. """ should_shutdown_after_run = bootstrap_options.shutdown_pantsd_after_run fs_event_service = FSEventService(watchman, build_root,) pidfile_absolute = PantsDaemon.metadata_file_path( "pantsd", "pid", bootstrap_options.pants_subprocessdir ) if pidfile_absolute.startswith(build_root): pidfile = os.path.relpath(pidfile_absolute, build_root) else: pidfile = None logging.getLogger(__name__).warning( "Not watching pantsd pidfile because subprocessdir is outside of buildroot. Having " "subprocessdir be a child of buildroot (as it is by default) may help avoid stray " "pantsd processes." ) scheduler_service = SchedulerService( fs_event_service=fs_event_service, legacy_graph_scheduler=legacy_graph_scheduler, build_root=build_root, invalidation_globs=OptionsInitializer.compute_pantsd_invalidation_globs( build_root, bootstrap_options ), pantsd_pidfile=pidfile, union_membership=union_membership, ) pailgun_service = PailgunService( (bootstrap_options.pantsd_pailgun_host, bootstrap_options.pantsd_pailgun_port), DaemonPantsRunner, scheduler_service, should_shutdown_after_run, ) store_gc_service = StoreGCService(legacy_graph_scheduler.scheduler) return PantsServices( services=(fs_event_service, scheduler_service, pailgun_service, store_gc_service), port_map=dict(pailgun=pailgun_service.pailgun_port), ) def __init__( self, native, build_root, work_dir, log_level, services, metadata_base_dir, bootstrap_options=None, ): """ :param Native native: A `Native` instance. :param string build_root: The pants build root. :param string work_dir: The pants work directory. :param string log_level: The log level to use for daemon logging. :param PantsServices services: A registry of services to use in this run. :param string metadata_base_dir: The ProcessManager metadata base dir. :param Options bootstrap_options: The bootstrap options, if available. """ super().__init__(name="pantsd", metadata_base_dir=metadata_base_dir) self._native = native self._build_root = build_root self._work_dir = work_dir self._log_level = log_level self._services = services self._bootstrap_options = bootstrap_options self._log_show_rust_3rdparty = ( bootstrap_options.for_global_scope().log_show_rust_3rdparty if bootstrap_options else True ) self._log_dir = os.path.join(work_dir, self.name) self._logger = logging.getLogger(__name__) # N.B. This Event is used as nothing more than a convenient atomic flag - nothing waits on it. self._kill_switch = threading.Event() @memoized_property def watchman_launcher(self): return WatchmanLauncher.create(self._bootstrap_options.for_global_scope()) @property def is_killed(self): return self._kill_switch.is_set() @property def options_fingerprint(self): return OptionsFingerprinter.combined_options_fingerprint_for_scope( GLOBAL_SCOPE, self._bootstrap_options, fingerprint_key="daemon", invert=True ) def shutdown(self, service_thread_map): """Gracefully terminate all services and kill the main PantsDaemon loop.""" with self._services.lifecycle_lock: for service, service_thread in service_thread_map.items(): self._logger.info(f"terminating pantsd service: {service}") service.terminate() service_thread.join(self.JOIN_TIMEOUT_SECONDS) self._logger.info("terminating pantsd") self._kill_switch.set() @staticmethod def _close_stdio(): """Close stdio streams to avoid output in the tty that launched pantsd.""" for fd in (sys.stdin, sys.stdout, sys.stderr): file_no = fd.fileno() fd.flush() fd.close() os.close(file_no) @contextmanager def _pantsd_logging(self): """A context manager that runs with pantsd logging. Asserts that stdio (represented by file handles 0, 1, 2) is closed to ensure that we can safely reuse those fd numbers. """ # Ensure that stdio is closed so that we can safely reuse those file descriptors. for fd in (0, 1, 2): try: os.fdopen(fd) raise AssertionError(f"pantsd logging cannot initialize while stdio is open: {fd}") except OSError: pass # Redirect stdio to /dev/null for the rest of the run, to reserve those file descriptors # for further forks. with stdio_as(stdin_fd=-1, stdout_fd=-1, stderr_fd=-1): # Reinitialize logging for the daemon context. init_rust_logger(self._log_level, self._log_show_rust_3rdparty) result = setup_logging( self._log_level, log_dir=self._log_dir, log_name=self.LOG_NAME, native=self._native, warnings_filter_regexes=self._bootstrap_options.for_global_scope(), ) self._native.override_thread_logging_destination_to_just_pantsd() # Do a python-level redirect of stdout/stderr, which will not disturb `0,1,2`. # TODO: Consider giving these pipes/actual fds, in order to make them "deep" replacements # for `1,2`, and allow them to be used via `stdio_as`. sys.stdout = _LoggerStream(logging.getLogger(), logging.INFO, result.log_handler) sys.stderr = _LoggerStream(logging.getLogger(), logging.WARN, result.log_handler) self._logger.debug("logging initialized") yield (result.log_handler.stream, result.log_handler.native_filename) def _setup_services(self, pants_services): for service in pants_services.services: self._logger.info(f"setting up service {service}") service.setup(self._services) @staticmethod def _make_thread(service): name = f"{service.__class__.__name__}Thread" def target(): Native().override_thread_logging_destination_to_just_pantsd() service.run() t = threading.Thread(target=target, name=name) t.daemon = True return t def _run_services(self, pants_services): """Service runner main loop.""" if not pants_services.services: self._logger.critical("no services to run, bailing!") return service_thread_map = { service: self._make_thread(service) for service in pants_services.services } # Start services. for service, service_thread in service_thread_map.items(): self._logger.info(f"starting service {service}") try: service_thread.start() except (RuntimeError, FSEventService.ServiceError): self.shutdown(service_thread_map) raise PantsDaemon.StartupFailure( f"service {service} failed to start, shutting down!" ) # Once all services are started, write our pid. self.write_pid() self.write_metadata_by_name( "pantsd", self.FINGERPRINT_KEY, ensure_text(self.options_fingerprint) ) # Monitor services. while not self.is_killed: for service, service_thread in service_thread_map.items(): if not service_thread.is_alive(): self.shutdown(service_thread_map) raise PantsDaemon.RuntimeFailure( f"service failure for {service}, shutting down!" ) else: # Avoid excessive CPU utilization. service_thread.join(self.JOIN_TIMEOUT_SECONDS) def _write_named_sockets(self, socket_map): """Write multiple named sockets using a socket mapping.""" for socket_name, socket_info in socket_map.items(): self.write_named_socket(socket_name, socket_info) def run_sync(self): """Synchronously run pantsd.""" os.environ.pop("PYTHONPATH") # Switch log output to the daemon's log stream from here forward. # Also, register an exiter using os._exit to ensure we only close stdio streams once. self._close_stdio() with self._pantsd_logging() as (log_stream, log_filename), ExceptionSink.exiter_as( lambda _: Exiter(exiter=os._exit) ): # We don't have any stdio streams to log to anymore, so we log to a file. # We don't override the faulthandler destination because the stream we get will proxy things # via the rust logging code, and faulthandler needs to be writing directly to a real file # descriptor. When pantsd logging was originally initialised, we already set up faulthandler # to log to the correct file descriptor, so don't override it. # # We can get tracebacks of the pantsd process by tailing the pantsd log and sending it # SIGUSR2. ExceptionSink.reset_interactive_output_stream( log_stream, override_faulthandler_destination=False, ) # Reset the log location and the backtrace preference from the global bootstrap options. global_bootstrap_options = self._bootstrap_options.for_global_scope() ExceptionSink.reset_should_print_backtrace_to_terminal( global_bootstrap_options.print_exception_stacktrace ) ExceptionSink.reset_log_location(global_bootstrap_options.pants_workdir) self._native.set_panic_handler() # Set the process name in ps output to 'pantsd' vs './pants compile src/etc:: -ldebug'. set_process_title(f"pantsd [{self._build_root}]") # Write service socket information to .pids. self._write_named_sockets(self._services.port_map) # Enter the main service runner loop. self._setup_services(self._services) self._run_services(self._services) def post_fork_child(self): """Post-fork() child callback for ProcessManager.daemon_spawn().""" spawn_control_env = dict( PANTS_ENTRYPOINT=f"{__name__}:launch", # The daemon should run under the same sys.path as us; so we ensure # this. NB: It will scrub PYTHONPATH once started to avoid infecting # its own unrelated subprocesses. PYTHONPATH=os.pathsep.join(sys.path), ) exec_env = {**os.environ, **spawn_control_env} # Pass all of sys.argv so that we can proxy arg flags e.g. `-ldebug`. cmd = [sys.executable] + sys.argv spawn_control_env_vars = " ".join(f"{k}={v}" for k, v in spawn_control_env.items()) cmd_line = " ".join(cmd) self._logger.debug(f"cmd is: {spawn_control_env_vars} {cmd_line}") # TODO: Improve error handling on launch failures. os.spawnve(os.P_NOWAIT, sys.executable, cmd, env=exec_env) def needs_launch(self): """Determines if pantsd needs to be launched. N.B. This should always be called under care of the `lifecycle_lock`. :returns: True if the daemon needs launching, False otherwise. :rtype: bool """ new_fingerprint = self.options_fingerprint self._logger.debug( "pantsd: is_alive={self.is_alive()} new_fingerprint={new_fingerprint} current_fingerprint={self.fingerprint}" ) return self.needs_restart(new_fingerprint) def launch(self): """Launches pantsd in a subprocess. N.B. This should always be called under care of the `lifecycle_lock`. :returns: A Handle for the pantsd instance. :rtype: PantsDaemon.Handle """ self.terminate(include_watchman=False) self.watchman_launcher.maybe_launch() self._logger.debug("launching pantsd") self.daemon_spawn() # Wait up to 60 seconds for pantsd to write its pidfile. pantsd_pid = self.await_pid(60) listening_port = self.read_named_socket("pailgun", int) self._logger.debug(f"pantsd is running at pid {self.pid}, pailgun port is {listening_port}") return self.Handle(pantsd_pid, listening_port, self._metadata_base_dir) def terminate(self, include_watchman=True): """Terminates pantsd and watchman. N.B. This should always be called under care of the `lifecycle_lock`. """ super().terminate() if include_watchman: self.watchman_launcher.terminate() def needs_restart(self, option_fingerprint): """Overrides ProcessManager.needs_restart, to account for the case where pantsd is running but we want to shutdown after this run. :param option_fingerprint: A fingeprint of the global bootstrap options. :return: True if the daemon needs to restart. """ should_shutdown_after_run = ( self._bootstrap_options.for_global_scope().shutdown_pantsd_after_run ) return super().needs_restart(option_fingerprint) or ( self.is_alive() and should_shutdown_after_run ) def launch(): """An external entrypoint that spawns a new pantsd instance.""" PantsDaemon.Factory.create(OptionsBootstrapper.create()).run_sync()
isatty
identifier_name
pants_daemon.py
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import logging import os import sys import threading from contextlib import contextmanager from dataclasses import dataclass from setproctitle import setproctitle as set_process_title from pants.base.build_environment import get_buildroot from pants.base.exception_sink import ExceptionSink, SignalHandler from pants.base.exiter import Exiter from pants.bin.daemon_pants_runner import DaemonPantsRunner from pants.engine.native import Native from pants.engine.rules import UnionMembership from pants.init.engine_initializer import EngineInitializer from pants.init.logging import init_rust_logger, setup_logging from pants.init.options_initializer import BuildConfigInitializer, OptionsInitializer from pants.option.options_bootstrapper import OptionsBootstrapper from pants.option.options_fingerprinter import OptionsFingerprinter from pants.option.scope import GLOBAL_SCOPE from pants.pantsd.process_manager import FingerprintedProcessManager from pants.pantsd.service.fs_event_service import FSEventService from pants.pantsd.service.pailgun_service import PailgunService from pants.pantsd.service.pants_service import PantsServices from pants.pantsd.service.scheduler_service import SchedulerService from pants.pantsd.service.store_gc_service import StoreGCService from pants.pantsd.watchman_launcher import WatchmanLauncher from pants.util.contextutil import stdio_as from pants.util.memo import memoized_property from pants.util.strutil import ensure_text class _LoggerStream(object): """A sys.std{out,err} replacement that pipes output to a logger. N.B. `logging.Logger` expects unicode. However, most of our outstream logic, such as in `exiter.py`, will use `sys.std{out,err}.buffer` and thus a bytes interface. So, we must provide a `buffer` property, and change the semantics of the buffer to always convert the message to unicode. This is an unfortunate code smell, as `logging` does not expose a bytes interface so this is the best solution we could think of. """ def __init__(self, logger, log_level, handler): """ :param logging.Logger logger: The logger instance to emit writes to. :param int log_level: The log level to use for the given logger. :param Handler handler: The underlying log handler, for determining the fileno to support faulthandler logging. """ self._logger = logger self._log_level = log_level self._handler = handler def write(self, msg): msg = ensure_text(msg) for line in msg.rstrip().splitlines(): # The log only accepts text, and will raise a decoding error if the default encoding is ascii # if provided a bytes input for unicode text. line = ensure_text(line) self._logger.log(self._log_level, line.rstrip()) def flush(self): return def isatty(self): return False def fileno(self): return self._handler.stream.fileno() @property def buffer(self): return self class PantsDaemonSignalHandler(SignalHandler): def __init__(self, daemon): super().__init__() self._daemon = daemon def handle_sigint(self, signum, _frame): self._daemon.terminate(include_watchman=False) class PantsDaemon(FingerprintedProcessManager): """A daemon that manages PantsService instances.""" JOIN_TIMEOUT_SECONDS = 1 LOG_NAME = "pantsd.log" class StartupFailure(Exception): """Represents a failure to start pantsd.""" class RuntimeFailure(Exception): """Represents a pantsd failure at runtime, usually from an underlying service failure.""" @dataclass(frozen=True) class Handle: """A handle to a "probably running" pantsd instance. We attempt to verify that the pantsd instance is still running when we create a Handle, but after it has been created it is entirely process that the pantsd instance perishes. """ pid: int port: int metadata_base_dir: str class Factory: @classmethod def maybe_launch(cls, options_bootstrapper): """Creates and launches a daemon instance if one does not already exist. :param OptionsBootstrapper options_bootstrapper: The bootstrap options. :returns: A Handle for the running pantsd instance. :rtype: PantsDaemon.Handle """ stub_pantsd = cls.create(options_bootstrapper, full_init=False) with stub_pantsd._services.lifecycle_lock: if stub_pantsd.needs_restart(stub_pantsd.options_fingerprint): # Once we determine we actually need to launch, recreate with full initialization. pantsd = cls.create(options_bootstrapper) return pantsd.launch() else: # We're already launched. return PantsDaemon.Handle( stub_pantsd.await_pid(10), stub_pantsd.read_named_socket("pailgun", int), stub_pantsd._metadata_base_dir, ) @classmethod def restart(cls, options_bootstrapper): """Restarts a running daemon instance. :param OptionsBootstrapper options_bootstrapper: The bootstrap options. :returns: A Handle for the pantsd instance. :rtype: PantsDaemon.Handle """ pantsd = cls.create(options_bootstrapper) with pantsd._services.lifecycle_lock: # N.B. This will call `pantsd.terminate()` before starting. return pantsd.launch() @classmethod def create(cls, options_bootstrapper, full_init=True): """ :param OptionsBootstrapper options_bootstrapper: The bootstrap options. :param bool full_init: Whether or not to fully initialize an engine et al for the purposes of spawning a new daemon. `full_init=False` is intended primarily for lightweight lifecycle checks (since there is a ~1s overhead to initialize the engine). See the impl of `maybe_launch` for an example of the intended usage. """ bootstrap_options = options_bootstrapper.bootstrap_options bootstrap_options_values = bootstrap_options.for_global_scope() # TODO: https://github.com/pantsbuild/pants/issues/3479 watchman = WatchmanLauncher.create(bootstrap_options_values).watchman if full_init: build_root = get_buildroot() native = Native() build_config = BuildConfigInitializer.get(options_bootstrapper) legacy_graph_scheduler = EngineInitializer.setup_legacy_graph( native, options_bootstrapper, build_config ) services = cls._setup_services( build_root, bootstrap_options_values, legacy_graph_scheduler, watchman, union_membership=UnionMembership(build_config.union_rules()), ) else: build_root = None native = None services = PantsServices() return PantsDaemon( native=native, build_root=build_root, work_dir=bootstrap_options_values.pants_workdir, log_level=bootstrap_options_values.level.upper(), services=services, metadata_base_dir=bootstrap_options_values.pants_subprocessdir, bootstrap_options=bootstrap_options, ) @staticmethod def _setup_services( build_root, bootstrap_options, legacy_graph_scheduler, watchman, union_membership: UnionMembership, ): """Initialize pantsd services. :returns: A PantsServices instance. """ should_shutdown_after_run = bootstrap_options.shutdown_pantsd_after_run fs_event_service = FSEventService(watchman, build_root,) pidfile_absolute = PantsDaemon.metadata_file_path( "pantsd", "pid", bootstrap_options.pants_subprocessdir ) if pidfile_absolute.startswith(build_root): pidfile = os.path.relpath(pidfile_absolute, build_root) else: pidfile = None logging.getLogger(__name__).warning( "Not watching pantsd pidfile because subprocessdir is outside of buildroot. Having " "subprocessdir be a child of buildroot (as it is by default) may help avoid stray " "pantsd processes." ) scheduler_service = SchedulerService( fs_event_service=fs_event_service, legacy_graph_scheduler=legacy_graph_scheduler, build_root=build_root, invalidation_globs=OptionsInitializer.compute_pantsd_invalidation_globs( build_root, bootstrap_options ), pantsd_pidfile=pidfile, union_membership=union_membership, ) pailgun_service = PailgunService( (bootstrap_options.pantsd_pailgun_host, bootstrap_options.pantsd_pailgun_port), DaemonPantsRunner, scheduler_service, should_shutdown_after_run, ) store_gc_service = StoreGCService(legacy_graph_scheduler.scheduler) return PantsServices( services=(fs_event_service, scheduler_service, pailgun_service, store_gc_service), port_map=dict(pailgun=pailgun_service.pailgun_port), ) def __init__( self, native, build_root, work_dir, log_level, services, metadata_base_dir, bootstrap_options=None, ): """ :param Native native: A `Native` instance. :param string build_root: The pants build root. :param string work_dir: The pants work directory. :param string log_level: The log level to use for daemon logging. :param PantsServices services: A registry of services to use in this run. :param string metadata_base_dir: The ProcessManager metadata base dir. :param Options bootstrap_options: The bootstrap options, if available. """ super().__init__(name="pantsd", metadata_base_dir=metadata_base_dir) self._native = native self._build_root = build_root self._work_dir = work_dir self._log_level = log_level self._services = services self._bootstrap_options = bootstrap_options self._log_show_rust_3rdparty = ( bootstrap_options.for_global_scope().log_show_rust_3rdparty if bootstrap_options else True ) self._log_dir = os.path.join(work_dir, self.name) self._logger = logging.getLogger(__name__) # N.B. This Event is used as nothing more than a convenient atomic flag - nothing waits on it. self._kill_switch = threading.Event() @memoized_property def watchman_launcher(self): return WatchmanLauncher.create(self._bootstrap_options.for_global_scope()) @property def is_killed(self): return self._kill_switch.is_set() @property def options_fingerprint(self): return OptionsFingerprinter.combined_options_fingerprint_for_scope( GLOBAL_SCOPE, self._bootstrap_options, fingerprint_key="daemon", invert=True ) def shutdown(self, service_thread_map): """Gracefully terminate all services and kill the main PantsDaemon loop.""" with self._services.lifecycle_lock: for service, service_thread in service_thread_map.items(): self._logger.info(f"terminating pantsd service: {service}") service.terminate() service_thread.join(self.JOIN_TIMEOUT_SECONDS) self._logger.info("terminating pantsd") self._kill_switch.set() @staticmethod def _close_stdio(): """Close stdio streams to avoid output in the tty that launched pantsd.""" for fd in (sys.stdin, sys.stdout, sys.stderr): file_no = fd.fileno() fd.flush() fd.close() os.close(file_no) @contextmanager def _pantsd_logging(self): """A context manager that runs with pantsd logging. Asserts that stdio (represented by file handles 0, 1, 2) is closed to ensure that we can safely reuse those fd numbers. """ # Ensure that stdio is closed so that we can safely reuse those file descriptors. for fd in (0, 1, 2):
# Redirect stdio to /dev/null for the rest of the run, to reserve those file descriptors # for further forks. with stdio_as(stdin_fd=-1, stdout_fd=-1, stderr_fd=-1): # Reinitialize logging for the daemon context. init_rust_logger(self._log_level, self._log_show_rust_3rdparty) result = setup_logging( self._log_level, log_dir=self._log_dir, log_name=self.LOG_NAME, native=self._native, warnings_filter_regexes=self._bootstrap_options.for_global_scope(), ) self._native.override_thread_logging_destination_to_just_pantsd() # Do a python-level redirect of stdout/stderr, which will not disturb `0,1,2`. # TODO: Consider giving these pipes/actual fds, in order to make them "deep" replacements # for `1,2`, and allow them to be used via `stdio_as`. sys.stdout = _LoggerStream(logging.getLogger(), logging.INFO, result.log_handler) sys.stderr = _LoggerStream(logging.getLogger(), logging.WARN, result.log_handler) self._logger.debug("logging initialized") yield (result.log_handler.stream, result.log_handler.native_filename) def _setup_services(self, pants_services): for service in pants_services.services: self._logger.info(f"setting up service {service}") service.setup(self._services) @staticmethod def _make_thread(service): name = f"{service.__class__.__name__}Thread" def target(): Native().override_thread_logging_destination_to_just_pantsd() service.run() t = threading.Thread(target=target, name=name) t.daemon = True return t def _run_services(self, pants_services): """Service runner main loop.""" if not pants_services.services: self._logger.critical("no services to run, bailing!") return service_thread_map = { service: self._make_thread(service) for service in pants_services.services } # Start services. for service, service_thread in service_thread_map.items(): self._logger.info(f"starting service {service}") try: service_thread.start() except (RuntimeError, FSEventService.ServiceError): self.shutdown(service_thread_map) raise PantsDaemon.StartupFailure( f"service {service} failed to start, shutting down!" ) # Once all services are started, write our pid. self.write_pid() self.write_metadata_by_name( "pantsd", self.FINGERPRINT_KEY, ensure_text(self.options_fingerprint) ) # Monitor services. while not self.is_killed: for service, service_thread in service_thread_map.items(): if not service_thread.is_alive(): self.shutdown(service_thread_map) raise PantsDaemon.RuntimeFailure( f"service failure for {service}, shutting down!" ) else: # Avoid excessive CPU utilization. service_thread.join(self.JOIN_TIMEOUT_SECONDS) def _write_named_sockets(self, socket_map): """Write multiple named sockets using a socket mapping.""" for socket_name, socket_info in socket_map.items(): self.write_named_socket(socket_name, socket_info) def run_sync(self): """Synchronously run pantsd.""" os.environ.pop("PYTHONPATH") # Switch log output to the daemon's log stream from here forward. # Also, register an exiter using os._exit to ensure we only close stdio streams once. self._close_stdio() with self._pantsd_logging() as (log_stream, log_filename), ExceptionSink.exiter_as( lambda _: Exiter(exiter=os._exit) ): # We don't have any stdio streams to log to anymore, so we log to a file. # We don't override the faulthandler destination because the stream we get will proxy things # via the rust logging code, and faulthandler needs to be writing directly to a real file # descriptor. When pantsd logging was originally initialised, we already set up faulthandler # to log to the correct file descriptor, so don't override it. # # We can get tracebacks of the pantsd process by tailing the pantsd log and sending it # SIGUSR2. ExceptionSink.reset_interactive_output_stream( log_stream, override_faulthandler_destination=False, ) # Reset the log location and the backtrace preference from the global bootstrap options. global_bootstrap_options = self._bootstrap_options.for_global_scope() ExceptionSink.reset_should_print_backtrace_to_terminal( global_bootstrap_options.print_exception_stacktrace ) ExceptionSink.reset_log_location(global_bootstrap_options.pants_workdir) self._native.set_panic_handler() # Set the process name in ps output to 'pantsd' vs './pants compile src/etc:: -ldebug'. set_process_title(f"pantsd [{self._build_root}]") # Write service socket information to .pids. self._write_named_sockets(self._services.port_map) # Enter the main service runner loop. self._setup_services(self._services) self._run_services(self._services) def post_fork_child(self): """Post-fork() child callback for ProcessManager.daemon_spawn().""" spawn_control_env = dict( PANTS_ENTRYPOINT=f"{__name__}:launch", # The daemon should run under the same sys.path as us; so we ensure # this. NB: It will scrub PYTHONPATH once started to avoid infecting # its own unrelated subprocesses. PYTHONPATH=os.pathsep.join(sys.path), ) exec_env = {**os.environ, **spawn_control_env} # Pass all of sys.argv so that we can proxy arg flags e.g. `-ldebug`. cmd = [sys.executable] + sys.argv spawn_control_env_vars = " ".join(f"{k}={v}" for k, v in spawn_control_env.items()) cmd_line = " ".join(cmd) self._logger.debug(f"cmd is: {spawn_control_env_vars} {cmd_line}") # TODO: Improve error handling on launch failures. os.spawnve(os.P_NOWAIT, sys.executable, cmd, env=exec_env) def needs_launch(self): """Determines if pantsd needs to be launched. N.B. This should always be called under care of the `lifecycle_lock`. :returns: True if the daemon needs launching, False otherwise. :rtype: bool """ new_fingerprint = self.options_fingerprint self._logger.debug( "pantsd: is_alive={self.is_alive()} new_fingerprint={new_fingerprint} current_fingerprint={self.fingerprint}" ) return self.needs_restart(new_fingerprint) def launch(self): """Launches pantsd in a subprocess. N.B. This should always be called under care of the `lifecycle_lock`. :returns: A Handle for the pantsd instance. :rtype: PantsDaemon.Handle """ self.terminate(include_watchman=False) self.watchman_launcher.maybe_launch() self._logger.debug("launching pantsd") self.daemon_spawn() # Wait up to 60 seconds for pantsd to write its pidfile. pantsd_pid = self.await_pid(60) listening_port = self.read_named_socket("pailgun", int) self._logger.debug(f"pantsd is running at pid {self.pid}, pailgun port is {listening_port}") return self.Handle(pantsd_pid, listening_port, self._metadata_base_dir) def terminate(self, include_watchman=True): """Terminates pantsd and watchman. N.B. This should always be called under care of the `lifecycle_lock`. """ super().terminate() if include_watchman: self.watchman_launcher.terminate() def needs_restart(self, option_fingerprint): """Overrides ProcessManager.needs_restart, to account for the case where pantsd is running but we want to shutdown after this run. :param option_fingerprint: A fingeprint of the global bootstrap options. :return: True if the daemon needs to restart. """ should_shutdown_after_run = ( self._bootstrap_options.for_global_scope().shutdown_pantsd_after_run ) return super().needs_restart(option_fingerprint) or ( self.is_alive() and should_shutdown_after_run ) def launch(): """An external entrypoint that spawns a new pantsd instance.""" PantsDaemon.Factory.create(OptionsBootstrapper.create()).run_sync()
try: os.fdopen(fd) raise AssertionError(f"pantsd logging cannot initialize while stdio is open: {fd}") except OSError: pass
conditional_block
pants_daemon.py
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import logging import os import sys import threading from contextlib import contextmanager from dataclasses import dataclass from setproctitle import setproctitle as set_process_title from pants.base.build_environment import get_buildroot from pants.base.exception_sink import ExceptionSink, SignalHandler from pants.base.exiter import Exiter from pants.bin.daemon_pants_runner import DaemonPantsRunner from pants.engine.native import Native from pants.engine.rules import UnionMembership from pants.init.engine_initializer import EngineInitializer from pants.init.logging import init_rust_logger, setup_logging from pants.init.options_initializer import BuildConfigInitializer, OptionsInitializer from pants.option.options_bootstrapper import OptionsBootstrapper from pants.option.options_fingerprinter import OptionsFingerprinter from pants.option.scope import GLOBAL_SCOPE from pants.pantsd.process_manager import FingerprintedProcessManager from pants.pantsd.service.fs_event_service import FSEventService from pants.pantsd.service.pailgun_service import PailgunService from pants.pantsd.service.pants_service import PantsServices from pants.pantsd.service.scheduler_service import SchedulerService from pants.pantsd.service.store_gc_service import StoreGCService from pants.pantsd.watchman_launcher import WatchmanLauncher from pants.util.contextutil import stdio_as from pants.util.memo import memoized_property from pants.util.strutil import ensure_text class _LoggerStream(object): """A sys.std{out,err} replacement that pipes output to a logger. N.B. `logging.Logger` expects unicode. However, most of our outstream logic, such as in `exiter.py`, will use `sys.std{out,err}.buffer` and thus a bytes interface. So, we must provide a `buffer` property, and change the semantics of the buffer to always convert the message to unicode. This is an unfortunate code smell, as `logging` does not expose a bytes interface so this is the best solution we could think of. """ def __init__(self, logger, log_level, handler): """ :param logging.Logger logger: The logger instance to emit writes to. :param int log_level: The log level to use for the given logger. :param Handler handler: The underlying log handler, for determining the fileno to support faulthandler logging. """ self._logger = logger self._log_level = log_level self._handler = handler def write(self, msg): msg = ensure_text(msg) for line in msg.rstrip().splitlines(): # The log only accepts text, and will raise a decoding error if the default encoding is ascii # if provided a bytes input for unicode text. line = ensure_text(line) self._logger.log(self._log_level, line.rstrip()) def flush(self): return def isatty(self): return False def fileno(self): return self._handler.stream.fileno() @property def buffer(self): return self class PantsDaemonSignalHandler(SignalHandler): def __init__(self, daemon): super().__init__() self._daemon = daemon def handle_sigint(self, signum, _frame): self._daemon.terminate(include_watchman=False) class PantsDaemon(FingerprintedProcessManager): """A daemon that manages PantsService instances.""" JOIN_TIMEOUT_SECONDS = 1 LOG_NAME = "pantsd.log" class StartupFailure(Exception): """Represents a failure to start pantsd.""" class RuntimeFailure(Exception): """Represents a pantsd failure at runtime, usually from an underlying service failure.""" @dataclass(frozen=True) class Handle: """A handle to a "probably running" pantsd instance. We attempt to verify that the pantsd instance is still running when we create a Handle, but after it has been created it is entirely process that the pantsd instance perishes. """ pid: int port: int metadata_base_dir: str class Factory: @classmethod def maybe_launch(cls, options_bootstrapper): """Creates and launches a daemon instance if one does not already exist. :param OptionsBootstrapper options_bootstrapper: The bootstrap options. :returns: A Handle for the running pantsd instance. :rtype: PantsDaemon.Handle """ stub_pantsd = cls.create(options_bootstrapper, full_init=False) with stub_pantsd._services.lifecycle_lock: if stub_pantsd.needs_restart(stub_pantsd.options_fingerprint): # Once we determine we actually need to launch, recreate with full initialization. pantsd = cls.create(options_bootstrapper) return pantsd.launch() else: # We're already launched. return PantsDaemon.Handle( stub_pantsd.await_pid(10), stub_pantsd.read_named_socket("pailgun", int), stub_pantsd._metadata_base_dir, ) @classmethod def restart(cls, options_bootstrapper): """Restarts a running daemon instance. :param OptionsBootstrapper options_bootstrapper: The bootstrap options. :returns: A Handle for the pantsd instance. :rtype: PantsDaemon.Handle """ pantsd = cls.create(options_bootstrapper) with pantsd._services.lifecycle_lock: # N.B. This will call `pantsd.terminate()` before starting. return pantsd.launch() @classmethod def create(cls, options_bootstrapper, full_init=True): """ :param OptionsBootstrapper options_bootstrapper: The bootstrap options. :param bool full_init: Whether or not to fully initialize an engine et al for the purposes of spawning a new daemon. `full_init=False` is intended primarily for lightweight lifecycle checks (since there is a ~1s overhead to initialize the engine). See the impl of `maybe_launch` for an example of the intended usage. """ bootstrap_options = options_bootstrapper.bootstrap_options bootstrap_options_values = bootstrap_options.for_global_scope() # TODO: https://github.com/pantsbuild/pants/issues/3479 watchman = WatchmanLauncher.create(bootstrap_options_values).watchman if full_init: build_root = get_buildroot() native = Native() build_config = BuildConfigInitializer.get(options_bootstrapper) legacy_graph_scheduler = EngineInitializer.setup_legacy_graph( native, options_bootstrapper, build_config ) services = cls._setup_services( build_root, bootstrap_options_values, legacy_graph_scheduler, watchman, union_membership=UnionMembership(build_config.union_rules()), ) else: build_root = None native = None services = PantsServices() return PantsDaemon( native=native, build_root=build_root, work_dir=bootstrap_options_values.pants_workdir, log_level=bootstrap_options_values.level.upper(), services=services, metadata_base_dir=bootstrap_options_values.pants_subprocessdir, bootstrap_options=bootstrap_options, ) @staticmethod def _setup_services( build_root, bootstrap_options, legacy_graph_scheduler, watchman, union_membership: UnionMembership, ): """Initialize pantsd services. :returns: A PantsServices instance. """ should_shutdown_after_run = bootstrap_options.shutdown_pantsd_after_run fs_event_service = FSEventService(watchman, build_root,) pidfile_absolute = PantsDaemon.metadata_file_path( "pantsd", "pid", bootstrap_options.pants_subprocessdir ) if pidfile_absolute.startswith(build_root): pidfile = os.path.relpath(pidfile_absolute, build_root) else: pidfile = None logging.getLogger(__name__).warning( "Not watching pantsd pidfile because subprocessdir is outside of buildroot. Having " "subprocessdir be a child of buildroot (as it is by default) may help avoid stray " "pantsd processes." ) scheduler_service = SchedulerService( fs_event_service=fs_event_service, legacy_graph_scheduler=legacy_graph_scheduler, build_root=build_root, invalidation_globs=OptionsInitializer.compute_pantsd_invalidation_globs( build_root, bootstrap_options ), pantsd_pidfile=pidfile, union_membership=union_membership, ) pailgun_service = PailgunService( (bootstrap_options.pantsd_pailgun_host, bootstrap_options.pantsd_pailgun_port), DaemonPantsRunner, scheduler_service, should_shutdown_after_run, ) store_gc_service = StoreGCService(legacy_graph_scheduler.scheduler) return PantsServices( services=(fs_event_service, scheduler_service, pailgun_service, store_gc_service), port_map=dict(pailgun=pailgun_service.pailgun_port), ) def __init__( self, native, build_root, work_dir, log_level, services, metadata_base_dir, bootstrap_options=None, ):
@memoized_property def watchman_launcher(self): return WatchmanLauncher.create(self._bootstrap_options.for_global_scope()) @property def is_killed(self): return self._kill_switch.is_set() @property def options_fingerprint(self): return OptionsFingerprinter.combined_options_fingerprint_for_scope( GLOBAL_SCOPE, self._bootstrap_options, fingerprint_key="daemon", invert=True ) def shutdown(self, service_thread_map): """Gracefully terminate all services and kill the main PantsDaemon loop.""" with self._services.lifecycle_lock: for service, service_thread in service_thread_map.items(): self._logger.info(f"terminating pantsd service: {service}") service.terminate() service_thread.join(self.JOIN_TIMEOUT_SECONDS) self._logger.info("terminating pantsd") self._kill_switch.set() @staticmethod def _close_stdio(): """Close stdio streams to avoid output in the tty that launched pantsd.""" for fd in (sys.stdin, sys.stdout, sys.stderr): file_no = fd.fileno() fd.flush() fd.close() os.close(file_no) @contextmanager def _pantsd_logging(self): """A context manager that runs with pantsd logging. Asserts that stdio (represented by file handles 0, 1, 2) is closed to ensure that we can safely reuse those fd numbers. """ # Ensure that stdio is closed so that we can safely reuse those file descriptors. for fd in (0, 1, 2): try: os.fdopen(fd) raise AssertionError(f"pantsd logging cannot initialize while stdio is open: {fd}") except OSError: pass # Redirect stdio to /dev/null for the rest of the run, to reserve those file descriptors # for further forks. with stdio_as(stdin_fd=-1, stdout_fd=-1, stderr_fd=-1): # Reinitialize logging for the daemon context. init_rust_logger(self._log_level, self._log_show_rust_3rdparty) result = setup_logging( self._log_level, log_dir=self._log_dir, log_name=self.LOG_NAME, native=self._native, warnings_filter_regexes=self._bootstrap_options.for_global_scope(), ) self._native.override_thread_logging_destination_to_just_pantsd() # Do a python-level redirect of stdout/stderr, which will not disturb `0,1,2`. # TODO: Consider giving these pipes/actual fds, in order to make them "deep" replacements # for `1,2`, and allow them to be used via `stdio_as`. sys.stdout = _LoggerStream(logging.getLogger(), logging.INFO, result.log_handler) sys.stderr = _LoggerStream(logging.getLogger(), logging.WARN, result.log_handler) self._logger.debug("logging initialized") yield (result.log_handler.stream, result.log_handler.native_filename) def _setup_services(self, pants_services): for service in pants_services.services: self._logger.info(f"setting up service {service}") service.setup(self._services) @staticmethod def _make_thread(service): name = f"{service.__class__.__name__}Thread" def target(): Native().override_thread_logging_destination_to_just_pantsd() service.run() t = threading.Thread(target=target, name=name) t.daemon = True return t def _run_services(self, pants_services): """Service runner main loop.""" if not pants_services.services: self._logger.critical("no services to run, bailing!") return service_thread_map = { service: self._make_thread(service) for service in pants_services.services } # Start services. for service, service_thread in service_thread_map.items(): self._logger.info(f"starting service {service}") try: service_thread.start() except (RuntimeError, FSEventService.ServiceError): self.shutdown(service_thread_map) raise PantsDaemon.StartupFailure( f"service {service} failed to start, shutting down!" ) # Once all services are started, write our pid. self.write_pid() self.write_metadata_by_name( "pantsd", self.FINGERPRINT_KEY, ensure_text(self.options_fingerprint) ) # Monitor services. while not self.is_killed: for service, service_thread in service_thread_map.items(): if not service_thread.is_alive(): self.shutdown(service_thread_map) raise PantsDaemon.RuntimeFailure( f"service failure for {service}, shutting down!" ) else: # Avoid excessive CPU utilization. service_thread.join(self.JOIN_TIMEOUT_SECONDS) def _write_named_sockets(self, socket_map): """Write multiple named sockets using a socket mapping.""" for socket_name, socket_info in socket_map.items(): self.write_named_socket(socket_name, socket_info) def run_sync(self): """Synchronously run pantsd.""" os.environ.pop("PYTHONPATH") # Switch log output to the daemon's log stream from here forward. # Also, register an exiter using os._exit to ensure we only close stdio streams once. self._close_stdio() with self._pantsd_logging() as (log_stream, log_filename), ExceptionSink.exiter_as( lambda _: Exiter(exiter=os._exit) ): # We don't have any stdio streams to log to anymore, so we log to a file. # We don't override the faulthandler destination because the stream we get will proxy things # via the rust logging code, and faulthandler needs to be writing directly to a real file # descriptor. When pantsd logging was originally initialised, we already set up faulthandler # to log to the correct file descriptor, so don't override it. # # We can get tracebacks of the pantsd process by tailing the pantsd log and sending it # SIGUSR2. ExceptionSink.reset_interactive_output_stream( log_stream, override_faulthandler_destination=False, ) # Reset the log location and the backtrace preference from the global bootstrap options. global_bootstrap_options = self._bootstrap_options.for_global_scope() ExceptionSink.reset_should_print_backtrace_to_terminal( global_bootstrap_options.print_exception_stacktrace ) ExceptionSink.reset_log_location(global_bootstrap_options.pants_workdir) self._native.set_panic_handler() # Set the process name in ps output to 'pantsd' vs './pants compile src/etc:: -ldebug'. set_process_title(f"pantsd [{self._build_root}]") # Write service socket information to .pids. self._write_named_sockets(self._services.port_map) # Enter the main service runner loop. self._setup_services(self._services) self._run_services(self._services) def post_fork_child(self): """Post-fork() child callback for ProcessManager.daemon_spawn().""" spawn_control_env = dict( PANTS_ENTRYPOINT=f"{__name__}:launch", # The daemon should run under the same sys.path as us; so we ensure # this. NB: It will scrub PYTHONPATH once started to avoid infecting # its own unrelated subprocesses. PYTHONPATH=os.pathsep.join(sys.path), ) exec_env = {**os.environ, **spawn_control_env} # Pass all of sys.argv so that we can proxy arg flags e.g. `-ldebug`. cmd = [sys.executable] + sys.argv spawn_control_env_vars = " ".join(f"{k}={v}" for k, v in spawn_control_env.items()) cmd_line = " ".join(cmd) self._logger.debug(f"cmd is: {spawn_control_env_vars} {cmd_line}") # TODO: Improve error handling on launch failures. os.spawnve(os.P_NOWAIT, sys.executable, cmd, env=exec_env) def needs_launch(self): """Determines if pantsd needs to be launched. N.B. This should always be called under care of the `lifecycle_lock`. :returns: True if the daemon needs launching, False otherwise. :rtype: bool """ new_fingerprint = self.options_fingerprint self._logger.debug( "pantsd: is_alive={self.is_alive()} new_fingerprint={new_fingerprint} current_fingerprint={self.fingerprint}" ) return self.needs_restart(new_fingerprint) def launch(self): """Launches pantsd in a subprocess. N.B. This should always be called under care of the `lifecycle_lock`. :returns: A Handle for the pantsd instance. :rtype: PantsDaemon.Handle """ self.terminate(include_watchman=False) self.watchman_launcher.maybe_launch() self._logger.debug("launching pantsd") self.daemon_spawn() # Wait up to 60 seconds for pantsd to write its pidfile. pantsd_pid = self.await_pid(60) listening_port = self.read_named_socket("pailgun", int) self._logger.debug(f"pantsd is running at pid {self.pid}, pailgun port is {listening_port}") return self.Handle(pantsd_pid, listening_port, self._metadata_base_dir) def terminate(self, include_watchman=True): """Terminates pantsd and watchman. N.B. This should always be called under care of the `lifecycle_lock`. """ super().terminate() if include_watchman: self.watchman_launcher.terminate() def needs_restart(self, option_fingerprint): """Overrides ProcessManager.needs_restart, to account for the case where pantsd is running but we want to shutdown after this run. :param option_fingerprint: A fingeprint of the global bootstrap options. :return: True if the daemon needs to restart. """ should_shutdown_after_run = ( self._bootstrap_options.for_global_scope().shutdown_pantsd_after_run ) return super().needs_restart(option_fingerprint) or ( self.is_alive() and should_shutdown_after_run ) def launch(): """An external entrypoint that spawns a new pantsd instance.""" PantsDaemon.Factory.create(OptionsBootstrapper.create()).run_sync()
""" :param Native native: A `Native` instance. :param string build_root: The pants build root. :param string work_dir: The pants work directory. :param string log_level: The log level to use for daemon logging. :param PantsServices services: A registry of services to use in this run. :param string metadata_base_dir: The ProcessManager metadata base dir. :param Options bootstrap_options: The bootstrap options, if available. """ super().__init__(name="pantsd", metadata_base_dir=metadata_base_dir) self._native = native self._build_root = build_root self._work_dir = work_dir self._log_level = log_level self._services = services self._bootstrap_options = bootstrap_options self._log_show_rust_3rdparty = ( bootstrap_options.for_global_scope().log_show_rust_3rdparty if bootstrap_options else True ) self._log_dir = os.path.join(work_dir, self.name) self._logger = logging.getLogger(__name__) # N.B. This Event is used as nothing more than a convenient atomic flag - nothing waits on it. self._kill_switch = threading.Event()
identifier_body
issue-2356.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. trait Groom { fn shave(other: usize); } pub struct cat { whiskers: isize, } pub enum MaybeDog { Dog, NoDog } impl MaybeDog { fn bark() { // If this provides a suggestion, it's a bug as MaybeDog doesn't impl Groom shave(); //~^ ERROR cannot find function `shave` } } impl Clone for cat { fn clone(&self) -> Self { clone(); //~^ ERROR cannot find function `clone` loop {} } } impl Default for cat { fn default() -> Self { default(); //~^ ERROR cannot find function `default` loop {} } } impl Groom for cat { fn shave(other: usize) { whiskers -= other; //~^ ERROR cannot find value `whiskers` shave(4); //~^ ERROR cannot find function `shave` purr(); //~^ ERROR cannot find function `purr` } } impl cat { fn static_method() {} fn purr_louder() { static_method(); //~^ ERROR cannot find function `static_method` purr(); //~^ ERROR cannot find function `purr` purr(); //~^ ERROR cannot find function `purr` purr(); //~^ ERROR cannot find function `purr` } } impl cat { fn meow() { if self.whiskers > 3 { //~^ ERROR expected value, found module `self` println!("MEOW"); } } fn purr(&self) { grow_older(); //~^ ERROR cannot find function `grow_older` shave(); //~^ ERROR cannot find function `shave` } fn burn_whiskers(&mut self) { whiskers = 0; //~^ ERROR cannot find value `whiskers` } pub fn
(other:usize) { whiskers = 4; //~^ ERROR cannot find value `whiskers` purr_louder(); //~^ ERROR cannot find function `purr_louder` } } fn main() { self += 1; //~^ ERROR expected value, found module `self` }
grow_older
identifier_name
issue-2356.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. trait Groom { fn shave(other: usize); } pub struct cat { whiskers: isize, } pub enum MaybeDog { Dog, NoDog } impl MaybeDog { fn bark() { // If this provides a suggestion, it's a bug as MaybeDog doesn't impl Groom shave(); //~^ ERROR cannot find function `shave` } } impl Clone for cat { fn clone(&self) -> Self { clone(); //~^ ERROR cannot find function `clone` loop {} } } impl Default for cat { fn default() -> Self { default(); //~^ ERROR cannot find function `default` loop {} } } impl Groom for cat { fn shave(other: usize) { whiskers -= other; //~^ ERROR cannot find value `whiskers` shave(4); //~^ ERROR cannot find function `shave` purr(); //~^ ERROR cannot find function `purr` } } impl cat { fn static_method() {} fn purr_louder() { static_method(); //~^ ERROR cannot find function `static_method` purr(); //~^ ERROR cannot find function `purr` purr(); //~^ ERROR cannot find function `purr` purr(); //~^ ERROR cannot find function `purr` } } impl cat { fn meow() { if self.whiskers > 3
} fn purr(&self) { grow_older(); //~^ ERROR cannot find function `grow_older` shave(); //~^ ERROR cannot find function `shave` } fn burn_whiskers(&mut self) { whiskers = 0; //~^ ERROR cannot find value `whiskers` } pub fn grow_older(other:usize) { whiskers = 4; //~^ ERROR cannot find value `whiskers` purr_louder(); //~^ ERROR cannot find function `purr_louder` } } fn main() { self += 1; //~^ ERROR expected value, found module `self` }
{ //~^ ERROR expected value, found module `self` println!("MEOW"); }
conditional_block
issue-2356.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. trait Groom { fn shave(other: usize); } pub struct cat { whiskers: isize, } pub enum MaybeDog { Dog, NoDog } impl MaybeDog { fn bark() { // If this provides a suggestion, it's a bug as MaybeDog doesn't impl Groom shave(); //~^ ERROR cannot find function `shave` } } impl Clone for cat { fn clone(&self) -> Self { clone(); //~^ ERROR cannot find function `clone` loop {} } } impl Default for cat { fn default() -> Self
} impl Groom for cat { fn shave(other: usize) { whiskers -= other; //~^ ERROR cannot find value `whiskers` shave(4); //~^ ERROR cannot find function `shave` purr(); //~^ ERROR cannot find function `purr` } } impl cat { fn static_method() {} fn purr_louder() { static_method(); //~^ ERROR cannot find function `static_method` purr(); //~^ ERROR cannot find function `purr` purr(); //~^ ERROR cannot find function `purr` purr(); //~^ ERROR cannot find function `purr` } } impl cat { fn meow() { if self.whiskers > 3 { //~^ ERROR expected value, found module `self` println!("MEOW"); } } fn purr(&self) { grow_older(); //~^ ERROR cannot find function `grow_older` shave(); //~^ ERROR cannot find function `shave` } fn burn_whiskers(&mut self) { whiskers = 0; //~^ ERROR cannot find value `whiskers` } pub fn grow_older(other:usize) { whiskers = 4; //~^ ERROR cannot find value `whiskers` purr_louder(); //~^ ERROR cannot find function `purr_louder` } } fn main() { self += 1; //~^ ERROR expected value, found module `self` }
{ default(); //~^ ERROR cannot find function `default` loop {} }
identifier_body
issue-2356.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. trait Groom { fn shave(other: usize); } pub struct cat { whiskers: isize, } pub enum MaybeDog { Dog, NoDog } impl MaybeDog { fn bark() { // If this provides a suggestion, it's a bug as MaybeDog doesn't impl Groom shave(); //~^ ERROR cannot find function `shave` } } impl Clone for cat { fn clone(&self) -> Self { clone();
impl Default for cat { fn default() -> Self { default(); //~^ ERROR cannot find function `default` loop {} } } impl Groom for cat { fn shave(other: usize) { whiskers -= other; //~^ ERROR cannot find value `whiskers` shave(4); //~^ ERROR cannot find function `shave` purr(); //~^ ERROR cannot find function `purr` } } impl cat { fn static_method() {} fn purr_louder() { static_method(); //~^ ERROR cannot find function `static_method` purr(); //~^ ERROR cannot find function `purr` purr(); //~^ ERROR cannot find function `purr` purr(); //~^ ERROR cannot find function `purr` } } impl cat { fn meow() { if self.whiskers > 3 { //~^ ERROR expected value, found module `self` println!("MEOW"); } } fn purr(&self) { grow_older(); //~^ ERROR cannot find function `grow_older` shave(); //~^ ERROR cannot find function `shave` } fn burn_whiskers(&mut self) { whiskers = 0; //~^ ERROR cannot find value `whiskers` } pub fn grow_older(other:usize) { whiskers = 4; //~^ ERROR cannot find value `whiskers` purr_louder(); //~^ ERROR cannot find function `purr_louder` } } fn main() { self += 1; //~^ ERROR expected value, found module `self` }
//~^ ERROR cannot find function `clone` loop {} } }
random_line_split
callee.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use syntax::ast; use syntax::codemap::Span; use CrateCtxt; /// Check that it is legal to call methods of the trait corresponding /// to `trait_id` (this only cares about the trait, not the specific /// method that is called) pub fn check_legal_trait_for_method_call(ccx: &CrateCtxt, span: Span, trait_id: ast::DefId)
{ let tcx = ccx.tcx; let did = Some(trait_id); let li = &tcx.lang_items; if did == li.drop_trait() { span_err!(tcx.sess, span, E0040, "explicit use of destructor method"); } else if !tcx.sess.features.borrow().unboxed_closures { // the #[feature(unboxed_closures)] feature isn't // activated so we need to enforce the closure // restrictions. let method = if did == li.fn_trait() { "call" } else if did == li.fn_mut_trait() { "call_mut" } else if did == li.fn_once_trait() { "call_once" } else { return // not a closure method, everything is OK. }; span_err!(tcx.sess, span, E0174, "explicit use of unboxed closure method `{}` is experimental", method); span_help!(tcx.sess, span, "add `#![feature(unboxed_closures)]` to the crate attributes to enable"); } }
identifier_body
callee.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use syntax::ast; use syntax::codemap::Span; use CrateCtxt; /// Check that it is legal to call methods of the trait corresponding /// to `trait_id` (this only cares about the trait, not the specific /// method that is called) pub fn
(ccx: &CrateCtxt, span: Span, trait_id: ast::DefId) { let tcx = ccx.tcx; let did = Some(trait_id); let li = &tcx.lang_items; if did == li.drop_trait() { span_err!(tcx.sess, span, E0040, "explicit use of destructor method"); } else if !tcx.sess.features.borrow().unboxed_closures { // the #[feature(unboxed_closures)] feature isn't // activated so we need to enforce the closure // restrictions. let method = if did == li.fn_trait() { "call" } else if did == li.fn_mut_trait() { "call_mut" } else if did == li.fn_once_trait() { "call_once" } else { return // not a closure method, everything is OK. }; span_err!(tcx.sess, span, E0174, "explicit use of unboxed closure method `{}` is experimental", method); span_help!(tcx.sess, span, "add `#![feature(unboxed_closures)]` to the crate attributes to enable"); } }
check_legal_trait_for_method_call
identifier_name
callee.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use syntax::ast; use syntax::codemap::Span; use CrateCtxt; /// Check that it is legal to call methods of the trait corresponding /// to `trait_id` (this only cares about the trait, not the specific /// method that is called) pub fn check_legal_trait_for_method_call(ccx: &CrateCtxt, span: Span, trait_id: ast::DefId) { let tcx = ccx.tcx; let did = Some(trait_id); let li = &tcx.lang_items; if did == li.drop_trait()
else if !tcx.sess.features.borrow().unboxed_closures { // the #[feature(unboxed_closures)] feature isn't // activated so we need to enforce the closure // restrictions. let method = if did == li.fn_trait() { "call" } else if did == li.fn_mut_trait() { "call_mut" } else if did == li.fn_once_trait() { "call_once" } else { return // not a closure method, everything is OK. }; span_err!(tcx.sess, span, E0174, "explicit use of unboxed closure method `{}` is experimental", method); span_help!(tcx.sess, span, "add `#![feature(unboxed_closures)]` to the crate attributes to enable"); } }
{ span_err!(tcx.sess, span, E0040, "explicit use of destructor method"); }
conditional_block
callee.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use syntax::ast; use syntax::codemap::Span; use CrateCtxt; /// Check that it is legal to call methods of the trait corresponding /// to `trait_id` (this only cares about the trait, not the specific /// method that is called) pub fn check_legal_trait_for_method_call(ccx: &CrateCtxt, span: Span, trait_id: ast::DefId) { let tcx = ccx.tcx;
if did == li.drop_trait() { span_err!(tcx.sess, span, E0040, "explicit use of destructor method"); } else if !tcx.sess.features.borrow().unboxed_closures { // the #[feature(unboxed_closures)] feature isn't // activated so we need to enforce the closure // restrictions. let method = if did == li.fn_trait() { "call" } else if did == li.fn_mut_trait() { "call_mut" } else if did == li.fn_once_trait() { "call_once" } else { return // not a closure method, everything is OK. }; span_err!(tcx.sess, span, E0174, "explicit use of unboxed closure method `{}` is experimental", method); span_help!(tcx.sess, span, "add `#![feature(unboxed_closures)]` to the crate attributes to enable"); } }
let did = Some(trait_id); let li = &tcx.lang_items;
random_line_split
cmp.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::cmp::Ordering::{self, Less, Equal, Greater}; // impl Ord for str { // #[inline] // fn cmp(&self, other: &str) -> Ordering { // for (s_b, o_b) in self.bytes().zip(other.bytes()) { // match s_b.cmp(&o_b) { // Greater => return Greater, // Less => return Less, // Equal => () // } // } // // self.len().cmp(&other.len()) // } // } #[test] fn
() { let x: &str = "日"; // '\u{65e5}' let other: &str = "月"; // '\u{6708}' let result: Ordering = x.cmp(other); assert_eq!(result, Less); } #[test] fn cmp_test2() { let x: &str = "天"; // '\u{5929}' let other: &str = "地"; // '\u{5730}' let result: Ordering = x.cmp(other); assert_eq!(result, Greater); } #[test] fn cmp_test3() { let x: &str = "人"; let other: &str = x; let result: Ordering = x.cmp(other); assert_eq!(result, Equal); } #[test] fn cmp_test4() { let x: &str = "人口"; let other: &str = "人"; let result: Ordering = x.cmp(other); assert_eq!(result, Greater); } #[test] fn cmp_test5() { let x: &str = "人"; let other: &str = "人種"; let result: Ordering = x.cmp(other); assert_eq!(result, Less); } }
cmp_test1
identifier_name
cmp.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::cmp::Ordering::{self, Less, Equal, Greater}; // impl Ord for str { // #[inline] // fn cmp(&self, other: &str) -> Ordering { // for (s_b, o_b) in self.bytes().zip(other.bytes()) { // match s_b.cmp(&o_b) { // Greater => return Greater, // Less => return Less, // Equal => () // } // } // // self.len().cmp(&other.len()) // } // } #[test] fn cmp_test1() { let x: &str = "日"; // '\u{65e5}' let other: &str = "月"; // '\u{6708}' let result: Ordering = x.cmp(other); assert_eq!(result, Less); } #[test] fn cmp_test2() { let x: &str = "天"; // '\u{5929}' let other: &str = "地"; // '\u{5730}' let result: Ordering = x.cmp(other); assert_eq!(result, Greater); } #[test] fn cmp_test3() { let x: &str = "人"; let other: &str = x; let result: Ordering = x.cmp(other); assert_eq!(result, Equal); } #[test] fn cmp_test4() { let x: &str = "人口"; let other: &str = "人"; let result: Ordering = x.cmp(other); assert_eq!(result, Greater); } #[test] fn cmp_test5() { let x: &str =
"人"; let other: &str = "人種"; let result: Ordering = x.cmp(other); assert_eq!(result, Less); } }
identifier_body
cmp.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::cmp::Ordering::{self, Less, Equal, Greater}; // impl Ord for str { // #[inline] // fn cmp(&self, other: &str) -> Ordering { // for (s_b, o_b) in self.bytes().zip(other.bytes()) { // match s_b.cmp(&o_b) { // Greater => return Greater, // Less => return Less, // Equal => () // } // } // // self.len().cmp(&other.len()) // } // } #[test] fn cmp_test1() { let x: &str = "日"; // '\u{65e5}' let other: &str = "月"; // '\u{6708}' let result: Ordering = x.cmp(other); assert_eq!(result, Less); } #[test] fn cmp_test2() { let x: &str = "天"; // '\u{5929}' let other: &str = "地"; // '\u{5730}' let result: Ordering = x.cmp(other); assert_eq!(result, Greater); } #[test] fn cmp_test3() { let x: &str = "人"; let other: &str = x; let result: Ordering = x.cmp(other); assert_eq!(result, Equal); } #[test] fn cmp_test4() { let x: &str = "人口";
let other: &str = "人"; let result: Ordering = x.cmp(other); assert_eq!(result, Greater); } #[test] fn cmp_test5() { let x: &str = "人"; let other: &str = "人種"; let result: Ordering = x.cmp(other); assert_eq!(result, Less); } }
random_line_split
admin.py
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2012 OpenPlans # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ######################################################################### from django.contrib import admin from geonode.base.admin import MediaTranslationAdmin, ResourceBaseAdminForm from geonode.layers.models import Layer, Attribute, Style from geonode.layers.models import LayerFile, UploadSession import autocomplete_light class LayerAdminForm(ResourceBaseAdminForm): class Meta: model = Layer class AttributeInline(admin.TabularInline): model = Attribute class LayerAdmin(MediaTranslationAdmin):
class AttributeAdmin(admin.ModelAdmin): model = Attribute list_display_links = ('id',) list_display = ( 'id', 'layer', 'attribute', 'description', 'attribute_label', 'attribute_type', 'display_order') list_filter = ('layer', 'attribute_type') search_fields = ('attribute', 'attribute_label',) class StyleAdmin(admin.ModelAdmin): model = Style list_display_links = ('sld_title',) list_display = ('id', 'name', 'sld_title', 'workspace', 'sld_url') list_filter = ('workspace',) search_fields = ('name', 'workspace',) class LayerFileInline(admin.TabularInline): model = LayerFile class UploadSessionAdmin(admin.ModelAdmin): model = UploadSession list_display = ('date', 'user', 'processed') inlines = [LayerFileInline] admin.site.register(Layer, LayerAdmin) admin.site.register(Attribute, AttributeAdmin) admin.site.register(Style, StyleAdmin) admin.site.register(UploadSession, UploadSessionAdmin)
list_display = ( 'id', 'typename', 'service_type', 'title', 'Floodplains', 'SUC', 'date', 'category') list_display_links = ('id',) list_editable = ('title', 'category') list_filter = ('owner', 'category', 'restriction_code_type__identifier', 'date', 'date_type') # def get_queryset(self, request): # return super(LayerAdmin, # self).get_queryset(request).prefetch_related('floodplain_tag','SUC_tag') def Floodplains(self, obj): return u", ".join(o.name for o in obj.floodplain_tag.all()) def SUC(self, obj): return u", ".join(o.name for o in obj.SUC_tag.all()) # def get_queryset(self, request): # return super(LayerAdmin, self).get_queryset(request).prefetch_related('SUC_tag') # def SUC(self, obj): # return u", ".join(o.name for o in obj.SUC_tag.all()) inlines = [AttributeInline] search_fields = ('typename', 'title', 'abstract', 'purpose',) filter_horizontal = ('contacts',) date_hierarchy = 'date' readonly_fields = ('uuid', 'typename', 'workspace') form = LayerAdminForm
identifier_body
admin.py
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2012 OpenPlans # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ######################################################################### from django.contrib import admin from geonode.base.admin import MediaTranslationAdmin, ResourceBaseAdminForm from geonode.layers.models import Layer, Attribute, Style from geonode.layers.models import LayerFile, UploadSession import autocomplete_light
class AttributeInline(admin.TabularInline): model = Attribute class LayerAdmin(MediaTranslationAdmin): list_display = ( 'id', 'typename', 'service_type', 'title', 'Floodplains', 'SUC', 'date', 'category') list_display_links = ('id',) list_editable = ('title', 'category') list_filter = ('owner', 'category', 'restriction_code_type__identifier', 'date', 'date_type') # def get_queryset(self, request): # return super(LayerAdmin, # self).get_queryset(request).prefetch_related('floodplain_tag','SUC_tag') def Floodplains(self, obj): return u", ".join(o.name for o in obj.floodplain_tag.all()) def SUC(self, obj): return u", ".join(o.name for o in obj.SUC_tag.all()) # def get_queryset(self, request): # return super(LayerAdmin, self).get_queryset(request).prefetch_related('SUC_tag') # def SUC(self, obj): # return u", ".join(o.name for o in obj.SUC_tag.all()) inlines = [AttributeInline] search_fields = ('typename', 'title', 'abstract', 'purpose',) filter_horizontal = ('contacts',) date_hierarchy = 'date' readonly_fields = ('uuid', 'typename', 'workspace') form = LayerAdminForm class AttributeAdmin(admin.ModelAdmin): model = Attribute list_display_links = ('id',) list_display = ( 'id', 'layer', 'attribute', 'description', 'attribute_label', 'attribute_type', 'display_order') list_filter = ('layer', 'attribute_type') search_fields = ('attribute', 'attribute_label',) class StyleAdmin(admin.ModelAdmin): model = Style list_display_links = ('sld_title',) list_display = ('id', 'name', 'sld_title', 'workspace', 'sld_url') list_filter = ('workspace',) search_fields = ('name', 'workspace',) class LayerFileInline(admin.TabularInline): model = LayerFile class UploadSessionAdmin(admin.ModelAdmin): model = UploadSession list_display = ('date', 'user', 'processed') inlines = [LayerFileInline] admin.site.register(Layer, LayerAdmin) admin.site.register(Attribute, AttributeAdmin) admin.site.register(Style, StyleAdmin) admin.site.register(UploadSession, UploadSessionAdmin)
class LayerAdminForm(ResourceBaseAdminForm): class Meta: model = Layer
random_line_split
admin.py
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2012 OpenPlans # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ######################################################################### from django.contrib import admin from geonode.base.admin import MediaTranslationAdmin, ResourceBaseAdminForm from geonode.layers.models import Layer, Attribute, Style from geonode.layers.models import LayerFile, UploadSession import autocomplete_light class LayerAdminForm(ResourceBaseAdminForm): class Meta: model = Layer class AttributeInline(admin.TabularInline): model = Attribute class LayerAdmin(MediaTranslationAdmin): list_display = ( 'id', 'typename', 'service_type', 'title', 'Floodplains', 'SUC', 'date', 'category') list_display_links = ('id',) list_editable = ('title', 'category') list_filter = ('owner', 'category', 'restriction_code_type__identifier', 'date', 'date_type') # def get_queryset(self, request): # return super(LayerAdmin, # self).get_queryset(request).prefetch_related('floodplain_tag','SUC_tag') def Floodplains(self, obj): return u", ".join(o.name for o in obj.floodplain_tag.all()) def SUC(self, obj): return u", ".join(o.name for o in obj.SUC_tag.all()) # def get_queryset(self, request): # return super(LayerAdmin, self).get_queryset(request).prefetch_related('SUC_tag') # def SUC(self, obj): # return u", ".join(o.name for o in obj.SUC_tag.all()) inlines = [AttributeInline] search_fields = ('typename', 'title', 'abstract', 'purpose',) filter_horizontal = ('contacts',) date_hierarchy = 'date' readonly_fields = ('uuid', 'typename', 'workspace') form = LayerAdminForm class AttributeAdmin(admin.ModelAdmin): model = Attribute list_display_links = ('id',) list_display = ( 'id', 'layer', 'attribute', 'description', 'attribute_label', 'attribute_type', 'display_order') list_filter = ('layer', 'attribute_type') search_fields = ('attribute', 'attribute_label',) class
(admin.ModelAdmin): model = Style list_display_links = ('sld_title',) list_display = ('id', 'name', 'sld_title', 'workspace', 'sld_url') list_filter = ('workspace',) search_fields = ('name', 'workspace',) class LayerFileInline(admin.TabularInline): model = LayerFile class UploadSessionAdmin(admin.ModelAdmin): model = UploadSession list_display = ('date', 'user', 'processed') inlines = [LayerFileInline] admin.site.register(Layer, LayerAdmin) admin.site.register(Attribute, AttributeAdmin) admin.site.register(Style, StyleAdmin) admin.site.register(UploadSession, UploadSessionAdmin)
StyleAdmin
identifier_name
block_drag_surface.js
/** * @license * Visual Blocks Editor * * Copyright 2016 Google Inc. * https://developers.google.com/blockly/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview A class that manages a surface for dragging blocks. When a * block drag is started, we move the block (and children) to a separate dom * element that we move around using translate3d. At the end of the drag, the * blocks are put back in into the svg they came from. This helps performance by * avoiding repainting the entire svg on every mouse move while dragging blocks. * @author picklesrus */ 'use strict'; goog.provide('Blockly.BlockDragSurfaceSvg'); goog.require('Blockly.utils'); goog.require('goog.asserts'); goog.require('goog.math.Coordinate'); /** * Class for a drag surface for the currently dragged block. This is a separate * SVG that contains only the currently moving block, or nothing. * @param {!Element} container Containing element. * @constructor */ Blockly.BlockDragSurfaceSvg = function(container) { /** * @type {!Element} * @private */ this.container_ = container; this.createDom(); }; /** * The SVG drag surface. Set once by Blockly.BlockDragSurfaceSvg.createDom. * @type {Element} * @private */ Blockly.BlockDragSurfaceSvg.prototype.SVG_ = null; /** * This is where blocks live while they are being dragged if the drag surface * is enabled. * @type {Element} * @private */
* @private */ Blockly.BlockDragSurfaceSvg.prototype.container_ = null; /** * Cached value for the scale of the drag surface. * Used to set/get the correct translation during and after a drag. * @type {number} * @private */ Blockly.BlockDragSurfaceSvg.prototype.scale_ = 1; /** * Cached value for the translation of the drag surface. * This translation is in pixel units, because the scale is applied to the * drag group rather than the top-level SVG. * @type {goog.math.Coordinate} * @private */ Blockly.BlockDragSurfaceSvg.prototype.surfaceXY_ = null; /** * Create the drag surface and inject it into the container. */ Blockly.BlockDragSurfaceSvg.prototype.createDom = function() { if (this.SVG_) { return; // Already created. } this.SVG_ = Blockly.utils.createSvgElement('svg', { 'xmlns': Blockly.SVG_NS, 'xmlns:html': Blockly.HTML_NS, 'xmlns:xlink': 'http://www.w3.org/1999/xlink', 'version': '1.1', 'class': 'blocklyBlockDragSurface' }, this.container_); this.dragGroup_ = Blockly.utils.createSvgElement('g', {}, this.SVG_); }; /** * Set the SVG blocks on the drag surface's group and show the surface. * Only one block group should be on the drag surface at a time. * @param {!Element} blocks Block or group of blocks to place on the drag * surface. */ Blockly.BlockDragSurfaceSvg.prototype.setBlocksAndShow = function(blocks) { goog.asserts.assert(this.dragGroup_.childNodes.length == 0, 'Already dragging a block.'); // appendChild removes the blocks from the previous parent this.dragGroup_.appendChild(blocks); this.SVG_.style.display = 'block'; this.surfaceXY_ = new goog.math.Coordinate(0, 0); }; /** * Translate and scale the entire drag surface group to the given position, to * keep in sync with the workspace. * @param {number} x X translation in workspace coordinates. * @param {number} y Y translation in workspace coordinates. * @param {number} scale Scale of the group. */ Blockly.BlockDragSurfaceSvg.prototype.translateAndScaleGroup = function(x, y, scale) { this.scale_ = scale; // This is a work-around to prevent a the blocks from rendering // fuzzy while they are being dragged on the drag surface. x = x.toFixed(0); y = y.toFixed(0); this.dragGroup_.setAttribute('transform', 'translate('+ x + ','+ y + ')' + ' scale(' + scale + ')'); }; /** * Translate the drag surface's SVG based on its internal state. * @private */ Blockly.BlockDragSurfaceSvg.prototype.translateSurfaceInternal_ = function() { var x = this.surfaceXY_.x; var y = this.surfaceXY_.y; // This is a work-around to prevent a the blocks from rendering // fuzzy while they are being dragged on the drag surface. x = x.toFixed(0); y = y.toFixed(0); this.SVG_.style.display = 'block'; Blockly.utils.setCssTransform(this.SVG_, 'translate3d(' + x + 'px, ' + y + 'px, 0px)'); }; /** * Translate the entire drag surface during a drag. * We translate the drag surface instead of the blocks inside the surface * so that the browser avoids repainting the SVG. * Because of this, the drag coordinates must be adjusted by scale. * @param {number} x X translation for the entire surface. * @param {number} y Y translation for the entire surface. */ Blockly.BlockDragSurfaceSvg.prototype.translateSurface = function(x, y) { this.surfaceXY_ = new goog.math.Coordinate(x * this.scale_, y * this.scale_); this.translateSurfaceInternal_(); }; /** * Reports the surface translation in scaled workspace coordinates. * Use this when finishing a drag to return blocks to the correct position. * @return {!goog.math.Coordinate} Current translation of the surface. */ Blockly.BlockDragSurfaceSvg.prototype.getSurfaceTranslation = function() { var xy = Blockly.utils.getRelativeXY(this.SVG_); return new goog.math.Coordinate(xy.x / this.scale_, xy.y / this.scale_); }; /** * Provide a reference to the drag group (primarily for * BlockSvg.getRelativeToSurfaceXY). * @return {Element} Drag surface group element. */ Blockly.BlockDragSurfaceSvg.prototype.getGroup = function() { return this.dragGroup_; }; /** * Get the current blocks on the drag surface, if any (primarily * for BlockSvg.getRelativeToSurfaceXY). * @return {!Element|undefined} Drag surface block DOM element, or undefined * if no blocks exist. */ Blockly.BlockDragSurfaceSvg.prototype.getCurrentBlock = function() { return this.dragGroup_.firstChild; }; /** * Clear the group and hide the surface; move the blocks off onto the provided * element. * If the block is being deleted it doesn't need to go back to the original * surface, since it would be removed immediately during dispose. * @param {Element} opt_newSurface Surface the dragging blocks should be moved * to, or null if the blocks should be removed from this surface without * being moved to a different surface. */ Blockly.BlockDragSurfaceSvg.prototype.clearAndHide = function(opt_newSurface) { if (opt_newSurface) { // appendChild removes the node from this.dragGroup_ opt_newSurface.appendChild(this.getCurrentBlock()); } else { this.dragGroup_.removeChild(this.getCurrentBlock()); } this.SVG_.style.display = 'none'; goog.asserts.assert(this.dragGroup_.childNodes.length == 0, 'Drag group was not cleared.'); this.surfaceXY_ = null; };
Blockly.BlockDragSurfaceSvg.prototype.dragGroup_ = null; /** * Containing HTML element; parent of the workspace and the drag surface. * @type {Element}
random_line_split
block_drag_surface.js
/** * @license * Visual Blocks Editor * * Copyright 2016 Google Inc. * https://developers.google.com/blockly/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview A class that manages a surface for dragging blocks. When a * block drag is started, we move the block (and children) to a separate dom * element that we move around using translate3d. At the end of the drag, the * blocks are put back in into the svg they came from. This helps performance by * avoiding repainting the entire svg on every mouse move while dragging blocks. * @author picklesrus */ 'use strict'; goog.provide('Blockly.BlockDragSurfaceSvg'); goog.require('Blockly.utils'); goog.require('goog.asserts'); goog.require('goog.math.Coordinate'); /** * Class for a drag surface for the currently dragged block. This is a separate * SVG that contains only the currently moving block, or nothing. * @param {!Element} container Containing element. * @constructor */ Blockly.BlockDragSurfaceSvg = function(container) { /** * @type {!Element} * @private */ this.container_ = container; this.createDom(); }; /** * The SVG drag surface. Set once by Blockly.BlockDragSurfaceSvg.createDom. * @type {Element} * @private */ Blockly.BlockDragSurfaceSvg.prototype.SVG_ = null; /** * This is where blocks live while they are being dragged if the drag surface * is enabled. * @type {Element} * @private */ Blockly.BlockDragSurfaceSvg.prototype.dragGroup_ = null; /** * Containing HTML element; parent of the workspace and the drag surface. * @type {Element} * @private */ Blockly.BlockDragSurfaceSvg.prototype.container_ = null; /** * Cached value for the scale of the drag surface. * Used to set/get the correct translation during and after a drag. * @type {number} * @private */ Blockly.BlockDragSurfaceSvg.prototype.scale_ = 1; /** * Cached value for the translation of the drag surface. * This translation is in pixel units, because the scale is applied to the * drag group rather than the top-level SVG. * @type {goog.math.Coordinate} * @private */ Blockly.BlockDragSurfaceSvg.prototype.surfaceXY_ = null; /** * Create the drag surface and inject it into the container. */ Blockly.BlockDragSurfaceSvg.prototype.createDom = function() { if (this.SVG_)
this.SVG_ = Blockly.utils.createSvgElement('svg', { 'xmlns': Blockly.SVG_NS, 'xmlns:html': Blockly.HTML_NS, 'xmlns:xlink': 'http://www.w3.org/1999/xlink', 'version': '1.1', 'class': 'blocklyBlockDragSurface' }, this.container_); this.dragGroup_ = Blockly.utils.createSvgElement('g', {}, this.SVG_); }; /** * Set the SVG blocks on the drag surface's group and show the surface. * Only one block group should be on the drag surface at a time. * @param {!Element} blocks Block or group of blocks to place on the drag * surface. */ Blockly.BlockDragSurfaceSvg.prototype.setBlocksAndShow = function(blocks) { goog.asserts.assert(this.dragGroup_.childNodes.length == 0, 'Already dragging a block.'); // appendChild removes the blocks from the previous parent this.dragGroup_.appendChild(blocks); this.SVG_.style.display = 'block'; this.surfaceXY_ = new goog.math.Coordinate(0, 0); }; /** * Translate and scale the entire drag surface group to the given position, to * keep in sync with the workspace. * @param {number} x X translation in workspace coordinates. * @param {number} y Y translation in workspace coordinates. * @param {number} scale Scale of the group. */ Blockly.BlockDragSurfaceSvg.prototype.translateAndScaleGroup = function(x, y, scale) { this.scale_ = scale; // This is a work-around to prevent a the blocks from rendering // fuzzy while they are being dragged on the drag surface. x = x.toFixed(0); y = y.toFixed(0); this.dragGroup_.setAttribute('transform', 'translate('+ x + ','+ y + ')' + ' scale(' + scale + ')'); }; /** * Translate the drag surface's SVG based on its internal state. * @private */ Blockly.BlockDragSurfaceSvg.prototype.translateSurfaceInternal_ = function() { var x = this.surfaceXY_.x; var y = this.surfaceXY_.y; // This is a work-around to prevent a the blocks from rendering // fuzzy while they are being dragged on the drag surface. x = x.toFixed(0); y = y.toFixed(0); this.SVG_.style.display = 'block'; Blockly.utils.setCssTransform(this.SVG_, 'translate3d(' + x + 'px, ' + y + 'px, 0px)'); }; /** * Translate the entire drag surface during a drag. * We translate the drag surface instead of the blocks inside the surface * so that the browser avoids repainting the SVG. * Because of this, the drag coordinates must be adjusted by scale. * @param {number} x X translation for the entire surface. * @param {number} y Y translation for the entire surface. */ Blockly.BlockDragSurfaceSvg.prototype.translateSurface = function(x, y) { this.surfaceXY_ = new goog.math.Coordinate(x * this.scale_, y * this.scale_); this.translateSurfaceInternal_(); }; /** * Reports the surface translation in scaled workspace coordinates. * Use this when finishing a drag to return blocks to the correct position. * @return {!goog.math.Coordinate} Current translation of the surface. */ Blockly.BlockDragSurfaceSvg.prototype.getSurfaceTranslation = function() { var xy = Blockly.utils.getRelativeXY(this.SVG_); return new goog.math.Coordinate(xy.x / this.scale_, xy.y / this.scale_); }; /** * Provide a reference to the drag group (primarily for * BlockSvg.getRelativeToSurfaceXY). * @return {Element} Drag surface group element. */ Blockly.BlockDragSurfaceSvg.prototype.getGroup = function() { return this.dragGroup_; }; /** * Get the current blocks on the drag surface, if any (primarily * for BlockSvg.getRelativeToSurfaceXY). * @return {!Element|undefined} Drag surface block DOM element, or undefined * if no blocks exist. */ Blockly.BlockDragSurfaceSvg.prototype.getCurrentBlock = function() { return this.dragGroup_.firstChild; }; /** * Clear the group and hide the surface; move the blocks off onto the provided * element. * If the block is being deleted it doesn't need to go back to the original * surface, since it would be removed immediately during dispose. * @param {Element} opt_newSurface Surface the dragging blocks should be moved * to, or null if the blocks should be removed from this surface without * being moved to a different surface. */ Blockly.BlockDragSurfaceSvg.prototype.clearAndHide = function(opt_newSurface) { if (opt_newSurface) { // appendChild removes the node from this.dragGroup_ opt_newSurface.appendChild(this.getCurrentBlock()); } else { this.dragGroup_.removeChild(this.getCurrentBlock()); } this.SVG_.style.display = 'none'; goog.asserts.assert(this.dragGroup_.childNodes.length == 0, 'Drag group was not cleared.'); this.surfaceXY_ = null; };
{ return; // Already created. }
conditional_block
_drop_test2.js
import { expect } from 'chai' import _drop from '../../src/array/_drop2' describe('_drop', function(){ it('is a function', function(){ expect(_drop).to.be.a('function') }) it('returns an array', function(){ const droppedArray = _drop([5,7,2]) expect(droppedArray).to.be.a('array') }) it('returns [2] when given [5,7,2], 2', function(){ const droppedArray = _drop([5,7,2], 2) expect(droppedArray).to.be.deep.equal([2]) }) it('returns [7, 2] when given [5,7,2]', function(){ const droppedArray = _drop([5,7,2])
}) it('returns [] when given [5,7,2], 17', function(){ const droppedArray = _drop([5,7,2], 17) expect(droppedArray).to.be.deep.equal([]) }) })
expect(droppedArray).to.be.deep.equal([7, 2])
random_line_split
SwapView.js
/** @module deliteful/SwapView */ define([ "dcl/dcl", "delite/register", "requirejs-dplugins/jquery!attributes/classes", "dpointer/events", "./ViewStack", "delite/theme!./SwapView/themes/{{theme}}/SwapView.css" ], function (dcl, register, $, dpointer, ViewStack) { /** * SwapView container widget. Extends ViewStack to let the user swap the visible child using a swipe gesture. * You can also use the Page Up / Down keyboard keys to go to the next/previous child. * * @example: * <d-swap-view id="sv"> * <div id="childA">...</div> * <div id="childB">...</div> * <div id="childC">...</div> * </d-swap-view> * @class module:deliteful/SwapView * @augments module:deliteful/ViewStack */ return register("d-swap-view", [HTMLElement, ViewStack], /** @lends module:deliteful/SwapView# */{ /** * The name of the CSS class of this widget. Note that this element also use the d-view-stack class to * leverage `deliteful/ViewStack` styles. * @member {string} * @default "d-swap-view" */ baseClass: "d-swap-view", /** * Drag threshold: drag will start only if the user moves the pointer more than this threshold. * @member {number} * @default 10 * @private */ _dragThreshold: 10, /** * Swap threshold: number between 0 and 1 that determines the minimum swipe gesture to swap the view. * Default is 0.25 which means that you must drag (horizontally) by more than 1/4 of the view size to swap * views. * @member {number} * @default 0.25 */ swapThreshold: 0.25, render: function () { dpointer.setTouchAction(this, "pan-y"); }, attachedCallback: function () { // If the user hasn't specified a tabindex declaratively, then set to default value. if (!this.hasAttribute("tabindex")) { this.tabIndex = "0"; } }, preRender: function () { // we want to inherit from ViewStack's CSS (including transitions). $(this).addClass("d-view-stack"); }, postRender: function () { this.on("pointerdown", this._pointerDownHandler.bind(this)); this.on("pointermove", this._pointerMoveHandler.bind(this)); this.on("pointerup", this._pointerUpHandler.bind(this)); this.on("lostpointercapture", this._pointerUpHandler.bind(this)); this.on("pointercancel", this._pointerUpHandler.bind(this)); this.on("keydown", this._keyDownHandler.bind(this)); }, /** * Starts drag/swipe interaction. * @private */ _pointerDownHandler: function (e) { if (!this._drag) { this._drag = { start: e.clientX }; dpointer.setPointerCapture(e.target, e.pointerId); } }, /** * Handle pointer move events during drag/swipe interaction. * @private */ _pointerMoveHandler: function (e) { /* jshint maxcomplexity: 13 */ if (this._drag) { var dx = e.clientX - this._drag.start; if (!this._drag.started && Math.abs(dx) > this._dragThreshold) { // user dragged (more than the threshold), start sliding children. var childOut = this._visibleChild; var childIn = (this.effectiveDir === "ltr" ? dx < 0 : dx > 0) ? childOut.nextElementSibling : childOut.previousElementSibling; if (childIn) { this._drag.childOut = childOut; this._drag.childIn = childIn; this._drag.started = true; this._drag.ended = false; this._drag.reverse = dx > 0; $(this).addClass("-d-swap-view-drag"); childIn.style.visibility = "visible"; childIn.style.display = ""; } } if (this._drag.started && !this._drag.ended) { // This is what will really translate the children as the user swipes/drags. var rx = this._drag.rx = dx / this.offsetWidth; var v = this._drag.reverse ? rx : -rx; var lv = Math.floor((this._drag.reverse ? 1 - v : v) * 100); var rv = Math.floor((this._drag.reverse ? v : 1 - v) * 100); var left = this._drag.reverse ? this._drag.childIn : this._drag.childOut; var right = this._drag.reverse ? this._drag.childOut : this._drag.childIn; this._setTranslation(left, -lv); this._setTranslation(right, rv); } } }, /** * Handle end of drag/swipe interaction. * @private */ _pointerUpHandler: function () { if (this._drag) { if (!this._drag.started) { // abort before user really dragged this._drag = null; } else if (!this._drag.ended) { // user released finger/mouse this._drag.ended = true; this._setupTransitionEndHandlers(); this._setTransitionProperties(this._drag.childIn); this._setTransitionProperties(this._drag.childOut); if ((this._drag.reverse && this._drag.rx > this.swapThreshold) || (!this._drag.reverse && this._drag.rx < -this.swapThreshold)) { // user dragged more than the swap threshold: finish sliding to the next/prev child. this._setTranslation(this._drag.childIn, 0); this._setTranslation(this._drag.childOut, this._drag.reverse ? 100 : -100); } else { // user dragged less then the swap threshold: slide back to the current child. this._drag.slideBack = true; this._setTranslation(this._drag.childIn, this._drag.reverse ? -100 : 100); this._setTranslation(this._drag.childOut, 0); } } } }, /** * Handle Page Up/Down keys to show the previous/next child. * @private */ _keyDownHandler: function (e) { switch (e.key) { case "PageUp": this.showNext(); break; case "PageDown": this.showPrevious({reverse: true}); break; } }, _setupTransitionEndHandlers: function () { // set listeners to cleanup all CSS classes after the slide transition (either from ViewStack::show, // of from the slide back animation). if (!this._endTransitionHandler)
}, /** * Cleanup all CSS classes and added rules after transition. * @private */ _endTransition: function () { if (this._drag) { $(this).removeClass("-d-swap-view-drag"); if (this._drag.slideBack) { // Hide the "in" view if the wap was cancelled (slide back). this._drag.childIn.style.visibility = "hidden"; this._drag.childIn.style.display = "none"; } else { this._drag.childOut.style.visibility = "hidden"; this._drag.childOut.style.display = "none"; this.show(this._drag.childIn, {transition: "none"}); } this._clearTransitionProperties(this._drag.childIn); this._clearTransitionProperties(this._drag.childOut); this._clearTranslation(this._drag.childIn); this._clearTranslation(this._drag.childOut); this._drag = null; } }, // CSS/events utilities _addTransitionEndHandlers: function (child, add) { var m = (add ? "add" : "remove") + "EventListener"; child[m]("webkitTransitionEnd", this._endTransitionHandler); child[m]("transitionend", this._endTransitionHandler); // IE10 + FF }, _setTransitionProperties: function (child) { child.style.webkitTransitionProperty = "-webkit-transform"; child.style.transitionProperty = "transform"; child.style.webkitTransitionDuration = "0.3s"; child.style.mozTransitionDuration = "0.3s"; child.style.transitionDuration = "0.3s"; }, _clearTransitionProperties: function (child) { child.style.webkitTransitionProperty = ""; child.style.transitionProperty = ""; child.style.webkitTransitionDuration = ""; child.style.mozTransitionDuration = ""; child.style.transitionDuration = ""; }, _setTranslation: function (child, percent) { var t = "translate3d(" + percent + "%, 0, 0)"; child.style.webkitTransform = t; child.style.transform = t; }, _clearTranslation: function (child) { child.style.webkitTransform = ""; child.style.transform = ""; } }); });
{ this._endTransitionHandler = function () { if (this._endTransitionHandler) { this._addTransitionEndHandlers(this._drag.childIn, false); this._addTransitionEndHandlers(this._drag.childOut, false); this._endTransitionHandler = null; } this._endTransition(); }.bind(this); this._addTransitionEndHandlers(this._drag.childIn, true); this._addTransitionEndHandlers(this._drag.childOut, true); }
conditional_block
SwapView.js
/** @module deliteful/SwapView */ define([ "dcl/dcl", "delite/register", "requirejs-dplugins/jquery!attributes/classes", "dpointer/events", "./ViewStack", "delite/theme!./SwapView/themes/{{theme}}/SwapView.css" ], function (dcl, register, $, dpointer, ViewStack) { /** * SwapView container widget. Extends ViewStack to let the user swap the visible child using a swipe gesture. * You can also use the Page Up / Down keyboard keys to go to the next/previous child. * * @example: * <d-swap-view id="sv"> * <div id="childA">...</div> * <div id="childB">...</div> * <div id="childC">...</div> * </d-swap-view> * @class module:deliteful/SwapView * @augments module:deliteful/ViewStack */ return register("d-swap-view", [HTMLElement, ViewStack], /** @lends module:deliteful/SwapView# */{ /** * The name of the CSS class of this widget. Note that this element also use the d-view-stack class to * leverage `deliteful/ViewStack` styles. * @member {string} * @default "d-swap-view" */ baseClass: "d-swap-view", /** * Drag threshold: drag will start only if the user moves the pointer more than this threshold. * @member {number} * @default 10 * @private */ _dragThreshold: 10, /** * Swap threshold: number between 0 and 1 that determines the minimum swipe gesture to swap the view. * Default is 0.25 which means that you must drag (horizontally) by more than 1/4 of the view size to swap * views. * @member {number} * @default 0.25 */ swapThreshold: 0.25, render: function () { dpointer.setTouchAction(this, "pan-y"); }, attachedCallback: function () { // If the user hasn't specified a tabindex declaratively, then set to default value. if (!this.hasAttribute("tabindex")) { this.tabIndex = "0"; } }, preRender: function () { // we want to inherit from ViewStack's CSS (including transitions). $(this).addClass("d-view-stack"); }, postRender: function () { this.on("pointerdown", this._pointerDownHandler.bind(this)); this.on("pointermove", this._pointerMoveHandler.bind(this)); this.on("pointerup", this._pointerUpHandler.bind(this)); this.on("lostpointercapture", this._pointerUpHandler.bind(this)); this.on("pointercancel", this._pointerUpHandler.bind(this)); this.on("keydown", this._keyDownHandler.bind(this)); }, /** * Starts drag/swipe interaction. * @private */ _pointerDownHandler: function (e) { if (!this._drag) { this._drag = { start: e.clientX }; dpointer.setPointerCapture(e.target, e.pointerId); } }, /** * Handle pointer move events during drag/swipe interaction.
if (this._drag) { var dx = e.clientX - this._drag.start; if (!this._drag.started && Math.abs(dx) > this._dragThreshold) { // user dragged (more than the threshold), start sliding children. var childOut = this._visibleChild; var childIn = (this.effectiveDir === "ltr" ? dx < 0 : dx > 0) ? childOut.nextElementSibling : childOut.previousElementSibling; if (childIn) { this._drag.childOut = childOut; this._drag.childIn = childIn; this._drag.started = true; this._drag.ended = false; this._drag.reverse = dx > 0; $(this).addClass("-d-swap-view-drag"); childIn.style.visibility = "visible"; childIn.style.display = ""; } } if (this._drag.started && !this._drag.ended) { // This is what will really translate the children as the user swipes/drags. var rx = this._drag.rx = dx / this.offsetWidth; var v = this._drag.reverse ? rx : -rx; var lv = Math.floor((this._drag.reverse ? 1 - v : v) * 100); var rv = Math.floor((this._drag.reverse ? v : 1 - v) * 100); var left = this._drag.reverse ? this._drag.childIn : this._drag.childOut; var right = this._drag.reverse ? this._drag.childOut : this._drag.childIn; this._setTranslation(left, -lv); this._setTranslation(right, rv); } } }, /** * Handle end of drag/swipe interaction. * @private */ _pointerUpHandler: function () { if (this._drag) { if (!this._drag.started) { // abort before user really dragged this._drag = null; } else if (!this._drag.ended) { // user released finger/mouse this._drag.ended = true; this._setupTransitionEndHandlers(); this._setTransitionProperties(this._drag.childIn); this._setTransitionProperties(this._drag.childOut); if ((this._drag.reverse && this._drag.rx > this.swapThreshold) || (!this._drag.reverse && this._drag.rx < -this.swapThreshold)) { // user dragged more than the swap threshold: finish sliding to the next/prev child. this._setTranslation(this._drag.childIn, 0); this._setTranslation(this._drag.childOut, this._drag.reverse ? 100 : -100); } else { // user dragged less then the swap threshold: slide back to the current child. this._drag.slideBack = true; this._setTranslation(this._drag.childIn, this._drag.reverse ? -100 : 100); this._setTranslation(this._drag.childOut, 0); } } } }, /** * Handle Page Up/Down keys to show the previous/next child. * @private */ _keyDownHandler: function (e) { switch (e.key) { case "PageUp": this.showNext(); break; case "PageDown": this.showPrevious({reverse: true}); break; } }, _setupTransitionEndHandlers: function () { // set listeners to cleanup all CSS classes after the slide transition (either from ViewStack::show, // of from the slide back animation). if (!this._endTransitionHandler) { this._endTransitionHandler = function () { if (this._endTransitionHandler) { this._addTransitionEndHandlers(this._drag.childIn, false); this._addTransitionEndHandlers(this._drag.childOut, false); this._endTransitionHandler = null; } this._endTransition(); }.bind(this); this._addTransitionEndHandlers(this._drag.childIn, true); this._addTransitionEndHandlers(this._drag.childOut, true); } }, /** * Cleanup all CSS classes and added rules after transition. * @private */ _endTransition: function () { if (this._drag) { $(this).removeClass("-d-swap-view-drag"); if (this._drag.slideBack) { // Hide the "in" view if the wap was cancelled (slide back). this._drag.childIn.style.visibility = "hidden"; this._drag.childIn.style.display = "none"; } else { this._drag.childOut.style.visibility = "hidden"; this._drag.childOut.style.display = "none"; this.show(this._drag.childIn, {transition: "none"}); } this._clearTransitionProperties(this._drag.childIn); this._clearTransitionProperties(this._drag.childOut); this._clearTranslation(this._drag.childIn); this._clearTranslation(this._drag.childOut); this._drag = null; } }, // CSS/events utilities _addTransitionEndHandlers: function (child, add) { var m = (add ? "add" : "remove") + "EventListener"; child[m]("webkitTransitionEnd", this._endTransitionHandler); child[m]("transitionend", this._endTransitionHandler); // IE10 + FF }, _setTransitionProperties: function (child) { child.style.webkitTransitionProperty = "-webkit-transform"; child.style.transitionProperty = "transform"; child.style.webkitTransitionDuration = "0.3s"; child.style.mozTransitionDuration = "0.3s"; child.style.transitionDuration = "0.3s"; }, _clearTransitionProperties: function (child) { child.style.webkitTransitionProperty = ""; child.style.transitionProperty = ""; child.style.webkitTransitionDuration = ""; child.style.mozTransitionDuration = ""; child.style.transitionDuration = ""; }, _setTranslation: function (child, percent) { var t = "translate3d(" + percent + "%, 0, 0)"; child.style.webkitTransform = t; child.style.transform = t; }, _clearTranslation: function (child) { child.style.webkitTransform = ""; child.style.transform = ""; } }); });
* @private */ _pointerMoveHandler: function (e) { /* jshint maxcomplexity: 13 */
random_line_split
eui48.py
#----------------------------------------------------------------------------- # Copyright (c) 2008-2015, David P. D. Moss. All rights reserved. # # Released under the BSD license. See the LICENSE file for details. #----------------------------------------------------------------------------- """ IEEE 48-bit EUI (MAC address) logic. Supports numerous MAC string formats including Cisco's triple hextet as well as bare MACs containing no delimiters. """ import struct as _struct import re as _re # Check whether we need to use fallback code or not. try: from socket import AF_LINK except ImportError: AF_LINK = 48 from netaddr.core import AddrFormatError from netaddr.strategy import \ valid_words as _valid_words, \ int_to_words as _int_to_words, \ words_to_int as _words_to_int, \ valid_bits as _valid_bits, \ bits_to_int as _bits_to_int, \ int_to_bits as _int_to_bits, \ valid_bin as _valid_bin, \ int_to_bin as _int_to_bin, \ bin_to_int as _bin_to_int from netaddr.compat import _is_str #: The width (in bits) of this address type. width = 48 #: The AF_* constant value of this address type. family = AF_LINK #: A friendly string name address type. family_name = 'MAC' #: The version of this address type. version = 48 #: The maximum integer value that can be represented by this address type. max_int = 2 ** width - 1 #----------------------------------------------------------------------------- # Dialect classes. #----------------------------------------------------------------------------- class mac_eui48(object): """A standard IEEE EUI-48 dialect class.""" #: The individual word size (in bits) of this address type. word_size = 8 #: The number of words in this address type. num_words = width // word_size #: The maximum integer value for an individual word in this address type. max_word = 2 ** word_size - 1 #: The separator character used between each word. word_sep = '-' #: The format string to be used when converting words to string values. word_fmt = '%.2X' #: The number base to be used when interpreting word values as integers. word_base = 16 class mac_unix(mac_eui48): """A UNIX-style MAC address dialect class.""" word_size = 8 num_words = width // word_size word_sep = ':' word_fmt = '%x' word_base = 16 class mac_unix_expanded(mac_unix): """A UNIX-style MAC address dialect class with leading zeroes.""" word_fmt = '%.2x' class mac_cisco(mac_eui48): """A Cisco 'triple hextet' MAC address dialect class.""" word_size = 16 num_words = width // word_size word_sep = '.' word_fmt = '%.4x' word_base = 16 class mac_bare(mac_eui48): """A bare (no delimiters) MAC address dialect class.""" word_size = 48 num_words = width // word_size word_sep = '' word_fmt = '%.12X' word_base = 16 class mac_pgsql(mac_eui48): """A PostgreSQL style (2 x 24-bit words) MAC address dialect class.""" word_size = 24 num_words = width // word_size word_sep = ':' word_fmt = '%.6x' word_base = 16 #: The default dialect to be used when not specified by the user. DEFAULT_DIALECT = mac_eui48 #----------------------------------------------------------------------------- #: Regular expressions to match all supported MAC address formats. RE_MAC_FORMATS = ( # 2 bytes x 6 (UNIX, Windows, EUI-48) '^' + ':'.join(['([0-9A-F]{1,2})'] * 6) + '$', '^' + '-'.join(['([0-9A-F]{1,2})'] * 6) + '$', # 4 bytes x 3 (Cisco) '^' + ':'.join(['([0-9A-F]{1,4})'] * 3) + '$', '^' + '-'.join(['([0-9A-F]{1,4})'] * 3) + '$', '^' + '\.'.join(['([0-9A-F]{1,4})'] * 3) + '$', # 6 bytes x 2 (PostgreSQL) '^' + '-'.join(['([0-9A-F]{5,6})'] * 2) + '$', '^' + ':'.join(['([0-9A-F]{5,6})'] * 2) + '$', # 12 bytes (bare, no delimiters) '^(' + ''.join(['[0-9A-F]'] * 12) + ')$', '^(' + ''.join(['[0-9A-F]'] * 11) + ')$', ) # For efficiency, each string regexp converted in place to its compiled # counterpart. RE_MAC_FORMATS = [_re.compile(_, _re.IGNORECASE) for _ in RE_MAC_FORMATS] def valid_str(addr): """ :param addr: An IEEE EUI-48 (MAC) address in string form. :return: ``True`` if MAC address string is valid, ``False`` otherwise. """ for regexp in RE_MAC_FORMATS: try: match_result = regexp.findall(addr) if len(match_result) != 0: return True except TypeError: pass return False def str_to_int(addr): """ :param addr: An IEEE EUI-48 (MAC) address in string form. :return: An unsigned integer that is equivalent to value represented by EUI-48/MAC string address formatted according to the dialect settings. """ words = [] if _is_str(addr): found_match = False for regexp in RE_MAC_FORMATS: match_result = regexp.findall(addr) if len(match_result) != 0: found_match = True if isinstance(match_result[0], tuple): words = match_result[0] else: words = (match_result[0],) break if not found_match: raise AddrFormatError('%r is not a supported MAC format!' % addr) else: raise TypeError('%r is not str() or unicode()!' % addr) int_val = None if len(words) == 6: # 2 bytes x 6 (UNIX, Windows, EUI-48) int_val = int(''.join(['%.2x' % int(w, 16) for w in words]), 16) elif len(words) == 3: # 4 bytes x 3 (Cisco) int_val = int(''.join(['%.4x' % int(w, 16) for w in words]), 16) elif len(words) == 2: # 6 bytes x 2 (PostgreSQL) int_val = int(''.join(['%.6x' % int(w, 16) for w in words]), 16) elif len(words) == 1: # 12 bytes (bare, no delimiters) int_val = int('%012x' % int(words[0], 16), 16) else: raise AddrFormatError('unexpected word count in MAC address %r!' \ % addr) return int_val def int_to_str(int_val, dialect=None): """ :param int_val: An unsigned integer. :param dialect: (optional) a Python class defining formatting options. :return: An IEEE EUI-48 (MAC) address string that is equivalent to unsigned integer formatted according to the dialect settings. """ if dialect is None: dialect = mac_eui48 words = int_to_words(int_val, dialect) tokens = [dialect.word_fmt % i for i in words] addr = dialect.word_sep.join(tokens) return addr def int_to_packed(int_val): """ :param int_val: the integer to be packed. :return: a packed string that is equivalent to value represented by an unsigned integer. """ return _struct.pack(">HI", int_val >> 32, int_val & 0xffffffff) def packed_to_int(packed_int): """ :param packed_int: a packed string containing an unsigned integer. It is assumed that string is packed in network byte order. :return: An unsigned integer equivalent to value of network address represented by packed binary string. """ words = list(_struct.unpack('>6B', packed_int)) int_val = 0 for i, num in enumerate(reversed(words)): word = num word = word << 8 * i int_val = int_val | word return int_val def valid_words(words, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _valid_words(words, dialect.word_size, dialect.num_words) def int_to_words(int_val, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _int_to_words(int_val, dialect.word_size, dialect.num_words) def words_to_int(words, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _words_to_int(words, dialect.word_size, dialect.num_words) def valid_bits(bits, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _valid_bits(bits, width, dialect.word_sep) def bits_to_int(bits, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _bits_to_int(bits, width, dialect.word_sep) def
(int_val, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _int_to_bits(int_val, dialect.word_size, dialect.num_words, dialect.word_sep) def valid_bin(bin_val, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _valid_bin(bin_val, width) def int_to_bin(int_val): return _int_to_bin(int_val, width) def bin_to_int(bin_val): return _bin_to_int(bin_val, width)
int_to_bits
identifier_name
eui48.py
#----------------------------------------------------------------------------- # Copyright (c) 2008-2015, David P. D. Moss. All rights reserved. # # Released under the BSD license. See the LICENSE file for details. #----------------------------------------------------------------------------- """ IEEE 48-bit EUI (MAC address) logic. Supports numerous MAC string formats including Cisco's triple hextet as well as bare MACs containing no delimiters. """ import struct as _struct import re as _re # Check whether we need to use fallback code or not. try: from socket import AF_LINK except ImportError: AF_LINK = 48 from netaddr.core import AddrFormatError from netaddr.strategy import \ valid_words as _valid_words, \ int_to_words as _int_to_words, \ words_to_int as _words_to_int, \ valid_bits as _valid_bits, \ bits_to_int as _bits_to_int, \ int_to_bits as _int_to_bits, \ valid_bin as _valid_bin, \ int_to_bin as _int_to_bin, \ bin_to_int as _bin_to_int from netaddr.compat import _is_str #: The width (in bits) of this address type. width = 48 #: The AF_* constant value of this address type. family = AF_LINK #: A friendly string name address type. family_name = 'MAC' #: The version of this address type. version = 48 #: The maximum integer value that can be represented by this address type. max_int = 2 ** width - 1 #----------------------------------------------------------------------------- # Dialect classes. #----------------------------------------------------------------------------- class mac_eui48(object): """A standard IEEE EUI-48 dialect class.""" #: The individual word size (in bits) of this address type. word_size = 8 #: The number of words in this address type. num_words = width // word_size #: The maximum integer value for an individual word in this address type. max_word = 2 ** word_size - 1 #: The separator character used between each word. word_sep = '-' #: The format string to be used when converting words to string values. word_fmt = '%.2X' #: The number base to be used when interpreting word values as integers. word_base = 16 class mac_unix(mac_eui48): """A UNIX-style MAC address dialect class.""" word_size = 8 num_words = width // word_size word_sep = ':' word_fmt = '%x' word_base = 16 class mac_unix_expanded(mac_unix): """A UNIX-style MAC address dialect class with leading zeroes.""" word_fmt = '%.2x' class mac_cisco(mac_eui48): """A Cisco 'triple hextet' MAC address dialect class.""" word_size = 16 num_words = width // word_size word_sep = '.' word_fmt = '%.4x' word_base = 16 class mac_bare(mac_eui48): """A bare (no delimiters) MAC address dialect class.""" word_size = 48 num_words = width // word_size word_sep = '' word_fmt = '%.12X' word_base = 16 class mac_pgsql(mac_eui48): """A PostgreSQL style (2 x 24-bit words) MAC address dialect class.""" word_size = 24 num_words = width // word_size word_sep = ':' word_fmt = '%.6x' word_base = 16 #: The default dialect to be used when not specified by the user. DEFAULT_DIALECT = mac_eui48 #----------------------------------------------------------------------------- #: Regular expressions to match all supported MAC address formats. RE_MAC_FORMATS = ( # 2 bytes x 6 (UNIX, Windows, EUI-48) '^' + ':'.join(['([0-9A-F]{1,2})'] * 6) + '$', '^' + '-'.join(['([0-9A-F]{1,2})'] * 6) + '$', # 4 bytes x 3 (Cisco) '^' + ':'.join(['([0-9A-F]{1,4})'] * 3) + '$', '^' + '-'.join(['([0-9A-F]{1,4})'] * 3) + '$', '^' + '\.'.join(['([0-9A-F]{1,4})'] * 3) + '$', # 6 bytes x 2 (PostgreSQL) '^' + '-'.join(['([0-9A-F]{5,6})'] * 2) + '$', '^' + ':'.join(['([0-9A-F]{5,6})'] * 2) + '$', # 12 bytes (bare, no delimiters) '^(' + ''.join(['[0-9A-F]'] * 12) + ')$', '^(' + ''.join(['[0-9A-F]'] * 11) + ')$', ) # For efficiency, each string regexp converted in place to its compiled # counterpart. RE_MAC_FORMATS = [_re.compile(_, _re.IGNORECASE) for _ in RE_MAC_FORMATS] def valid_str(addr): """ :param addr: An IEEE EUI-48 (MAC) address in string form. :return: ``True`` if MAC address string is valid, ``False`` otherwise. """ for regexp in RE_MAC_FORMATS: try: match_result = regexp.findall(addr) if len(match_result) != 0: return True except TypeError: pass return False def str_to_int(addr): """ :param addr: An IEEE EUI-48 (MAC) address in string form. :return: An unsigned integer that is equivalent to value represented by EUI-48/MAC string address formatted according to the dialect settings. """ words = [] if _is_str(addr): found_match = False for regexp in RE_MAC_FORMATS: match_result = regexp.findall(addr) if len(match_result) != 0: found_match = True if isinstance(match_result[0], tuple): words = match_result[0] else: words = (match_result[0],) break if not found_match: raise AddrFormatError('%r is not a supported MAC format!' % addr) else: raise TypeError('%r is not str() or unicode()!' % addr) int_val = None if len(words) == 6: # 2 bytes x 6 (UNIX, Windows, EUI-48) int_val = int(''.join(['%.2x' % int(w, 16) for w in words]), 16) elif len(words) == 3: # 4 bytes x 3 (Cisco) int_val = int(''.join(['%.4x' % int(w, 16) for w in words]), 16) elif len(words) == 2: # 6 bytes x 2 (PostgreSQL) int_val = int(''.join(['%.6x' % int(w, 16) for w in words]), 16) elif len(words) == 1: # 12 bytes (bare, no delimiters) int_val = int('%012x' % int(words[0], 16), 16) else: raise AddrFormatError('unexpected word count in MAC address %r!' \ % addr) return int_val def int_to_str(int_val, dialect=None): """ :param int_val: An unsigned integer. :param dialect: (optional) a Python class defining formatting options. :return: An IEEE EUI-48 (MAC) address string that is equivalent to unsigned integer formatted according to the dialect settings. """ if dialect is None: dialect = mac_eui48 words = int_to_words(int_val, dialect) tokens = [dialect.word_fmt % i for i in words] addr = dialect.word_sep.join(tokens) return addr def int_to_packed(int_val): """ :param int_val: the integer to be packed. :return: a packed string that is equivalent to value represented by an unsigned integer. """ return _struct.pack(">HI", int_val >> 32, int_val & 0xffffffff) def packed_to_int(packed_int): """ :param packed_int: a packed string containing an unsigned integer. It is assumed that string is packed in network byte order. :return: An unsigned integer equivalent to value of network address represented by packed binary string. """ words = list(_struct.unpack('>6B', packed_int)) int_val = 0 for i, num in enumerate(reversed(words)): word = num word = word << 8 * i int_val = int_val | word return int_val def valid_words(words, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _valid_words(words, dialect.word_size, dialect.num_words) def int_to_words(int_val, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _int_to_words(int_val, dialect.word_size, dialect.num_words) def words_to_int(words, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _words_to_int(words, dialect.word_size, dialect.num_words) def valid_bits(bits, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _valid_bits(bits, width, dialect.word_sep) def bits_to_int(bits, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _bits_to_int(bits, width, dialect.word_sep) def int_to_bits(int_val, dialect=None): if dialect is None:
return _int_to_bits(int_val, dialect.word_size, dialect.num_words, dialect.word_sep) def valid_bin(bin_val, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _valid_bin(bin_val, width) def int_to_bin(int_val): return _int_to_bin(int_val, width) def bin_to_int(bin_val): return _bin_to_int(bin_val, width)
dialect = DEFAULT_DIALECT
conditional_block
eui48.py
#----------------------------------------------------------------------------- # Copyright (c) 2008-2015, David P. D. Moss. All rights reserved. # # Released under the BSD license. See the LICENSE file for details. #----------------------------------------------------------------------------- """ IEEE 48-bit EUI (MAC address) logic. Supports numerous MAC string formats including Cisco's triple hextet as well as bare MACs containing no delimiters. """ import struct as _struct import re as _re # Check whether we need to use fallback code or not. try: from socket import AF_LINK except ImportError: AF_LINK = 48 from netaddr.core import AddrFormatError from netaddr.strategy import \ valid_words as _valid_words, \ int_to_words as _int_to_words, \ words_to_int as _words_to_int, \ valid_bits as _valid_bits, \ bits_to_int as _bits_to_int, \ int_to_bits as _int_to_bits, \ valid_bin as _valid_bin, \
from netaddr.compat import _is_str #: The width (in bits) of this address type. width = 48 #: The AF_* constant value of this address type. family = AF_LINK #: A friendly string name address type. family_name = 'MAC' #: The version of this address type. version = 48 #: The maximum integer value that can be represented by this address type. max_int = 2 ** width - 1 #----------------------------------------------------------------------------- # Dialect classes. #----------------------------------------------------------------------------- class mac_eui48(object): """A standard IEEE EUI-48 dialect class.""" #: The individual word size (in bits) of this address type. word_size = 8 #: The number of words in this address type. num_words = width // word_size #: The maximum integer value for an individual word in this address type. max_word = 2 ** word_size - 1 #: The separator character used between each word. word_sep = '-' #: The format string to be used when converting words to string values. word_fmt = '%.2X' #: The number base to be used when interpreting word values as integers. word_base = 16 class mac_unix(mac_eui48): """A UNIX-style MAC address dialect class.""" word_size = 8 num_words = width // word_size word_sep = ':' word_fmt = '%x' word_base = 16 class mac_unix_expanded(mac_unix): """A UNIX-style MAC address dialect class with leading zeroes.""" word_fmt = '%.2x' class mac_cisco(mac_eui48): """A Cisco 'triple hextet' MAC address dialect class.""" word_size = 16 num_words = width // word_size word_sep = '.' word_fmt = '%.4x' word_base = 16 class mac_bare(mac_eui48): """A bare (no delimiters) MAC address dialect class.""" word_size = 48 num_words = width // word_size word_sep = '' word_fmt = '%.12X' word_base = 16 class mac_pgsql(mac_eui48): """A PostgreSQL style (2 x 24-bit words) MAC address dialect class.""" word_size = 24 num_words = width // word_size word_sep = ':' word_fmt = '%.6x' word_base = 16 #: The default dialect to be used when not specified by the user. DEFAULT_DIALECT = mac_eui48 #----------------------------------------------------------------------------- #: Regular expressions to match all supported MAC address formats. RE_MAC_FORMATS = ( # 2 bytes x 6 (UNIX, Windows, EUI-48) '^' + ':'.join(['([0-9A-F]{1,2})'] * 6) + '$', '^' + '-'.join(['([0-9A-F]{1,2})'] * 6) + '$', # 4 bytes x 3 (Cisco) '^' + ':'.join(['([0-9A-F]{1,4})'] * 3) + '$', '^' + '-'.join(['([0-9A-F]{1,4})'] * 3) + '$', '^' + '\.'.join(['([0-9A-F]{1,4})'] * 3) + '$', # 6 bytes x 2 (PostgreSQL) '^' + '-'.join(['([0-9A-F]{5,6})'] * 2) + '$', '^' + ':'.join(['([0-9A-F]{5,6})'] * 2) + '$', # 12 bytes (bare, no delimiters) '^(' + ''.join(['[0-9A-F]'] * 12) + ')$', '^(' + ''.join(['[0-9A-F]'] * 11) + ')$', ) # For efficiency, each string regexp converted in place to its compiled # counterpart. RE_MAC_FORMATS = [_re.compile(_, _re.IGNORECASE) for _ in RE_MAC_FORMATS] def valid_str(addr): """ :param addr: An IEEE EUI-48 (MAC) address in string form. :return: ``True`` if MAC address string is valid, ``False`` otherwise. """ for regexp in RE_MAC_FORMATS: try: match_result = regexp.findall(addr) if len(match_result) != 0: return True except TypeError: pass return False def str_to_int(addr): """ :param addr: An IEEE EUI-48 (MAC) address in string form. :return: An unsigned integer that is equivalent to value represented by EUI-48/MAC string address formatted according to the dialect settings. """ words = [] if _is_str(addr): found_match = False for regexp in RE_MAC_FORMATS: match_result = regexp.findall(addr) if len(match_result) != 0: found_match = True if isinstance(match_result[0], tuple): words = match_result[0] else: words = (match_result[0],) break if not found_match: raise AddrFormatError('%r is not a supported MAC format!' % addr) else: raise TypeError('%r is not str() or unicode()!' % addr) int_val = None if len(words) == 6: # 2 bytes x 6 (UNIX, Windows, EUI-48) int_val = int(''.join(['%.2x' % int(w, 16) for w in words]), 16) elif len(words) == 3: # 4 bytes x 3 (Cisco) int_val = int(''.join(['%.4x' % int(w, 16) for w in words]), 16) elif len(words) == 2: # 6 bytes x 2 (PostgreSQL) int_val = int(''.join(['%.6x' % int(w, 16) for w in words]), 16) elif len(words) == 1: # 12 bytes (bare, no delimiters) int_val = int('%012x' % int(words[0], 16), 16) else: raise AddrFormatError('unexpected word count in MAC address %r!' \ % addr) return int_val def int_to_str(int_val, dialect=None): """ :param int_val: An unsigned integer. :param dialect: (optional) a Python class defining formatting options. :return: An IEEE EUI-48 (MAC) address string that is equivalent to unsigned integer formatted according to the dialect settings. """ if dialect is None: dialect = mac_eui48 words = int_to_words(int_val, dialect) tokens = [dialect.word_fmt % i for i in words] addr = dialect.word_sep.join(tokens) return addr def int_to_packed(int_val): """ :param int_val: the integer to be packed. :return: a packed string that is equivalent to value represented by an unsigned integer. """ return _struct.pack(">HI", int_val >> 32, int_val & 0xffffffff) def packed_to_int(packed_int): """ :param packed_int: a packed string containing an unsigned integer. It is assumed that string is packed in network byte order. :return: An unsigned integer equivalent to value of network address represented by packed binary string. """ words = list(_struct.unpack('>6B', packed_int)) int_val = 0 for i, num in enumerate(reversed(words)): word = num word = word << 8 * i int_val = int_val | word return int_val def valid_words(words, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _valid_words(words, dialect.word_size, dialect.num_words) def int_to_words(int_val, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _int_to_words(int_val, dialect.word_size, dialect.num_words) def words_to_int(words, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _words_to_int(words, dialect.word_size, dialect.num_words) def valid_bits(bits, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _valid_bits(bits, width, dialect.word_sep) def bits_to_int(bits, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _bits_to_int(bits, width, dialect.word_sep) def int_to_bits(int_val, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _int_to_bits(int_val, dialect.word_size, dialect.num_words, dialect.word_sep) def valid_bin(bin_val, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _valid_bin(bin_val, width) def int_to_bin(int_val): return _int_to_bin(int_val, width) def bin_to_int(bin_val): return _bin_to_int(bin_val, width)
int_to_bin as _int_to_bin, \ bin_to_int as _bin_to_int
random_line_split
eui48.py
#----------------------------------------------------------------------------- # Copyright (c) 2008-2015, David P. D. Moss. All rights reserved. # # Released under the BSD license. See the LICENSE file for details. #----------------------------------------------------------------------------- """ IEEE 48-bit EUI (MAC address) logic. Supports numerous MAC string formats including Cisco's triple hextet as well as bare MACs containing no delimiters. """ import struct as _struct import re as _re # Check whether we need to use fallback code or not. try: from socket import AF_LINK except ImportError: AF_LINK = 48 from netaddr.core import AddrFormatError from netaddr.strategy import \ valid_words as _valid_words, \ int_to_words as _int_to_words, \ words_to_int as _words_to_int, \ valid_bits as _valid_bits, \ bits_to_int as _bits_to_int, \ int_to_bits as _int_to_bits, \ valid_bin as _valid_bin, \ int_to_bin as _int_to_bin, \ bin_to_int as _bin_to_int from netaddr.compat import _is_str #: The width (in bits) of this address type. width = 48 #: The AF_* constant value of this address type. family = AF_LINK #: A friendly string name address type. family_name = 'MAC' #: The version of this address type. version = 48 #: The maximum integer value that can be represented by this address type. max_int = 2 ** width - 1 #----------------------------------------------------------------------------- # Dialect classes. #----------------------------------------------------------------------------- class mac_eui48(object): """A standard IEEE EUI-48 dialect class.""" #: The individual word size (in bits) of this address type. word_size = 8 #: The number of words in this address type. num_words = width // word_size #: The maximum integer value for an individual word in this address type. max_word = 2 ** word_size - 1 #: The separator character used between each word. word_sep = '-' #: The format string to be used when converting words to string values. word_fmt = '%.2X' #: The number base to be used when interpreting word values as integers. word_base = 16 class mac_unix(mac_eui48): """A UNIX-style MAC address dialect class.""" word_size = 8 num_words = width // word_size word_sep = ':' word_fmt = '%x' word_base = 16 class mac_unix_expanded(mac_unix): """A UNIX-style MAC address dialect class with leading zeroes.""" word_fmt = '%.2x' class mac_cisco(mac_eui48): """A Cisco 'triple hextet' MAC address dialect class.""" word_size = 16 num_words = width // word_size word_sep = '.' word_fmt = '%.4x' word_base = 16 class mac_bare(mac_eui48): """A bare (no delimiters) MAC address dialect class.""" word_size = 48 num_words = width // word_size word_sep = '' word_fmt = '%.12X' word_base = 16 class mac_pgsql(mac_eui48):
#: The default dialect to be used when not specified by the user. DEFAULT_DIALECT = mac_eui48 #----------------------------------------------------------------------------- #: Regular expressions to match all supported MAC address formats. RE_MAC_FORMATS = ( # 2 bytes x 6 (UNIX, Windows, EUI-48) '^' + ':'.join(['([0-9A-F]{1,2})'] * 6) + '$', '^' + '-'.join(['([0-9A-F]{1,2})'] * 6) + '$', # 4 bytes x 3 (Cisco) '^' + ':'.join(['([0-9A-F]{1,4})'] * 3) + '$', '^' + '-'.join(['([0-9A-F]{1,4})'] * 3) + '$', '^' + '\.'.join(['([0-9A-F]{1,4})'] * 3) + '$', # 6 bytes x 2 (PostgreSQL) '^' + '-'.join(['([0-9A-F]{5,6})'] * 2) + '$', '^' + ':'.join(['([0-9A-F]{5,6})'] * 2) + '$', # 12 bytes (bare, no delimiters) '^(' + ''.join(['[0-9A-F]'] * 12) + ')$', '^(' + ''.join(['[0-9A-F]'] * 11) + ')$', ) # For efficiency, each string regexp converted in place to its compiled # counterpart. RE_MAC_FORMATS = [_re.compile(_, _re.IGNORECASE) for _ in RE_MAC_FORMATS] def valid_str(addr): """ :param addr: An IEEE EUI-48 (MAC) address in string form. :return: ``True`` if MAC address string is valid, ``False`` otherwise. """ for regexp in RE_MAC_FORMATS: try: match_result = regexp.findall(addr) if len(match_result) != 0: return True except TypeError: pass return False def str_to_int(addr): """ :param addr: An IEEE EUI-48 (MAC) address in string form. :return: An unsigned integer that is equivalent to value represented by EUI-48/MAC string address formatted according to the dialect settings. """ words = [] if _is_str(addr): found_match = False for regexp in RE_MAC_FORMATS: match_result = regexp.findall(addr) if len(match_result) != 0: found_match = True if isinstance(match_result[0], tuple): words = match_result[0] else: words = (match_result[0],) break if not found_match: raise AddrFormatError('%r is not a supported MAC format!' % addr) else: raise TypeError('%r is not str() or unicode()!' % addr) int_val = None if len(words) == 6: # 2 bytes x 6 (UNIX, Windows, EUI-48) int_val = int(''.join(['%.2x' % int(w, 16) for w in words]), 16) elif len(words) == 3: # 4 bytes x 3 (Cisco) int_val = int(''.join(['%.4x' % int(w, 16) for w in words]), 16) elif len(words) == 2: # 6 bytes x 2 (PostgreSQL) int_val = int(''.join(['%.6x' % int(w, 16) for w in words]), 16) elif len(words) == 1: # 12 bytes (bare, no delimiters) int_val = int('%012x' % int(words[0], 16), 16) else: raise AddrFormatError('unexpected word count in MAC address %r!' \ % addr) return int_val def int_to_str(int_val, dialect=None): """ :param int_val: An unsigned integer. :param dialect: (optional) a Python class defining formatting options. :return: An IEEE EUI-48 (MAC) address string that is equivalent to unsigned integer formatted according to the dialect settings. """ if dialect is None: dialect = mac_eui48 words = int_to_words(int_val, dialect) tokens = [dialect.word_fmt % i for i in words] addr = dialect.word_sep.join(tokens) return addr def int_to_packed(int_val): """ :param int_val: the integer to be packed. :return: a packed string that is equivalent to value represented by an unsigned integer. """ return _struct.pack(">HI", int_val >> 32, int_val & 0xffffffff) def packed_to_int(packed_int): """ :param packed_int: a packed string containing an unsigned integer. It is assumed that string is packed in network byte order. :return: An unsigned integer equivalent to value of network address represented by packed binary string. """ words = list(_struct.unpack('>6B', packed_int)) int_val = 0 for i, num in enumerate(reversed(words)): word = num word = word << 8 * i int_val = int_val | word return int_val def valid_words(words, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _valid_words(words, dialect.word_size, dialect.num_words) def int_to_words(int_val, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _int_to_words(int_val, dialect.word_size, dialect.num_words) def words_to_int(words, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _words_to_int(words, dialect.word_size, dialect.num_words) def valid_bits(bits, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _valid_bits(bits, width, dialect.word_sep) def bits_to_int(bits, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _bits_to_int(bits, width, dialect.word_sep) def int_to_bits(int_val, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _int_to_bits(int_val, dialect.word_size, dialect.num_words, dialect.word_sep) def valid_bin(bin_val, dialect=None): if dialect is None: dialect = DEFAULT_DIALECT return _valid_bin(bin_val, width) def int_to_bin(int_val): return _int_to_bin(int_val, width) def bin_to_int(bin_val): return _bin_to_int(bin_val, width)
"""A PostgreSQL style (2 x 24-bit words) MAC address dialect class.""" word_size = 24 num_words = width // word_size word_sep = ':' word_fmt = '%.6x' word_base = 16
identifier_body
builder.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # module builder script # import os, sys, shutil, tempfile, subprocess, platform template_dir = os.path.abspath(os.path.dirname(sys._getframe(0).f_code.co_filename)) support_dir = os.path.join(template_dir, 'support') sdk_dir = os.path.dirname(template_dir) android_support_dir = os.path.join(sdk_dir, 'android') sys.path.extend([sdk_dir, support_dir, android_support_dir]) from androidsdk import AndroidSDK from manifest import Manifest import traceback, uuid, time, thread, string, markdown from os.path import join, splitext, split, exists def run_pipe(args, cwd=None): return subprocess.Popen(args, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, cwd=cwd) def print_emulator_line(line): if line: s = line.strip() if s!='': if s.startswith("["): print s else: print "[DEBUG] %s" % s sys.stdout.flush() def run_python(args, cwd=None): args.insert(0, sys.executable) return run(args, cwd=cwd) def run(args, cwd=None): proc = run_pipe(args, cwd) rc = None while True: print_emulator_line(proc.stdout.readline()) rc = proc.poll() if rc!=None: break return rc def run_ant(project_dir): build_xml = os.path.join(project_dir, 'build.xml') ant = 'ant' if 'ANT_HOME' in os.environ: ant = os.path.join(os.environ['ANT_HOME'], 'bin', 'ant') if platform.system() == 'Windows': ant += '.bat' ant_args = [ant, '-f', build_xml] if platform.system() == 'Windows': ant_args = ['cmd.exe', '/C'] + ant_args else: # wrap with /bin/sh in Unix, in some cases the script itself isn't executable ant_args = ['/bin/sh'] + ant_args run(ant_args, cwd=project_dir) ignoreFiles = ['.gitignore', '.cvsignore', '.DS_Store']; ignoreDirs = ['.git','.svn','_svn','CVS']; android_sdk = None def copy_resources(source, target): if not os.path.exists(os.path.expanduser(target)): os.makedirs(os.path.expanduser(target)) for root, dirs, files in os.walk(source): for name in ignoreDirs: if name in dirs: dirs.remove(name) # don't visit ignored directories for file in files: if file in ignoreFiles: continue from_ = os.path.join(root, file) to_ = os.path.expanduser(from_.replace(source, target, 1)) to_directory = os.path.expanduser(split(to_)[0]) if not exists(to_directory): os.makedirs(to_directory) shutil.copyfile(from_, to_) def is_ios(platform): return platform == 'iphone' or platform == 'ipad' or platform == 'ios' def is_android(platform): return platform == 'android' def stage(platform, project_dir, manifest, callback): dont_delete = True dir = tempfile.mkdtemp('ti','m') print '[DEBUG] Staging module project at %s' % dir try: name = manifest.name moduleid = manifest.moduleid version = manifest.version script = os.path.join(template_dir,'..','project.py') # create a temporary proj create_project_args = [script, name, moduleid, dir, platform] if is_android(platform): create_project_args.append(android_sdk.get_android_sdk()) run_python(create_project_args) gen_project_dir = os.path.join(dir, name) gen_resources_dir = os.path.join(gen_project_dir, 'Resources') # copy in our example source copy_resources(os.path.join(project_dir,'example'), gen_resources_dir) # patch in our tiapp.xml tiapp = os.path.join(gen_project_dir, 'tiapp.xml') xml = open(tiapp).read() tiappf = open(tiapp,'w') xml = xml.replace('<guid/>','<guid></guid>') xml = xml.replace('</guid>','</guid>\n<modules>\n<module version="%s">%s</module>\n</modules>\n' % (version,moduleid)) # generate a guid since this is currently done by developer guid = str(uuid.uuid4()) xml = xml.replace('<guid></guid>','<guid>%s</guid>' % guid) tiappf.write(xml) tiappf.close() module_dir = os.path.join(gen_project_dir,'modules',platform) if not os.path.exists(module_dir): os.makedirs(module_dir) module_zip_name = '%s-%s-%s.zip' % (moduleid.lower(), platform, version) module_zip = os.path.join(project_dir, 'dist', module_zip_name) if is_ios(platform): module_zip = os.path.join(project_dir, module_zip_name) script = os.path.join(project_dir,'build.py') run_python([script]) elif is_android(platform): run_ant(project_dir) shutil.copy(module_zip, gen_project_dir) callback(gen_project_dir) except: dont_delete = True traceback.print_exc(file=sys.stderr) sys.exit(1) finally: if not dont_delete: shutil.rmtree(dir) def docgen(module_dir, dest_dir): if not os.path.exists(dest_dir): print "Creating dir: %s" % dest_dir os.makedirs(dest_dir) doc_dir = os.path.join(module_dir, 'documentation') if not os.path.exists(doc_dir): print "Couldn't find documentation file at: %s" % doc_dir return for file in os.listdir(doc_dir): if file in ignoreFiles or os.path.isdir(os.path.join(doc_dir, file)): continue md = open(os.path.join(doc_dir, file), 'r').read() html = markdown.markdown(md) filename = string.replace(file, '.md', '.html') filepath = os.path.join(dest_dir, filename) print 'Generating %s' % filepath open(filepath, 'w+').write(html) # a simplified .properties file parser def read_properties(file): properties = {} for line in file.read().splitlines(): line = line.strip() if len(line) > 0 and line[0] == '#':
if len(line) == 0 or '=' not in line: continue key, value = line.split('=', 1) properties[key.strip()] = value.strip().replace('\\\\', '\\') return properties def main(args): global android_sdk # command platform project_dir command = args[1] platform = args[2] project_dir = os.path.expanduser(args[3]) manifest = Manifest(os.path.join(project_dir, 'manifest')) error = False if is_android(platform): build_properties = read_properties(open(os.path.join(project_dir, 'build.properties'))) android_sdk_path = os.path.dirname(os.path.dirname(build_properties['android.platform'])) android_sdk = AndroidSDK(android_sdk_path) if command == 'run': def run_callback(gen_project_dir): script = os.path.abspath(os.path.join(template_dir,'..',platform,'builder.py')) script_args = [script, 'run', gen_project_dir] if is_android(platform): script_args.append(android_sdk.get_android_sdk()) rc = run_python(script_args) # run the project if rc==1: if is_ios(platform): error = os.path.join(gen_project_dir,'build','iphone','build','build.log') print "[ERROR] Build Failed. See: %s" % os.path.abspath(error) else: print "[ERROR] Build Failed." stage(platform, project_dir, manifest, run_callback) elif command == 'run-emulator': if is_android(platform): def run_emulator_callback(gen_project_dir): script = os.path.abspath(os.path.join(template_dir, '..', platform, 'builder.py')) run_python([script, 'run-emulator', gen_project_dir, android_sdk.get_android_sdk()]) stage(platform, project_dir, manifest, run_emulator_callback) elif command == 'docgen': if is_android(platform): dest_dir = args[4] docgen(project_dir, dest_dir) if error: sys.exit(1) else: sys.exit(0) if __name__ == "__main__": main(sys.argv)
continue
conditional_block
builder.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # module builder script # import os, sys, shutil, tempfile, subprocess, platform template_dir = os.path.abspath(os.path.dirname(sys._getframe(0).f_code.co_filename)) support_dir = os.path.join(template_dir, 'support') sdk_dir = os.path.dirname(template_dir) android_support_dir = os.path.join(sdk_dir, 'android') sys.path.extend([sdk_dir, support_dir, android_support_dir]) from androidsdk import AndroidSDK from manifest import Manifest import traceback, uuid, time, thread, string, markdown from os.path import join, splitext, split, exists def run_pipe(args, cwd=None): return subprocess.Popen(args, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, cwd=cwd) def print_emulator_line(line): if line: s = line.strip() if s!='': if s.startswith("["): print s else: print "[DEBUG] %s" % s sys.stdout.flush() def run_python(args, cwd=None): args.insert(0, sys.executable) return run(args, cwd=cwd) def run(args, cwd=None): proc = run_pipe(args, cwd) rc = None while True: print_emulator_line(proc.stdout.readline()) rc = proc.poll() if rc!=None: break return rc def run_ant(project_dir): build_xml = os.path.join(project_dir, 'build.xml') ant = 'ant' if 'ANT_HOME' in os.environ: ant = os.path.join(os.environ['ANT_HOME'], 'bin', 'ant') if platform.system() == 'Windows': ant += '.bat' ant_args = [ant, '-f', build_xml] if platform.system() == 'Windows': ant_args = ['cmd.exe', '/C'] + ant_args else: # wrap with /bin/sh in Unix, in some cases the script itself isn't executable ant_args = ['/bin/sh'] + ant_args run(ant_args, cwd=project_dir) ignoreFiles = ['.gitignore', '.cvsignore', '.DS_Store']; ignoreDirs = ['.git','.svn','_svn','CVS']; android_sdk = None def copy_resources(source, target): if not os.path.exists(os.path.expanduser(target)): os.makedirs(os.path.expanduser(target)) for root, dirs, files in os.walk(source): for name in ignoreDirs: if name in dirs: dirs.remove(name) # don't visit ignored directories for file in files: if file in ignoreFiles: continue from_ = os.path.join(root, file) to_ = os.path.expanduser(from_.replace(source, target, 1)) to_directory = os.path.expanduser(split(to_)[0]) if not exists(to_directory): os.makedirs(to_directory) shutil.copyfile(from_, to_) def is_ios(platform): return platform == 'iphone' or platform == 'ipad' or platform == 'ios' def is_android(platform): return platform == 'android' def stage(platform, project_dir, manifest, callback): dont_delete = True dir = tempfile.mkdtemp('ti','m') print '[DEBUG] Staging module project at %s' % dir try: name = manifest.name moduleid = manifest.moduleid version = manifest.version script = os.path.join(template_dir,'..','project.py') # create a temporary proj create_project_args = [script, name, moduleid, dir, platform] if is_android(platform): create_project_args.append(android_sdk.get_android_sdk()) run_python(create_project_args) gen_project_dir = os.path.join(dir, name) gen_resources_dir = os.path.join(gen_project_dir, 'Resources') # copy in our example source copy_resources(os.path.join(project_dir,'example'), gen_resources_dir) # patch in our tiapp.xml tiapp = os.path.join(gen_project_dir, 'tiapp.xml') xml = open(tiapp).read() tiappf = open(tiapp,'w') xml = xml.replace('<guid/>','<guid></guid>') xml = xml.replace('</guid>','</guid>\n<modules>\n<module version="%s">%s</module>\n</modules>\n' % (version,moduleid)) # generate a guid since this is currently done by developer guid = str(uuid.uuid4()) xml = xml.replace('<guid></guid>','<guid>%s</guid>' % guid) tiappf.write(xml) tiappf.close() module_dir = os.path.join(gen_project_dir,'modules',platform) if not os.path.exists(module_dir): os.makedirs(module_dir) module_zip_name = '%s-%s-%s.zip' % (moduleid.lower(), platform, version) module_zip = os.path.join(project_dir, 'dist', module_zip_name) if is_ios(platform): module_zip = os.path.join(project_dir, module_zip_name) script = os.path.join(project_dir,'build.py') run_python([script]) elif is_android(platform): run_ant(project_dir) shutil.copy(module_zip, gen_project_dir) callback(gen_project_dir) except: dont_delete = True traceback.print_exc(file=sys.stderr) sys.exit(1) finally: if not dont_delete: shutil.rmtree(dir) def docgen(module_dir, dest_dir): if not os.path.exists(dest_dir): print "Creating dir: %s" % dest_dir os.makedirs(dest_dir) doc_dir = os.path.join(module_dir, 'documentation') if not os.path.exists(doc_dir): print "Couldn't find documentation file at: %s" % doc_dir return for file in os.listdir(doc_dir): if file in ignoreFiles or os.path.isdir(os.path.join(doc_dir, file)): continue md = open(os.path.join(doc_dir, file), 'r').read() html = markdown.markdown(md) filename = string.replace(file, '.md', '.html') filepath = os.path.join(dest_dir, filename) print 'Generating %s' % filepath open(filepath, 'w+').write(html) # a simplified .properties file parser def read_properties(file): properties = {} for line in file.read().splitlines(): line = line.strip() if len(line) > 0 and line[0] == '#': continue if len(line) == 0 or '=' not in line: continue key, value = line.split('=', 1) properties[key.strip()] = value.strip().replace('\\\\', '\\') return properties def main(args): global android_sdk # command platform project_dir command = args[1] platform = args[2] project_dir = os.path.expanduser(args[3]) manifest = Manifest(os.path.join(project_dir, 'manifest')) error = False if is_android(platform): build_properties = read_properties(open(os.path.join(project_dir, 'build.properties'))) android_sdk_path = os.path.dirname(os.path.dirname(build_properties['android.platform'])) android_sdk = AndroidSDK(android_sdk_path) if command == 'run': def run_callback(gen_project_dir): script = os.path.abspath(os.path.join(template_dir,'..',platform,'builder.py')) script_args = [script, 'run', gen_project_dir] if is_android(platform): script_args.append(android_sdk.get_android_sdk()) rc = run_python(script_args)
print "[ERROR] Build Failed. See: %s" % os.path.abspath(error) else: print "[ERROR] Build Failed." stage(platform, project_dir, manifest, run_callback) elif command == 'run-emulator': if is_android(platform): def run_emulator_callback(gen_project_dir): script = os.path.abspath(os.path.join(template_dir, '..', platform, 'builder.py')) run_python([script, 'run-emulator', gen_project_dir, android_sdk.get_android_sdk()]) stage(platform, project_dir, manifest, run_emulator_callback) elif command == 'docgen': if is_android(platform): dest_dir = args[4] docgen(project_dir, dest_dir) if error: sys.exit(1) else: sys.exit(0) if __name__ == "__main__": main(sys.argv)
# run the project if rc==1: if is_ios(platform): error = os.path.join(gen_project_dir,'build','iphone','build','build.log')
random_line_split
builder.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # module builder script # import os, sys, shutil, tempfile, subprocess, platform template_dir = os.path.abspath(os.path.dirname(sys._getframe(0).f_code.co_filename)) support_dir = os.path.join(template_dir, 'support') sdk_dir = os.path.dirname(template_dir) android_support_dir = os.path.join(sdk_dir, 'android') sys.path.extend([sdk_dir, support_dir, android_support_dir]) from androidsdk import AndroidSDK from manifest import Manifest import traceback, uuid, time, thread, string, markdown from os.path import join, splitext, split, exists def run_pipe(args, cwd=None):
def print_emulator_line(line): if line: s = line.strip() if s!='': if s.startswith("["): print s else: print "[DEBUG] %s" % s sys.stdout.flush() def run_python(args, cwd=None): args.insert(0, sys.executable) return run(args, cwd=cwd) def run(args, cwd=None): proc = run_pipe(args, cwd) rc = None while True: print_emulator_line(proc.stdout.readline()) rc = proc.poll() if rc!=None: break return rc def run_ant(project_dir): build_xml = os.path.join(project_dir, 'build.xml') ant = 'ant' if 'ANT_HOME' in os.environ: ant = os.path.join(os.environ['ANT_HOME'], 'bin', 'ant') if platform.system() == 'Windows': ant += '.bat' ant_args = [ant, '-f', build_xml] if platform.system() == 'Windows': ant_args = ['cmd.exe', '/C'] + ant_args else: # wrap with /bin/sh in Unix, in some cases the script itself isn't executable ant_args = ['/bin/sh'] + ant_args run(ant_args, cwd=project_dir) ignoreFiles = ['.gitignore', '.cvsignore', '.DS_Store']; ignoreDirs = ['.git','.svn','_svn','CVS']; android_sdk = None def copy_resources(source, target): if not os.path.exists(os.path.expanduser(target)): os.makedirs(os.path.expanduser(target)) for root, dirs, files in os.walk(source): for name in ignoreDirs: if name in dirs: dirs.remove(name) # don't visit ignored directories for file in files: if file in ignoreFiles: continue from_ = os.path.join(root, file) to_ = os.path.expanduser(from_.replace(source, target, 1)) to_directory = os.path.expanduser(split(to_)[0]) if not exists(to_directory): os.makedirs(to_directory) shutil.copyfile(from_, to_) def is_ios(platform): return platform == 'iphone' or platform == 'ipad' or platform == 'ios' def is_android(platform): return platform == 'android' def stage(platform, project_dir, manifest, callback): dont_delete = True dir = tempfile.mkdtemp('ti','m') print '[DEBUG] Staging module project at %s' % dir try: name = manifest.name moduleid = manifest.moduleid version = manifest.version script = os.path.join(template_dir,'..','project.py') # create a temporary proj create_project_args = [script, name, moduleid, dir, platform] if is_android(platform): create_project_args.append(android_sdk.get_android_sdk()) run_python(create_project_args) gen_project_dir = os.path.join(dir, name) gen_resources_dir = os.path.join(gen_project_dir, 'Resources') # copy in our example source copy_resources(os.path.join(project_dir,'example'), gen_resources_dir) # patch in our tiapp.xml tiapp = os.path.join(gen_project_dir, 'tiapp.xml') xml = open(tiapp).read() tiappf = open(tiapp,'w') xml = xml.replace('<guid/>','<guid></guid>') xml = xml.replace('</guid>','</guid>\n<modules>\n<module version="%s">%s</module>\n</modules>\n' % (version,moduleid)) # generate a guid since this is currently done by developer guid = str(uuid.uuid4()) xml = xml.replace('<guid></guid>','<guid>%s</guid>' % guid) tiappf.write(xml) tiappf.close() module_dir = os.path.join(gen_project_dir,'modules',platform) if not os.path.exists(module_dir): os.makedirs(module_dir) module_zip_name = '%s-%s-%s.zip' % (moduleid.lower(), platform, version) module_zip = os.path.join(project_dir, 'dist', module_zip_name) if is_ios(platform): module_zip = os.path.join(project_dir, module_zip_name) script = os.path.join(project_dir,'build.py') run_python([script]) elif is_android(platform): run_ant(project_dir) shutil.copy(module_zip, gen_project_dir) callback(gen_project_dir) except: dont_delete = True traceback.print_exc(file=sys.stderr) sys.exit(1) finally: if not dont_delete: shutil.rmtree(dir) def docgen(module_dir, dest_dir): if not os.path.exists(dest_dir): print "Creating dir: %s" % dest_dir os.makedirs(dest_dir) doc_dir = os.path.join(module_dir, 'documentation') if not os.path.exists(doc_dir): print "Couldn't find documentation file at: %s" % doc_dir return for file in os.listdir(doc_dir): if file in ignoreFiles or os.path.isdir(os.path.join(doc_dir, file)): continue md = open(os.path.join(doc_dir, file), 'r').read() html = markdown.markdown(md) filename = string.replace(file, '.md', '.html') filepath = os.path.join(dest_dir, filename) print 'Generating %s' % filepath open(filepath, 'w+').write(html) # a simplified .properties file parser def read_properties(file): properties = {} for line in file.read().splitlines(): line = line.strip() if len(line) > 0 and line[0] == '#': continue if len(line) == 0 or '=' not in line: continue key, value = line.split('=', 1) properties[key.strip()] = value.strip().replace('\\\\', '\\') return properties def main(args): global android_sdk # command platform project_dir command = args[1] platform = args[2] project_dir = os.path.expanduser(args[3]) manifest = Manifest(os.path.join(project_dir, 'manifest')) error = False if is_android(platform): build_properties = read_properties(open(os.path.join(project_dir, 'build.properties'))) android_sdk_path = os.path.dirname(os.path.dirname(build_properties['android.platform'])) android_sdk = AndroidSDK(android_sdk_path) if command == 'run': def run_callback(gen_project_dir): script = os.path.abspath(os.path.join(template_dir,'..',platform,'builder.py')) script_args = [script, 'run', gen_project_dir] if is_android(platform): script_args.append(android_sdk.get_android_sdk()) rc = run_python(script_args) # run the project if rc==1: if is_ios(platform): error = os.path.join(gen_project_dir,'build','iphone','build','build.log') print "[ERROR] Build Failed. See: %s" % os.path.abspath(error) else: print "[ERROR] Build Failed." stage(platform, project_dir, manifest, run_callback) elif command == 'run-emulator': if is_android(platform): def run_emulator_callback(gen_project_dir): script = os.path.abspath(os.path.join(template_dir, '..', platform, 'builder.py')) run_python([script, 'run-emulator', gen_project_dir, android_sdk.get_android_sdk()]) stage(platform, project_dir, manifest, run_emulator_callback) elif command == 'docgen': if is_android(platform): dest_dir = args[4] docgen(project_dir, dest_dir) if error: sys.exit(1) else: sys.exit(0) if __name__ == "__main__": main(sys.argv)
return subprocess.Popen(args, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, cwd=cwd)
identifier_body
builder.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # module builder script # import os, sys, shutil, tempfile, subprocess, platform template_dir = os.path.abspath(os.path.dirname(sys._getframe(0).f_code.co_filename)) support_dir = os.path.join(template_dir, 'support') sdk_dir = os.path.dirname(template_dir) android_support_dir = os.path.join(sdk_dir, 'android') sys.path.extend([sdk_dir, support_dir, android_support_dir]) from androidsdk import AndroidSDK from manifest import Manifest import traceback, uuid, time, thread, string, markdown from os.path import join, splitext, split, exists def run_pipe(args, cwd=None): return subprocess.Popen(args, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, cwd=cwd) def print_emulator_line(line): if line: s = line.strip() if s!='': if s.startswith("["): print s else: print "[DEBUG] %s" % s sys.stdout.flush() def run_python(args, cwd=None): args.insert(0, sys.executable) return run(args, cwd=cwd) def
(args, cwd=None): proc = run_pipe(args, cwd) rc = None while True: print_emulator_line(proc.stdout.readline()) rc = proc.poll() if rc!=None: break return rc def run_ant(project_dir): build_xml = os.path.join(project_dir, 'build.xml') ant = 'ant' if 'ANT_HOME' in os.environ: ant = os.path.join(os.environ['ANT_HOME'], 'bin', 'ant') if platform.system() == 'Windows': ant += '.bat' ant_args = [ant, '-f', build_xml] if platform.system() == 'Windows': ant_args = ['cmd.exe', '/C'] + ant_args else: # wrap with /bin/sh in Unix, in some cases the script itself isn't executable ant_args = ['/bin/sh'] + ant_args run(ant_args, cwd=project_dir) ignoreFiles = ['.gitignore', '.cvsignore', '.DS_Store']; ignoreDirs = ['.git','.svn','_svn','CVS']; android_sdk = None def copy_resources(source, target): if not os.path.exists(os.path.expanduser(target)): os.makedirs(os.path.expanduser(target)) for root, dirs, files in os.walk(source): for name in ignoreDirs: if name in dirs: dirs.remove(name) # don't visit ignored directories for file in files: if file in ignoreFiles: continue from_ = os.path.join(root, file) to_ = os.path.expanduser(from_.replace(source, target, 1)) to_directory = os.path.expanduser(split(to_)[0]) if not exists(to_directory): os.makedirs(to_directory) shutil.copyfile(from_, to_) def is_ios(platform): return platform == 'iphone' or platform == 'ipad' or platform == 'ios' def is_android(platform): return platform == 'android' def stage(platform, project_dir, manifest, callback): dont_delete = True dir = tempfile.mkdtemp('ti','m') print '[DEBUG] Staging module project at %s' % dir try: name = manifest.name moduleid = manifest.moduleid version = manifest.version script = os.path.join(template_dir,'..','project.py') # create a temporary proj create_project_args = [script, name, moduleid, dir, platform] if is_android(platform): create_project_args.append(android_sdk.get_android_sdk()) run_python(create_project_args) gen_project_dir = os.path.join(dir, name) gen_resources_dir = os.path.join(gen_project_dir, 'Resources') # copy in our example source copy_resources(os.path.join(project_dir,'example'), gen_resources_dir) # patch in our tiapp.xml tiapp = os.path.join(gen_project_dir, 'tiapp.xml') xml = open(tiapp).read() tiappf = open(tiapp,'w') xml = xml.replace('<guid/>','<guid></guid>') xml = xml.replace('</guid>','</guid>\n<modules>\n<module version="%s">%s</module>\n</modules>\n' % (version,moduleid)) # generate a guid since this is currently done by developer guid = str(uuid.uuid4()) xml = xml.replace('<guid></guid>','<guid>%s</guid>' % guid) tiappf.write(xml) tiappf.close() module_dir = os.path.join(gen_project_dir,'modules',platform) if not os.path.exists(module_dir): os.makedirs(module_dir) module_zip_name = '%s-%s-%s.zip' % (moduleid.lower(), platform, version) module_zip = os.path.join(project_dir, 'dist', module_zip_name) if is_ios(platform): module_zip = os.path.join(project_dir, module_zip_name) script = os.path.join(project_dir,'build.py') run_python([script]) elif is_android(platform): run_ant(project_dir) shutil.copy(module_zip, gen_project_dir) callback(gen_project_dir) except: dont_delete = True traceback.print_exc(file=sys.stderr) sys.exit(1) finally: if not dont_delete: shutil.rmtree(dir) def docgen(module_dir, dest_dir): if not os.path.exists(dest_dir): print "Creating dir: %s" % dest_dir os.makedirs(dest_dir) doc_dir = os.path.join(module_dir, 'documentation') if not os.path.exists(doc_dir): print "Couldn't find documentation file at: %s" % doc_dir return for file in os.listdir(doc_dir): if file in ignoreFiles or os.path.isdir(os.path.join(doc_dir, file)): continue md = open(os.path.join(doc_dir, file), 'r').read() html = markdown.markdown(md) filename = string.replace(file, '.md', '.html') filepath = os.path.join(dest_dir, filename) print 'Generating %s' % filepath open(filepath, 'w+').write(html) # a simplified .properties file parser def read_properties(file): properties = {} for line in file.read().splitlines(): line = line.strip() if len(line) > 0 and line[0] == '#': continue if len(line) == 0 or '=' not in line: continue key, value = line.split('=', 1) properties[key.strip()] = value.strip().replace('\\\\', '\\') return properties def main(args): global android_sdk # command platform project_dir command = args[1] platform = args[2] project_dir = os.path.expanduser(args[3]) manifest = Manifest(os.path.join(project_dir, 'manifest')) error = False if is_android(platform): build_properties = read_properties(open(os.path.join(project_dir, 'build.properties'))) android_sdk_path = os.path.dirname(os.path.dirname(build_properties['android.platform'])) android_sdk = AndroidSDK(android_sdk_path) if command == 'run': def run_callback(gen_project_dir): script = os.path.abspath(os.path.join(template_dir,'..',platform,'builder.py')) script_args = [script, 'run', gen_project_dir] if is_android(platform): script_args.append(android_sdk.get_android_sdk()) rc = run_python(script_args) # run the project if rc==1: if is_ios(platform): error = os.path.join(gen_project_dir,'build','iphone','build','build.log') print "[ERROR] Build Failed. See: %s" % os.path.abspath(error) else: print "[ERROR] Build Failed." stage(platform, project_dir, manifest, run_callback) elif command == 'run-emulator': if is_android(platform): def run_emulator_callback(gen_project_dir): script = os.path.abspath(os.path.join(template_dir, '..', platform, 'builder.py')) run_python([script, 'run-emulator', gen_project_dir, android_sdk.get_android_sdk()]) stage(platform, project_dir, manifest, run_emulator_callback) elif command == 'docgen': if is_android(platform): dest_dir = args[4] docgen(project_dir, dest_dir) if error: sys.exit(1) else: sys.exit(0) if __name__ == "__main__": main(sys.argv)
run
identifier_name
packageHandler.py
#!/usr/bin/python import piksemel import os def updateGConf (filepath, remove=False): parse = piksemel.parse (filepath) schemaList = list() for xmlfile in parse.tags ("File"): path = xmlfile.getTagData ("Path") # Only interested in /etc/gconf/schemas if "etc/gconf/schemas" in path: schemaList.append ("/%s" % path)
def setupPackage (metapath, filepath): updateGConf (filepath) def postCleanupPackage (metapath, filepath): updateGConf (filepath)
if len(schemaList) > 0: os.environ['GCONF_CONFIG_SOURCE'] = 'xml:merged:/etc/gconf/gconf.xml.defaults' operation = "--makefile-uninstall-rule" if remove else "--makefile-install-rule" cmd = "/usr/bin/gconftool-2 %s %s" % (operation, " ".join(schemaList)) os.system (cmd)
random_line_split
packageHandler.py
#!/usr/bin/python import piksemel import os def updateGConf (filepath, remove=False): parse = piksemel.parse (filepath) schemaList = list() for xmlfile in parse.tags ("File"): path = xmlfile.getTagData ("Path") # Only interested in /etc/gconf/schemas if "etc/gconf/schemas" in path: schemaList.append ("/%s" % path) if len(schemaList) > 0: os.environ['GCONF_CONFIG_SOURCE'] = 'xml:merged:/etc/gconf/gconf.xml.defaults' operation = "--makefile-uninstall-rule" if remove else "--makefile-install-rule" cmd = "/usr/bin/gconftool-2 %s %s" % (operation, " ".join(schemaList)) os.system (cmd) def setupPackage (metapath, filepath):
def postCleanupPackage (metapath, filepath): updateGConf (filepath)
updateGConf (filepath)
identifier_body
packageHandler.py
#!/usr/bin/python import piksemel import os def
(filepath, remove=False): parse = piksemel.parse (filepath) schemaList = list() for xmlfile in parse.tags ("File"): path = xmlfile.getTagData ("Path") # Only interested in /etc/gconf/schemas if "etc/gconf/schemas" in path: schemaList.append ("/%s" % path) if len(schemaList) > 0: os.environ['GCONF_CONFIG_SOURCE'] = 'xml:merged:/etc/gconf/gconf.xml.defaults' operation = "--makefile-uninstall-rule" if remove else "--makefile-install-rule" cmd = "/usr/bin/gconftool-2 %s %s" % (operation, " ".join(schemaList)) os.system (cmd) def setupPackage (metapath, filepath): updateGConf (filepath) def postCleanupPackage (metapath, filepath): updateGConf (filepath)
updateGConf
identifier_name
packageHandler.py
#!/usr/bin/python import piksemel import os def updateGConf (filepath, remove=False): parse = piksemel.parse (filepath) schemaList = list() for xmlfile in parse.tags ("File"):
if len(schemaList) > 0: os.environ['GCONF_CONFIG_SOURCE'] = 'xml:merged:/etc/gconf/gconf.xml.defaults' operation = "--makefile-uninstall-rule" if remove else "--makefile-install-rule" cmd = "/usr/bin/gconftool-2 %s %s" % (operation, " ".join(schemaList)) os.system (cmd) def setupPackage (metapath, filepath): updateGConf (filepath) def postCleanupPackage (metapath, filepath): updateGConf (filepath)
path = xmlfile.getTagData ("Path") # Only interested in /etc/gconf/schemas if "etc/gconf/schemas" in path: schemaList.append ("/%s" % path)
conditional_block
http.js
/** * @namespace http * * The C<http> namespace groups functions and classes used while making * HTTP Requests. * */ ECMAScript.Extend('http', function (ecma) { // Intentionally private var _documentLocation = null function _getDocumentLocation ()
/** * @constant HTTP_STATUS_NAMES * HTTP/1.1 Status Code Definitions * * Taken from, RFC 2616 Section 10: * L<http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html> * * These names are used in conjuction with L<ecma.http.Request> for * indicating callback functions. The name is prepended with C<on> such * that * onMethodNotAllowed * corresponds to the callback triggered when a 405 status is received. * # Names * * 100 Continue * 101 SwitchingProtocols * 200 Ok * 201 Created * 202 Accepted * 203 NonAuthoritativeInformation * 204 NoContent * 205 ResetContent * 206 PartialContent * 300 MultipleChoices * 301 MovedPermanently * 302 Found * 303 SeeOther * 304 NotModified * 305 UseProxy * 306 Unused * 307 TemporaryRedirect * 400 BadRequest * 401 Unauthorized * 402 PaymentRequired * 403 Forbidden * 404 NotFound * 405 MethodNotAllowed * 406 NotAcceptable * 407 ProxyAuthenticationRequired * 408 RequestTimeout * 409 Conflict * 410 Gone * 411 LengthRequired * 412 PreconditionFailed * 413 RequestEntityTooLarge * 414 RequestURITooLong * 415 UnsupportedMediaType * 416 RequestedRangeNotSatisfiable * 417 ExpectationFailed * 500 InternalServerError * 501 NotImplemented * 502 BadGateway * 503 ServiceUnavailable * 504 GatewayTimeout * 505 HTTPVersionNotSupported */ this.HTTP_STATUS_NAMES = { 100: 'Continue', 101: 'SwitchingProtocols', 200: 'Ok', 201: 'Created', 202: 'Accepted', 203: 'NonAuthoritativeInformation', 204: 'NoContent', 205: 'ResetContent', 206: 'PartialContent', 300: 'MultipleChoices', 301: 'MovedPermanently', 302: 'Found', 303: 'SeeOther', 304: 'NotModified', 305: 'UseProxy', 306: 'Unused', 307: 'TemporaryRedirect', 400: 'BadRequest', 401: 'Unauthorized', 402: 'PaymentRequired', 403: 'Forbidden', 404: 'NotFound', 405: 'MethodNotAllowed', 406: 'NotAcceptable', 407: 'ProxyAuthenticationRequired', 408: 'RequestTimeout', 409: 'Conflict', 410: 'Gone', 411: 'LengthRequired', 412: 'PreconditionFailed', 413: 'RequestEntityTooLarge', 414: 'RequestURITooLong', 415: 'UnsupportedMediaType', 416: 'RequestedRangeNotSatisfiable', 417: 'ExpectationFailed', 500: 'InternalServerError', 501: 'NotImplemented', 502: 'BadGateway', 503: 'ServiceUnavailable', 504: 'GatewayTimeout', 505: 'HTTPVersionNotSupported' }; /** * @function isSameOrigin * * Compare originating servers. * * var bool = ecma.http.isSameOrigin(uri); * var bool = ecma.http.isSameOrigin(uri, uri); * * Is the resource located on the server at the port using the same protocol * which served the document. * * var bool = ecma.http.isSameOrigin('http://www.example.com'); * * Are the two URI's served from the same origin * * var bool = ecma.http.isSameOrigin('http://www.example.com', 'https://www.example.com'); * */ this.isSameOrigin = function(uri1, uri2) { if (!(uri1)) return false; var loc1 = uri1 instanceof ecma.http.Location ? uri1 : new ecma.http.Location(uri1); var loc2 = uri2 || _getDocumentLocation(); return loc1.isSameOrigin(loc2); }; });
{ if (!_documentLocation) _documentLocation = new ecma.http.Location(); return _documentLocation; }
identifier_body
http.js
/** * @namespace http * * The C<http> namespace groups functions and classes used while making * HTTP Requests. * */ ECMAScript.Extend('http', function (ecma) { // Intentionally private var _documentLocation = null function
() { if (!_documentLocation) _documentLocation = new ecma.http.Location(); return _documentLocation; } /** * @constant HTTP_STATUS_NAMES * HTTP/1.1 Status Code Definitions * * Taken from, RFC 2616 Section 10: * L<http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html> * * These names are used in conjuction with L<ecma.http.Request> for * indicating callback functions. The name is prepended with C<on> such * that * onMethodNotAllowed * corresponds to the callback triggered when a 405 status is received. * # Names * * 100 Continue * 101 SwitchingProtocols * 200 Ok * 201 Created * 202 Accepted * 203 NonAuthoritativeInformation * 204 NoContent * 205 ResetContent * 206 PartialContent * 300 MultipleChoices * 301 MovedPermanently * 302 Found * 303 SeeOther * 304 NotModified * 305 UseProxy * 306 Unused * 307 TemporaryRedirect * 400 BadRequest * 401 Unauthorized * 402 PaymentRequired * 403 Forbidden * 404 NotFound * 405 MethodNotAllowed * 406 NotAcceptable * 407 ProxyAuthenticationRequired * 408 RequestTimeout * 409 Conflict * 410 Gone * 411 LengthRequired * 412 PreconditionFailed * 413 RequestEntityTooLarge * 414 RequestURITooLong * 415 UnsupportedMediaType * 416 RequestedRangeNotSatisfiable * 417 ExpectationFailed * 500 InternalServerError * 501 NotImplemented * 502 BadGateway * 503 ServiceUnavailable * 504 GatewayTimeout * 505 HTTPVersionNotSupported */ this.HTTP_STATUS_NAMES = { 100: 'Continue', 101: 'SwitchingProtocols', 200: 'Ok', 201: 'Created', 202: 'Accepted', 203: 'NonAuthoritativeInformation', 204: 'NoContent', 205: 'ResetContent', 206: 'PartialContent', 300: 'MultipleChoices', 301: 'MovedPermanently', 302: 'Found', 303: 'SeeOther', 304: 'NotModified', 305: 'UseProxy', 306: 'Unused', 307: 'TemporaryRedirect', 400: 'BadRequest', 401: 'Unauthorized', 402: 'PaymentRequired', 403: 'Forbidden', 404: 'NotFound', 405: 'MethodNotAllowed', 406: 'NotAcceptable', 407: 'ProxyAuthenticationRequired', 408: 'RequestTimeout', 409: 'Conflict', 410: 'Gone', 411: 'LengthRequired', 412: 'PreconditionFailed', 413: 'RequestEntityTooLarge', 414: 'RequestURITooLong', 415: 'UnsupportedMediaType', 416: 'RequestedRangeNotSatisfiable', 417: 'ExpectationFailed', 500: 'InternalServerError', 501: 'NotImplemented', 502: 'BadGateway', 503: 'ServiceUnavailable', 504: 'GatewayTimeout', 505: 'HTTPVersionNotSupported' }; /** * @function isSameOrigin * * Compare originating servers. * * var bool = ecma.http.isSameOrigin(uri); * var bool = ecma.http.isSameOrigin(uri, uri); * * Is the resource located on the server at the port using the same protocol * which served the document. * * var bool = ecma.http.isSameOrigin('http://www.example.com'); * * Are the two URI's served from the same origin * * var bool = ecma.http.isSameOrigin('http://www.example.com', 'https://www.example.com'); * */ this.isSameOrigin = function(uri1, uri2) { if (!(uri1)) return false; var loc1 = uri1 instanceof ecma.http.Location ? uri1 : new ecma.http.Location(uri1); var loc2 = uri2 || _getDocumentLocation(); return loc1.isSameOrigin(loc2); }; });
_getDocumentLocation
identifier_name
http.js
/** * @namespace http * * The C<http> namespace groups functions and classes used while making * HTTP Requests. * */ ECMAScript.Extend('http', function (ecma) { // Intentionally private var _documentLocation = null function _getDocumentLocation () { if (!_documentLocation) _documentLocation = new ecma.http.Location(); return _documentLocation; } /** * @constant HTTP_STATUS_NAMES * HTTP/1.1 Status Code Definitions * * Taken from, RFC 2616 Section 10: * L<http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html> * * These names are used in conjuction with L<ecma.http.Request> for * indicating callback functions. The name is prepended with C<on> such * that * onMethodNotAllowed * corresponds to the callback triggered when a 405 status is received. * # Names * * 100 Continue * 101 SwitchingProtocols * 200 Ok * 201 Created * 202 Accepted * 203 NonAuthoritativeInformation * 204 NoContent * 205 ResetContent * 206 PartialContent * 300 MultipleChoices * 301 MovedPermanently * 302 Found * 303 SeeOther * 304 NotModified * 305 UseProxy * 306 Unused * 307 TemporaryRedirect * 400 BadRequest * 401 Unauthorized * 402 PaymentRequired * 403 Forbidden * 404 NotFound * 405 MethodNotAllowed * 406 NotAcceptable * 407 ProxyAuthenticationRequired * 408 RequestTimeout * 409 Conflict * 410 Gone * 411 LengthRequired * 412 PreconditionFailed * 413 RequestEntityTooLarge * 414 RequestURITooLong * 415 UnsupportedMediaType * 416 RequestedRangeNotSatisfiable * 417 ExpectationFailed * 500 InternalServerError * 501 NotImplemented * 502 BadGateway * 503 ServiceUnavailable * 504 GatewayTimeout * 505 HTTPVersionNotSupported */ this.HTTP_STATUS_NAMES = { 100: 'Continue', 101: 'SwitchingProtocols', 200: 'Ok', 201: 'Created', 202: 'Accepted', 203: 'NonAuthoritativeInformation', 204: 'NoContent', 205: 'ResetContent', 206: 'PartialContent', 300: 'MultipleChoices', 301: 'MovedPermanently', 302: 'Found', 303: 'SeeOther', 304: 'NotModified', 305: 'UseProxy', 306: 'Unused', 307: 'TemporaryRedirect', 400: 'BadRequest', 401: 'Unauthorized', 402: 'PaymentRequired', 403: 'Forbidden', 404: 'NotFound', 405: 'MethodNotAllowed', 406: 'NotAcceptable', 407: 'ProxyAuthenticationRequired', 408: 'RequestTimeout', 409: 'Conflict', 410: 'Gone', 411: 'LengthRequired', 412: 'PreconditionFailed', 413: 'RequestEntityTooLarge', 414: 'RequestURITooLong', 415: 'UnsupportedMediaType', 416: 'RequestedRangeNotSatisfiable', 417: 'ExpectationFailed', 500: 'InternalServerError',
505: 'HTTPVersionNotSupported' }; /** * @function isSameOrigin * * Compare originating servers. * * var bool = ecma.http.isSameOrigin(uri); * var bool = ecma.http.isSameOrigin(uri, uri); * * Is the resource located on the server at the port using the same protocol * which served the document. * * var bool = ecma.http.isSameOrigin('http://www.example.com'); * * Are the two URI's served from the same origin * * var bool = ecma.http.isSameOrigin('http://www.example.com', 'https://www.example.com'); * */ this.isSameOrigin = function(uri1, uri2) { if (!(uri1)) return false; var loc1 = uri1 instanceof ecma.http.Location ? uri1 : new ecma.http.Location(uri1); var loc2 = uri2 || _getDocumentLocation(); return loc1.isSameOrigin(loc2); }; });
501: 'NotImplemented', 502: 'BadGateway', 503: 'ServiceUnavailable', 504: 'GatewayTimeout',
random_line_split
index.js
import React from 'react' import {HOC, Link} from 'cerebral-view-react' import PageProgress from '../PageProgress' // View class AutoReload extends React.Component { constructor (props) { super(props) this.state = { secondsElapsed: 0 } this.onInterval = this.onInterval.bind(this) } componentWillMount () { this.intervals = [] } componentWillUnmount () { this.intervals.forEach(clearInterval) } componentDidMount () { this.setInterval(this.onInterval, 1000) } setInterval () { this.intervals.push(setInterval.apply(null, arguments)) } onInterval () { let secondsElapsed = 0 if (this.props.isEnabled) { secondsElapsed = this.state.secondsElapsed + 1 if (secondsElapsed >= this.props.triggerAfterSeconds) { this.trigger() secondsElapsed = 0 } } if (secondsElapsed !== this.state.secondsElapsed) { this.setState({ secondsElapsed: secondsElapsed }) } } trigger () { this.props.triggers.map((trigger) => trigger()) } triggerNow (e) { if (e) { e.preventDefault() } if (this.props.isEnabled) { if (this.state.secondsElapsed > 0) { this.trigger() this.setState({ secondsElapsed: 0 }) } } } render () { const signals = this.props.signals const progress = { isEnabled: this.props.isEnabled, elapsed: this.state.secondsElapsed, total: this.props.triggerAfterSeconds } return ( <div> <PageProgress {...progress} /> <hr /> <pre> BastardAutoloaderFromHell<br /> =========================<br />
secondsElapsed: {this.state.secondsElapsed}<br /> secondsBeforeReload: {this.props.triggerAfterSeconds - this.state.secondsElapsed}<br /> -------------------------<br /> <Link signal={signals.app.reload.reloadingDisabled}>clickmeto_<b>disable</b>_reloading</Link><br /> --<br /> <Link signal={signals.app.reload.reloadingEnabled}>clickmeto_<b>enable</b>_reloading</Link><br /> --<br /> <Link signal={signals.app.reload.reloadingToggled}>clickmeto_<b>toggle</b>_reloading</Link><br /> -------------------------<br /> <a onClick={(e) => this.triggerNow(e)}>clickmeto_<b>trigger_NOW</b></a><br /> -------------------------<br /> <Link signal={signals.app.reload.triggerIntervalChanged} params={{interval: 10}}>clickmeto_reload_@<b>10_seconds</b></Link><br /> --<br /> <Link signal={signals.app.reload.triggerIntervalChanged} params={{interval: 20}}>clickmeto_reload_@<b>20_seconds</b></Link><br /> --<br /> <Link signal={signals.app.reload.triggerIntervalChanged} params={{interval: 30}}>clickmeto_reload_@<b>30_seconds</b></Link><br /> --<br /> <Link signal={signals.app.reload.triggerIntervalChanged} params={{interval: 60}}>clickmeto_reload_@<b>60_seconds</b></Link><br /> ====<br /> <i>designed by pbit</i> </pre> </div> ) } } // Model AutoReload.propTypes = { isEnabled: React.PropTypes.bool, triggerAfterSeconds: React.PropTypes.number, signals: React.PropTypes.object, triggers: React.PropTypes.array } AutoReload.defaultProps = { triggers: [] } // Binding const StatefullAutoReload = HOC(AutoReload, { isEnabled: ['app', 'reload', 'isEnabled'], triggerAfterSeconds: ['app', 'reload', 'triggerAfterSeconds'] }) // API export default StatefullAutoReload
[{'='.repeat(this.state.secondsElapsed)}{'.'.repeat(this.props.triggerAfterSeconds - this.state.secondsElapsed - 1)}]<br /> isEnabled: {this.props.isEnabled ? 'yepp' : 'nope'}<br /> triggerAfterSeconds: {this.props.triggerAfterSeconds}<br /> numberOfTriggers: {this.props.triggers.length}<br />
random_line_split
index.js
import React from 'react' import {HOC, Link} from 'cerebral-view-react' import PageProgress from '../PageProgress' // View class AutoReload extends React.Component { constructor (props) { super(props) this.state = { secondsElapsed: 0 } this.onInterval = this.onInterval.bind(this) } componentWillMount () { this.intervals = [] } componentWillUnmount () { this.intervals.forEach(clearInterval) } componentDidMount () { this.setInterval(this.onInterval, 1000) } setInterval () { this.intervals.push(setInterval.apply(null, arguments)) } onInterval () { let secondsElapsed = 0 if (this.props.isEnabled) { secondsElapsed = this.state.secondsElapsed + 1 if (secondsElapsed >= this.props.triggerAfterSeconds)
} if (secondsElapsed !== this.state.secondsElapsed) { this.setState({ secondsElapsed: secondsElapsed }) } } trigger () { this.props.triggers.map((trigger) => trigger()) } triggerNow (e) { if (e) { e.preventDefault() } if (this.props.isEnabled) { if (this.state.secondsElapsed > 0) { this.trigger() this.setState({ secondsElapsed: 0 }) } } } render () { const signals = this.props.signals const progress = { isEnabled: this.props.isEnabled, elapsed: this.state.secondsElapsed, total: this.props.triggerAfterSeconds } return ( <div> <PageProgress {...progress} /> <hr /> <pre> BastardAutoloaderFromHell<br /> =========================<br /> [{'='.repeat(this.state.secondsElapsed)}{'.'.repeat(this.props.triggerAfterSeconds - this.state.secondsElapsed - 1)}]<br /> isEnabled: {this.props.isEnabled ? 'yepp' : 'nope'}<br /> triggerAfterSeconds: {this.props.triggerAfterSeconds}<br /> numberOfTriggers: {this.props.triggers.length}<br /> secondsElapsed: {this.state.secondsElapsed}<br /> secondsBeforeReload: {this.props.triggerAfterSeconds - this.state.secondsElapsed}<br /> -------------------------<br /> <Link signal={signals.app.reload.reloadingDisabled}>clickmeto_<b>disable</b>_reloading</Link><br /> --<br /> <Link signal={signals.app.reload.reloadingEnabled}>clickmeto_<b>enable</b>_reloading</Link><br /> --<br /> <Link signal={signals.app.reload.reloadingToggled}>clickmeto_<b>toggle</b>_reloading</Link><br /> -------------------------<br /> <a onClick={(e) => this.triggerNow(e)}>clickmeto_<b>trigger_NOW</b></a><br /> -------------------------<br /> <Link signal={signals.app.reload.triggerIntervalChanged} params={{interval: 10}}>clickmeto_reload_@<b>10_seconds</b></Link><br /> --<br /> <Link signal={signals.app.reload.triggerIntervalChanged} params={{interval: 20}}>clickmeto_reload_@<b>20_seconds</b></Link><br /> --<br /> <Link signal={signals.app.reload.triggerIntervalChanged} params={{interval: 30}}>clickmeto_reload_@<b>30_seconds</b></Link><br /> --<br /> <Link signal={signals.app.reload.triggerIntervalChanged} params={{interval: 60}}>clickmeto_reload_@<b>60_seconds</b></Link><br /> ====<br /> <i>designed by pbit</i> </pre> </div> ) } } // Model AutoReload.propTypes = { isEnabled: React.PropTypes.bool, triggerAfterSeconds: React.PropTypes.number, signals: React.PropTypes.object, triggers: React.PropTypes.array } AutoReload.defaultProps = { triggers: [] } // Binding const StatefullAutoReload = HOC(AutoReload, { isEnabled: ['app', 'reload', 'isEnabled'], triggerAfterSeconds: ['app', 'reload', 'triggerAfterSeconds'] }) // API export default StatefullAutoReload
{ this.trigger() secondsElapsed = 0 }
conditional_block
index.js
import React from 'react' import {HOC, Link} from 'cerebral-view-react' import PageProgress from '../PageProgress' // View class AutoReload extends React.Component { constructor (props) { super(props) this.state = { secondsElapsed: 0 } this.onInterval = this.onInterval.bind(this) } componentWillMount () { this.intervals = [] } componentWillUnmount () { this.intervals.forEach(clearInterval) } componentDidMount () { this.setInterval(this.onInterval, 1000) } setInterval () { this.intervals.push(setInterval.apply(null, arguments)) } onInterval () { let secondsElapsed = 0 if (this.props.isEnabled) { secondsElapsed = this.state.secondsElapsed + 1 if (secondsElapsed >= this.props.triggerAfterSeconds) { this.trigger() secondsElapsed = 0 } } if (secondsElapsed !== this.state.secondsElapsed) { this.setState({ secondsElapsed: secondsElapsed }) } } trigger () { this.props.triggers.map((trigger) => trigger()) } triggerNow (e) { if (e) { e.preventDefault() } if (this.props.isEnabled) { if (this.state.secondsElapsed > 0) { this.trigger() this.setState({ secondsElapsed: 0 }) } } } render ()
} // Model AutoReload.propTypes = { isEnabled: React.PropTypes.bool, triggerAfterSeconds: React.PropTypes.number, signals: React.PropTypes.object, triggers: React.PropTypes.array } AutoReload.defaultProps = { triggers: [] } // Binding const StatefullAutoReload = HOC(AutoReload, { isEnabled: ['app', 'reload', 'isEnabled'], triggerAfterSeconds: ['app', 'reload', 'triggerAfterSeconds'] }) // API export default StatefullAutoReload
{ const signals = this.props.signals const progress = { isEnabled: this.props.isEnabled, elapsed: this.state.secondsElapsed, total: this.props.triggerAfterSeconds } return ( <div> <PageProgress {...progress} /> <hr /> <pre> BastardAutoloaderFromHell<br /> =========================<br /> [{'='.repeat(this.state.secondsElapsed)}{'.'.repeat(this.props.triggerAfterSeconds - this.state.secondsElapsed - 1)}]<br /> isEnabled: {this.props.isEnabled ? 'yepp' : 'nope'}<br /> triggerAfterSeconds: {this.props.triggerAfterSeconds}<br /> numberOfTriggers: {this.props.triggers.length}<br /> secondsElapsed: {this.state.secondsElapsed}<br /> secondsBeforeReload: {this.props.triggerAfterSeconds - this.state.secondsElapsed}<br /> -------------------------<br /> <Link signal={signals.app.reload.reloadingDisabled}>clickmeto_<b>disable</b>_reloading</Link><br /> --<br /> <Link signal={signals.app.reload.reloadingEnabled}>clickmeto_<b>enable</b>_reloading</Link><br /> --<br /> <Link signal={signals.app.reload.reloadingToggled}>clickmeto_<b>toggle</b>_reloading</Link><br /> -------------------------<br /> <a onClick={(e) => this.triggerNow(e)}>clickmeto_<b>trigger_NOW</b></a><br /> -------------------------<br /> <Link signal={signals.app.reload.triggerIntervalChanged} params={{interval: 10}}>clickmeto_reload_@<b>10_seconds</b></Link><br /> --<br /> <Link signal={signals.app.reload.triggerIntervalChanged} params={{interval: 20}}>clickmeto_reload_@<b>20_seconds</b></Link><br /> --<br /> <Link signal={signals.app.reload.triggerIntervalChanged} params={{interval: 30}}>clickmeto_reload_@<b>30_seconds</b></Link><br /> --<br /> <Link signal={signals.app.reload.triggerIntervalChanged} params={{interval: 60}}>clickmeto_reload_@<b>60_seconds</b></Link><br /> ====<br /> <i>designed by pbit</i> </pre> </div> ) }
identifier_body
index.js
import React from 'react' import {HOC, Link} from 'cerebral-view-react' import PageProgress from '../PageProgress' // View class
extends React.Component { constructor (props) { super(props) this.state = { secondsElapsed: 0 } this.onInterval = this.onInterval.bind(this) } componentWillMount () { this.intervals = [] } componentWillUnmount () { this.intervals.forEach(clearInterval) } componentDidMount () { this.setInterval(this.onInterval, 1000) } setInterval () { this.intervals.push(setInterval.apply(null, arguments)) } onInterval () { let secondsElapsed = 0 if (this.props.isEnabled) { secondsElapsed = this.state.secondsElapsed + 1 if (secondsElapsed >= this.props.triggerAfterSeconds) { this.trigger() secondsElapsed = 0 } } if (secondsElapsed !== this.state.secondsElapsed) { this.setState({ secondsElapsed: secondsElapsed }) } } trigger () { this.props.triggers.map((trigger) => trigger()) } triggerNow (e) { if (e) { e.preventDefault() } if (this.props.isEnabled) { if (this.state.secondsElapsed > 0) { this.trigger() this.setState({ secondsElapsed: 0 }) } } } render () { const signals = this.props.signals const progress = { isEnabled: this.props.isEnabled, elapsed: this.state.secondsElapsed, total: this.props.triggerAfterSeconds } return ( <div> <PageProgress {...progress} /> <hr /> <pre> BastardAutoloaderFromHell<br /> =========================<br /> [{'='.repeat(this.state.secondsElapsed)}{'.'.repeat(this.props.triggerAfterSeconds - this.state.secondsElapsed - 1)}]<br /> isEnabled: {this.props.isEnabled ? 'yepp' : 'nope'}<br /> triggerAfterSeconds: {this.props.triggerAfterSeconds}<br /> numberOfTriggers: {this.props.triggers.length}<br /> secondsElapsed: {this.state.secondsElapsed}<br /> secondsBeforeReload: {this.props.triggerAfterSeconds - this.state.secondsElapsed}<br /> -------------------------<br /> <Link signal={signals.app.reload.reloadingDisabled}>clickmeto_<b>disable</b>_reloading</Link><br /> --<br /> <Link signal={signals.app.reload.reloadingEnabled}>clickmeto_<b>enable</b>_reloading</Link><br /> --<br /> <Link signal={signals.app.reload.reloadingToggled}>clickmeto_<b>toggle</b>_reloading</Link><br /> -------------------------<br /> <a onClick={(e) => this.triggerNow(e)}>clickmeto_<b>trigger_NOW</b></a><br /> -------------------------<br /> <Link signal={signals.app.reload.triggerIntervalChanged} params={{interval: 10}}>clickmeto_reload_@<b>10_seconds</b></Link><br /> --<br /> <Link signal={signals.app.reload.triggerIntervalChanged} params={{interval: 20}}>clickmeto_reload_@<b>20_seconds</b></Link><br /> --<br /> <Link signal={signals.app.reload.triggerIntervalChanged} params={{interval: 30}}>clickmeto_reload_@<b>30_seconds</b></Link><br /> --<br /> <Link signal={signals.app.reload.triggerIntervalChanged} params={{interval: 60}}>clickmeto_reload_@<b>60_seconds</b></Link><br /> ====<br /> <i>designed by pbit</i> </pre> </div> ) } } // Model AutoReload.propTypes = { isEnabled: React.PropTypes.bool, triggerAfterSeconds: React.PropTypes.number, signals: React.PropTypes.object, triggers: React.PropTypes.array } AutoReload.defaultProps = { triggers: [] } // Binding const StatefullAutoReload = HOC(AutoReload, { isEnabled: ['app', 'reload', 'isEnabled'], triggerAfterSeconds: ['app', 'reload', 'triggerAfterSeconds'] }) // API export default StatefullAutoReload
AutoReload
identifier_name
doctor_attentions_diseases_inherit.py
# -*- coding: utf-8 -*- # ############################################################################# # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from dateutil.relativedelta import * from datetime import datetime, date from openerp.osv import fields, osv from openerp.tools.translate import _ import logging _logger = logging.getLogger(__name__) class doctor_attentions_diseases(osv.osv):
r_attentions_diseases()
_name = "doctor.attentions.diseases" _inherit = 'doctor.attentions.diseases' _columns = { } def _check_main_disease(self, cr, uid, ids, context=None): ''' verify there's only one main disease ''' for r in self.browse(cr, uid, ids, context=context): diseases_ids = self.search(cr,uid,[('attentiont_id','=',r.attentiont_id.id),('diseases_type','=','main')]) if len(diseases_ids) > 1: return False return True def _check_duplicated_disease(self, cr, uid, ids, context=None): ''' verify duplicated disease ''' for r in self.browse(cr, uid, ids, context=context): diseases_ids = self.search(cr,uid,[('attentiont_id','=',r.attentiont_id.id),('diseases_id','=',r.diseases_id.id)]) if len(diseases_ids) > 1: return False return True _constraints = [ #(_check_main_disease, u'Hay más de un diagnóstico seleccionado como Principal. Por favor seleccione uno como Principal y los demás como Relacionados.', [u'\n\nTipo de Diagnóstico\n\n']), #(_check_duplicated_disease, u'Hay uno o más diagnósticos duplicados.', [u'\n\nDiagnósticos\n\n']) ] docto
identifier_body
doctor_attentions_diseases_inherit.py
# -*- coding: utf-8 -*- # ############################################################################# # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from dateutil.relativedelta import * from datetime import datetime, date from openerp.osv import fields, osv from openerp.tools.translate import _ import logging _logger = logging.getLogger(__name__) class doctor_attentions_diseases(osv.osv): _name = "doctor.attentions.diseases" _inherit = 'doctor.attentions.diseases' _columns = { } def _check_main_disease(self, cr, uid, ids, context=None): ''' verify there's only one main disease ''' for r in self.browse(cr, uid, ids, context=context): diseases_ids = self.search(cr,uid,[('attentiont_id','=',r.attentiont_id.id),('diseases_type','=','main')]) if len(diseases_ids) > 1:
return True def _check_duplicated_disease(self, cr, uid, ids, context=None): ''' verify duplicated disease ''' for r in self.browse(cr, uid, ids, context=context): diseases_ids = self.search(cr,uid,[('attentiont_id','=',r.attentiont_id.id),('diseases_id','=',r.diseases_id.id)]) if len(diseases_ids) > 1: return False return True _constraints = [ #(_check_main_disease, u'Hay más de un diagnóstico seleccionado como Principal. Por favor seleccione uno como Principal y los demás como Relacionados.', [u'\n\nTipo de Diagnóstico\n\n']), #(_check_duplicated_disease, u'Hay uno o más diagnósticos duplicados.', [u'\n\nDiagnósticos\n\n']) ] doctor_attentions_diseases()
return False
conditional_block
doctor_attentions_diseases_inherit.py
# -*- coding: utf-8 -*- # ############################################################################# # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from dateutil.relativedelta import * from datetime import datetime, date from openerp.osv import fields, osv from openerp.tools.translate import _ import logging _logger = logging.getLogger(__name__) class doctor_attentions_diseases(osv.osv): _name = "doctor.attentions.diseases" _inherit = 'doctor.attentions.diseases' _columns = { } def
(self, cr, uid, ids, context=None): ''' verify there's only one main disease ''' for r in self.browse(cr, uid, ids, context=context): diseases_ids = self.search(cr,uid,[('attentiont_id','=',r.attentiont_id.id),('diseases_type','=','main')]) if len(diseases_ids) > 1: return False return True def _check_duplicated_disease(self, cr, uid, ids, context=None): ''' verify duplicated disease ''' for r in self.browse(cr, uid, ids, context=context): diseases_ids = self.search(cr,uid,[('attentiont_id','=',r.attentiont_id.id),('diseases_id','=',r.diseases_id.id)]) if len(diseases_ids) > 1: return False return True _constraints = [ #(_check_main_disease, u'Hay más de un diagnóstico seleccionado como Principal. Por favor seleccione uno como Principal y los demás como Relacionados.', [u'\n\nTipo de Diagnóstico\n\n']), #(_check_duplicated_disease, u'Hay uno o más diagnósticos duplicados.', [u'\n\nDiagnósticos\n\n']) ] doctor_attentions_diseases()
_check_main_disease
identifier_name
doctor_attentions_diseases_inherit.py
# -*- coding: utf-8 -*- # ############################################################################# # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from dateutil.relativedelta import * from datetime import datetime, date from openerp.osv import fields, osv from openerp.tools.translate import _ import logging _logger = logging.getLogger(__name__) class doctor_attentions_diseases(osv.osv): _name = "doctor.attentions.diseases" _inherit = 'doctor.attentions.diseases' _columns = { } def _check_main_disease(self, cr, uid, ids, context=None): ''' verify there's only one main disease ''' for r in self.browse(cr, uid, ids, context=context): diseases_ids = self.search(cr,uid,[('attentiont_id','=',r.attentiont_id.id),('diseases_type','=','main')])
if len(diseases_ids) > 1: return False return True def _check_duplicated_disease(self, cr, uid, ids, context=None): ''' verify duplicated disease ''' for r in self.browse(cr, uid, ids, context=context): diseases_ids = self.search(cr,uid,[('attentiont_id','=',r.attentiont_id.id),('diseases_id','=',r.diseases_id.id)]) if len(diseases_ids) > 1: return False return True _constraints = [ #(_check_main_disease, u'Hay más de un diagnóstico seleccionado como Principal. Por favor seleccione uno como Principal y los demás como Relacionados.', [u'\n\nTipo de Diagnóstico\n\n']), #(_check_duplicated_disease, u'Hay uno o más diagnósticos duplicados.', [u'\n\nDiagnósticos\n\n']) ] doctor_attentions_diseases()
random_line_split
util.rs
use std::str; use nom::{self, InputLength, IResult, Needed}; pub fn fixed_length_ascii(input: &[u8], len: usize) -> IResult<&[u8], &str> { if input.len() < len { return Err(nom::Err::Incomplete(Needed::Size(len)));
for i in 0..len { match input[i] { 0 => { // This is the end let s = unsafe { str::from_utf8_unchecked(&input[..i]) }; return Ok((&input[len..], s)); } 32 ... 126 => { // OK } _ => { // Totally bogus character return Err(nom::Err::Error(nom::Context::Code(&input[i..], nom::ErrorKind::Custom(0)))); } } } Ok((&input[len..], unsafe { str::from_utf8_unchecked(&input[..len]) })) } /// Like nom's eof!(), except it actually works on buffers -- which means it won't work on streams pub fn naive_eof(input: &[u8]) -> IResult<&[u8], ()> { if input.input_len() == 0 { Ok((input, ())) } else { Err(nom::Err::Error(error_position!(input, nom::ErrorKind::Eof::<u32>))) } }
}
random_line_split
util.rs
use std::str; use nom::{self, InputLength, IResult, Needed}; pub fn fixed_length_ascii(input: &[u8], len: usize) -> IResult<&[u8], &str> { if input.len() < len { return Err(nom::Err::Incomplete(Needed::Size(len))); } for i in 0..len { match input[i] { 0 => { // This is the end let s = unsafe { str::from_utf8_unchecked(&input[..i]) }; return Ok((&input[len..], s)); } 32 ... 126 =>
_ => { // Totally bogus character return Err(nom::Err::Error(nom::Context::Code(&input[i..], nom::ErrorKind::Custom(0)))); } } } Ok((&input[len..], unsafe { str::from_utf8_unchecked(&input[..len]) })) } /// Like nom's eof!(), except it actually works on buffers -- which means it won't work on streams pub fn naive_eof(input: &[u8]) -> IResult<&[u8], ()> { if input.input_len() == 0 { Ok((input, ())) } else { Err(nom::Err::Error(error_position!(input, nom::ErrorKind::Eof::<u32>))) } }
{ // OK }
conditional_block
util.rs
use std::str; use nom::{self, InputLength, IResult, Needed}; pub fn fixed_length_ascii(input: &[u8], len: usize) -> IResult<&[u8], &str>
/// Like nom's eof!(), except it actually works on buffers -- which means it won't work on streams pub fn naive_eof(input: &[u8]) -> IResult<&[u8], ()> { if input.input_len() == 0 { Ok((input, ())) } else { Err(nom::Err::Error(error_position!(input, nom::ErrorKind::Eof::<u32>))) } }
{ if input.len() < len { return Err(nom::Err::Incomplete(Needed::Size(len))); } for i in 0..len { match input[i] { 0 => { // This is the end let s = unsafe { str::from_utf8_unchecked(&input[..i]) }; return Ok((&input[len..], s)); } 32 ... 126 => { // OK } _ => { // Totally bogus character return Err(nom::Err::Error(nom::Context::Code(&input[i..], nom::ErrorKind::Custom(0)))); } } } Ok((&input[len..], unsafe { str::from_utf8_unchecked(&input[..len]) })) }
identifier_body
util.rs
use std::str; use nom::{self, InputLength, IResult, Needed}; pub fn fixed_length_ascii(input: &[u8], len: usize) -> IResult<&[u8], &str> { if input.len() < len { return Err(nom::Err::Incomplete(Needed::Size(len))); } for i in 0..len { match input[i] { 0 => { // This is the end let s = unsafe { str::from_utf8_unchecked(&input[..i]) }; return Ok((&input[len..], s)); } 32 ... 126 => { // OK } _ => { // Totally bogus character return Err(nom::Err::Error(nom::Context::Code(&input[i..], nom::ErrorKind::Custom(0)))); } } } Ok((&input[len..], unsafe { str::from_utf8_unchecked(&input[..len]) })) } /// Like nom's eof!(), except it actually works on buffers -- which means it won't work on streams pub fn
(input: &[u8]) -> IResult<&[u8], ()> { if input.input_len() == 0 { Ok((input, ())) } else { Err(nom::Err::Error(error_position!(input, nom::ErrorKind::Eof::<u32>))) } }
naive_eof
identifier_name
mod.rs
// Copyright 2020 The Exonum Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! All available `MerkleDB` indexes.
entry::Entry, group::Group, iter::{Entries, IndexIterator, Keys, Values}, key_set::KeySetIndex, list::ListIndex, map::MapIndex, proof_entry::ProofEntry, sparse_list::SparseListIndex, value_set::ValueSetIndex, }; mod entry; mod group; mod iter; mod key_set; mod list; mod map; mod proof_entry; pub mod proof_list; pub mod proof_map; mod sparse_list; mod value_set;
pub use self::{
random_line_split
methodManager.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Method Manager Provide the end user interface for method (geophysical) dependent modelling and inversion as well as data and model visualization. """ import numpy as np import pygimli as pg from pygimli.utils import prettyFloat as pf def fit(funct, data, err=None, **kwargs): """Generic function fitter. Fit data to a given function. TODO ---- * Dictionary support for funct to submit user data.. Parameters ---------- funct: callable Function with the first argmument as data space, e.g., x, t, f, Nr. .. Any following arguments are the parameters to be fit. Except if a verbose flag if used. data: iterable (float) Data values err: iterable (float) [None] Data error values in %/100. Default is 1% if None are given. Other Parameters ---------------- *dataSpace*: iterable Keyword argument of the data space of len(data). The name need to fit the first argument of funct. Returns ------- model: array Fitted model parameter. response: array Model response. Example ------- >>> import pygimli as pg >>> >>> func = lambda t, a, b: a*np.exp(b*t) >>> t = np.linspace(1, 2, 20) >>> data = func(t, 1.1, 2.2) >>> model, response = pg.frameworks.fit(func, data, t=t) >>> print(pg.core.round(model, 1e-5)) 2 [1.1, 2.2] >>> _ = pg.plt.plot(t, data, 'o', label='data') >>> _ = pg.plt.plot(t, response, label='response') >>> _ = pg.plt.legend() """ mgr = ParameterInversionManager(funct, **kwargs) model = mgr.invert(data, err, **kwargs) return model, mgr.fw.response # TG: harmonicFit does not really belong here as it is no curve fit # We should rather use a class Decomposition # Discuss .. rename to Framework or InversionFramework since he only manages # the union of Inversion/Modelling and RegionManager(later) class MethodManager(object): """General manager to maintenance a measurement method. Method Manager are the interface to end-user interaction and can be seen as simple but complete application classes which manage all tasks of geophysical data processing. The method manager holds one instance of a forward operator and an appropriate inversion framework to handle modelling and data inversion. Method Manager also helps with data import and export, handle measurement data error estimation as well as model and data visualization. Attributes ---------- verbose : bool Give verbose output. debug : bool Give debug output. fop : :py:mod:`pygimli.frameworks.Modelling` Forward Operator instance .. knows the physics. fop is initialized by :py:mod:`pygimli.manager.MethodManager.initForwardOperator` and calls a valid :py:mod:`pygimli.manager.MethodManager.createForwardOperator` method in any derived classes. inv : :py:mod:`pygimli.frameworks.Inversion`. Inversion framework instance .. knows the reconstruction approach. The attribute inv is initialized by default but can be changed overwriting :py:mod:`pygimli.manager.MethodManager.initInversionFramework` """ def __init__(self, fop=None, fw=None, data=None, **kwargs): """Constructor.""" self._fop = fop self._fw = fw # we hold our own copy of the data self._verbose = kwargs.pop('verbose', False) self._debug = kwargs.pop('debug', False) self.data = None if data is not None: if isinstance(data, str): self.load(data) else: self.data = data # The inversion framework self._initInversionFramework(verbose=self._verbose, debug=self._debug) # The forward operator is stored in self._fw self._initForwardOperator(verbose=self._verbose, **kwargs) # maybe obsolete self.figs = {} self.errIsAbsolute = False def __hash__(self): """Create a hash for Method Manager.""" return pg.utils.strHash(str(type(self))) ^ hash(self.fop) @property def verbose(self): return self._verbose @verbose.setter def verbose(self, v): self._verbose = v self.fw.verbose = self._verbose @property def debug(self): return self._debug @debug.setter def debug(self, v): self._debug = v self.fw.debug = self._debug @property def fw(self): return self._fw @property def fop(self): return self.fw.fop @property def inv(self): return self.fw @property def model(self): return self.fw.model def reinitForwardOperator(self, **kwargs): """Reinitialize the forward operator. Sometimes it can be useful to reinitialize the forward operator. Keyword arguments will be forwarded to 'self.createForwardOperator'. """ self._initForwardOperator(**kwargs) def _initForwardOperator(self, **kwargs): """Initialize or re-initialize the forward operator. Called once in the constructor to force the manager to create the necessary forward operator member. Can be recalled if you need to changed the mangers own forward operator object. If you want an own instance of a valid FOP call createForwardOperator. """ if self._fop is not None: fop = self._fop else: fop = self.createForwardOperator(**kwargs) if fop is None: pg.critical("It seems that createForwardOperator method " "does not return a valid forward operator.") if self.fw is not None: self.fw.reset() self.fw.setForwardOperator(fop) else: pg.critical("No inversion framework defined.") def createForwardOperator(self, **kwargs): """Mandatory interface for derived classes. Here you need to specify which kind of forward operator FOP you want to use. This is called by any initForwardOperator() call. Parameters ---------- **kwargs Any arguments that are necessary for your FOP creation. Returns ------- Modelling Instance of any kind of :py:mod:`pygimli.framework.Modelling`. """ pg.critical("No forward operator defined, either give one or " "overwrite in derived class") def _initInversionFramework(self, **kwargs): """Initialize or re-initialize the inversion framework. Called once in the constructor to force the manager to create the necessary Framework instance. """ self._fw = self.createInversionFramework(**kwargs) if self.fw is None: pg.critical("createInversionFramework does not return " "valid inversion framework.") def createInversionFramework(self, **kwargs): """Create default Inversion framework. Derived classes may overwrite this method. Parameters ---------- **kwargs Any arguments that are necessary for your creation. Returns ------- Inversion Instance of any kind of :py:mod:`pygimli.framework.Inversion`. """ if self._fw is None: return pg.frameworks.Inversion(**kwargs) else: return self._fw def load(self, fileName): """API, overwrite in derived classes.""" pg.critical('API, overwrite in derived classes', fileName) def estimateError(self, data, errLevel=0.01, absError=None): # TODO check, rel or abs in return. """Estimate data error. Create an error of estimated measurement error. On default it returns an array of constant relative errors. More sophisticated error estimation should be done in specialized derived classes. Parameters ---------- data : iterable Data values for which the errors should be estimated. errLevel : float (0.01) Error level in percent/100 (i.e., 3% = 0.03). absError : float (None) Absolute error in the unit of the data. Returns ------- err : array Returning array of size len(data) """ if absError is not None: return absError + data * errLevel return np.ones(len(data)) * errLevel def simulate(self, model, **kwargs): # """Run a simulation aka the forward task.""" ra = self.fop.response(par=model) noiseLevel = kwargs.pop('noiseLevel', 0.0) if noiseLevel > 0: err = self.estimateError(ra, errLevel=noiseLevel) ra *= 1. + pg.randn(ra.size(), seed=kwargs.pop('seed', None)) * err return ra, err return ra def setData(self, data): """Set a data and distribute it to the forward operator""" self.data = data self.applyData(data) def applyData(self, data): """ """ self.fop.data = data def checkData(self, data): """Overwrite for special checks to return data values""" # if self._dataToken == 'nan': # pg.critical('self._dataToken nan, should be set in class', self) # return data(self._dataToken) return data def _ensureData(self, data): """Check data validity""" if data is None: data = self.fw.dataVals vals = self.checkData(data) if vals is None: pg.critical("There are no data values.") if abs(min(vals)) < 1e-12: print(min(vals), max(vals)) pg.critical("There are zero data values.") return vals def checkError(self, err, dataVals=None): """Return relative error. Default we assume 'err' are relative values. Overwrite is derived class if needed. """ if isinstance(err, pg.DataContainer): if not err.haveData('err'): pg.error('Datacontainer have no "err" values. ' 'Fallback set to 0.01') return err['err'] return err def _ensureError(self, err, dataVals=None): """Check error validity""" if err is None: err = self.fw.errorVals vals = self.checkError(err, dataVals) if vals is None: pg.warn('No data error given, set Fallback set to 1%') vals = np.ones(len(dataVals)) * 0.01 try: if min(vals) <= 0: pg.critical("All error values need to be larger then 0. Either" " give and err argument or fill dataContainer " " with a valid 'err' ", min(vals), max(vals)) except ValueError: pg.critical("Can't estimate data error") return vals def preRun(self, *args, **kwargs): """Called just before the inversion run starts.""" pass def postRun(self, *args, **kwargs): """Called just after the inversion run.""" pass def invert(self, data=None, err=None, **kwargs): """Invert the data. Invert the data by calling self.inv.run() with mandatory data and error values. TODO *need dataVals mandatory? what about already loaded data Parameters ---------- dataVals : iterable Data values to be inverted. errVals : iterable | float Error value for the given data. If errVals is float we assume this means to be a global relative error and force self.estimateError to be called. """ if data is not None: self.data = data else: data = self.data dataVals = self._ensureData(data) errVals = self._ensureError(err, dataVals) self.preRun(**kwargs) self.fw.run(dataVals, errVals, **kwargs) self.postRun(**kwargs) return self.fw.model def showModel(self, model, ax=None, **kwargs): """Show a model. Draw model into a given axes or show inversion result from last run. Forwards on default to the self.fop.drawModel function of the modelling operator. If there is no function given, you have to override this method. Parameters ---------- ax : mpl axes Axes object to draw into. Create a new if its not given. model : iterable Model data to be draw. Returns ------- ax, cbar """ if ax is None: fig, ax = pg.plt.subplots() ax, cBar = self.fop.drawModel(ax, model, **kwargs) return ax, cBar def showData(self, data=None, ax=None, **kwargs): """Show the data. Draw data values into a given axes or show the data values from the last run. Forwards on default to the self.fop.drawData function of the modelling operator. If there is no given function given, you have to override this method. Parameters ---------- ax : mpl axes Axes object to draw into. Create a new if its not given. data : iterable | pg.DataContainer Data values to be draw. Returns ------- ax, cbar """ if ax is None: fig, ax = pg.plt.subplots() if data is None: data = self.data return self.fop.drawData(ax, data, **kwargs), None def showResult(self, model=None, ax=None, **kwargs): """Show the last inversion result. TODO ---- DRY: decide showModel or showResult Parameters ---------- ax : mpl axes Axes object to draw into. Create a new if its not given. model : iterable [None] Model values to be draw. Default is self.model from the last run Returns ------- ax, cbar """ if model is None: model = self.model return self.showModel(model, ax=ax, **kwargs) def showFit(self, ax=None, **kwargs): """Show the last inversion data and response.""" ax, cBar = self.showData(data=self.inv.dataVals, error=self.inv.errorVals, label='Data', ax=ax, **kwargs) ax, cBar = self.showData(data=self.inv.response, label='Response', ax=ax, **kwargs) if not kwargs.pop('hideFittingAnnotation', False): fittext = r"rrms: {0}, $\chi^2$: {1}".format( pf(self.fw.inv.relrms()), pf(self.fw.inv.chi2())) ax.text(0.99, 0.005, fittext, transform=ax.transAxes, horizontalalignment='right', verticalalignment='bottom', fontsize=8) if not kwargs.pop('hideLegend', False): ax.legend() return ax, cBar def showResultAndFit(self, **kwargs): """Calls showResults and showFit.""" fig = pg.plt.figure() ax = fig.add_subplot(1, 2, 1) self.showResult(ax=ax, model=self.model, **kwargs) ax1 = fig.add_subplot(2, 2, 2) ax2 = fig.add_subplot(2, 2, 4) self.showFit(axs=[ax1, ax2], **kwargs) fig.tight_layout() return fig @staticmethod def createArgParser(dataSuffix='dat'): """Create default argument parser. TODO move this to some kind of app class Create default argument parser for the following options: -Q, --quiet -R, --robustData: options.robustData -B, --blockyModel: options.blockyModel -l, --lambda: options.lam -i, --maxIter: options.maxIter --depth: options.depth """ import argparse parser = argparse.ArgumentParser( description="usage: %prog [options] *." + dataSuffix) parser.add_argument("-Q", "--quiet", dest="quiet", action="store_true", default=False, help="Be verbose.") # parser.add_argument("-R", "--robustData", dest="robustData", # action="store_true", default=False, # help="Robust data (L1 norm) minimization.") # parser.add_argument("-B", "--blockyModel", dest="blockyModel", # action="store_true", default=False, # help="Blocky model (L1 norm) regularization.") parser.add_argument('-l', "--lambda", dest="lam", type=float, default=100, help="Regularization strength.") parser.add_argument('-i', "--maxIter", dest="maxIter", type=int, default=20, help="Maximum iteration count.") # parser.add_argument("--depth", dest="depth", type=float, # default=None, # help="Depth of inversion domain. [None=auto].") parser.add_argument('dataFileName') return parser class ParameterInversionManager(MethodManager): """Framework to invert unconstrained parameters.""" def __init__(self, funct=None, fop=None, **kwargs): """Constructor.""" if fop is not None: if not isinstance(fop, pg.frameworks.ParameterModelling): pg.critical("We need a fop if type ", pg.frameworks.ParameterModelling) elif funct is not None: fop = pg.frameworks.ParameterModelling(funct) else: pg.critical("you should either give a valid fop or a function so " "I can create the fop for you") super(ParameterInversionManager, self).__init__(fop, **kwargs) def createInversionFramework(self, **kwargs): """ """ return pg.frameworks.MarquardtInversion(**kwargs) def invert(self, data=None, err=None, **kwargs): """ Parameters ---------- limits: {str: [min, max]} Set limits for parameter by parameter name. startModel: {str: startModel} Set the start value for parameter by parameter name. """ dataSpace = kwargs.pop(self.fop.dataSpaceName, None) if dataSpace is not None: self.fop.dataSpace = dataSpace limits = kwargs.pop('limits', {}) for k, v in limits.items(): self.fop.setRegionProperties(k, limits=v) startModel = kwargs.pop('startModel', {}) if isinstance(startModel, dict): for k, v in startModel.items(): self.fop.setRegionProperties(k, startModel=v) else: kwargs['startModel'] = startModel return super(ParameterInversionManager, self).invert(data=data, err=err, **kwargs) class MethodManager1d(MethodManager): """Method Manager base class for managers on a 1d discretization.""" def __init__(self, fop=None, **kwargs): """Constructor.""" super(MethodManager1d, self).__init__(fop, **kwargs) def createInversionFramework(self, **kwargs): """ """ return pg.frameworks.Block1DInversion(**kwargs) def invert(self, data=None, err=None, **kwargs): """ """ return super(MethodManager1d, self).invert(data=data, err=err, **kwargs) class MeshMethodManager(MethodManager): def __init__(self, **kwargs): """Constructor. Attribute --------- mesh: pg.Mesh Copy of the main mesh to be distributed to inversion and the fop. You can overwrite it with invert(mesh=mesh). """ super(MeshMethodManager, self).__init__(**kwargs) self.mesh = None @property def paraDomain(self): return self.fop.paraDomain def paraModel(self, model=None): """Give the model parameter regarding the parameter mesh.""" if model is None: model = self.fw.model return self.fop.paraModel(model) def createMesh(self, data=None, **kwargs): """API, implement in derived classes.""" pg.critical('no default mesh generation defined .. implement in ' 'derived class') def setMesh(self, mesh, **kwargs): """Set a mesh and distribute it to the forward operator""" self.mesh = mesh self.applyMesh(mesh, **kwargs) def applyMesh(self, mesh, ignoreRegionManager=False, **kwargs): """ """ if ignoreRegionManager: mesh = self.fop.createRefinedFwdMesh(mesh, **kwargs) self.fop.setMesh(mesh, ignoreRegionManager=ignoreRegionManager) def invert(self, data=None, mesh=None, zWeight=1.0, startModel=None, **kwargs): """Run the full inversion. Parameters ---------- data : pg.DataContainer mesh : pg.Mesh [None] zWeight : float [1.0] startModel : float | iterable [None] If set to None fop.createDefaultStartModel(dataValues) is called. Keyword Arguments ----------------- forwarded to Inversion.run Returns ------- model : array Model mapped for match the paraDomain Cell markers. The calculated model is in self.fw.model. """ if data is None: data = self.data if data is None: pg.critical('No data given for inversion') self.applyData(data) # no mesh given and there is no mesh known .. we create them if mesh is None and self.mesh is None: mesh = self.createMesh(data, **kwargs) # a mesh was given or created so we forward it to the fop if mesh is not None: self.setMesh(mesh) # remove unused keyword argument .. need better kwargfs self.fop._refineP2 = kwargs.pop('refineP2', False) dataVals = self._ensureData(self.fop.data) errorVals = self._ensureError(self.fop.data, dataVals) if self.fop.mesh() is None: pg.critical('Please provide a mesh') # inversion will call this itsself as default behaviour # if startModel is None: # startModel = self.fop.createStartModel(dataVals) # pg._g('invert-dats', dataVals) # pg._g('invert-err', errVals) # pg._g('invert-sm', startModel) kwargs['startModel'] = startModel self.fop.setRegionProperties('*', zWeight=zWeight) # Limits is no mesh related argument here or base?? limits = kwargs.pop('limits', None) if limits is not None: self.fop.setRegionProperties('*', limits=limits) self.preRun(**kwargs) self.fw.run(dataVals, errorVals, **kwargs) self.postRun(**kwargs) return self.paraModel(self.fw.model) def showFit(self, axs=None, **kwargs): """Show data and the inversion result model response.""" orientation = 'vertical' if axs is None: fig, axs = pg.plt.subplots(nrows=1, ncols=2) orientation = 'horizontal' self.showData(data=self.inv.dataVals, orientation=orientation, ax=axs[0], **kwargs) axs[0].text(0.0, 1.03, "Data", transform=axs[0].transAxes, horizontalalignment='left', verticalalignment='center') resp = None data = None if 'model' in kwargs: resp = self.fop.response(kwargs['model']) data = self._ensureData(self.fop.data) else: resp = self.inv.response data = self.fw.dataVals self.showData(data=resp, orientation=orientation, ax=axs[1], **kwargs) axs[1].text(0.0, 1.03, "Response", transform=axs[1].transAxes, horizontalalignment='left', verticalalignment='center') fittext = r"rrms: {0}%, $\chi^2$: {1}".format( pg.pf(pg.utils.rrms(data, resp)*100), pg.pf(self.fw.chi2History[-1])) axs[1].text(1.0, 1.03, fittext, transform=axs[1].transAxes, horizontalalignment='right', verticalalignment='center') # if not kwargs.pop('hideFittingAnnotation', False): # axs[0].text(0.01, 1.0025, "rrms: {0}, $\chi^2$: {1}" # .format(pg.utils.prettyFloat(self.fw.inv.relrms()), # pg.utils.prettyFloat(self.fw.inv.chi2())), # transform=axs[0].transAxes, # horizontalalignment='left', # verticalalignment='bottom') return axs def coverage(self): """Return coverage vector considering the logarithmic transformation. """ covTrans = pg.core.coverageDCtrans(self.fop.jacobian(), 1.0 / self.inv.response, 1.0 / self.inv.model) nCells = self.fop.paraDomain.cellCount() return np.log10(covTrans[:nCells] / self.fop.paraDomain.cellSizes()) def standardizedCoverage(self, threshhold=0.01): """Return standardized coverage vector (0|1) using thresholding. """ return 1.0*(abs(self.coverage()) > threshhold)
class PetroInversionManager(MeshMethodManager): """Class for petrophysical inversion (s. Rücker et al. 2017).""" def __init__(self, petro, mgr=None, **kwargs): """Initialize instance with manager and petrophysical relation.""" petrofop = kwargs.pop('petrofop', None) if petrofop is None: fop = kwargs.pop('fop', None) if fop is None and mgr is not None: # Check! why I can't use mgr.fop # fop = mgr.fop fop = mgr.createForwardOperator() self.checkData = mgr.checkData self.checkError = mgr.checkError if fop is not None: if not isinstance(fop, pg.frameworks.PetroModelling): petrofop = pg.frameworks.PetroModelling(fop, petro) if petrofop is None: print(mgr) print(fop) pg.critical('implement me') super().__init__(fop=petrofop, **kwargs) # Really necessary? Should a combination of petro and joint do the same class JointPetroInversionManager(MeshMethodManager): """Joint inversion targeting at the same parameter through petrophysics.""" def __init__(self, petros, mgrs): """Initialize with lists of managers and transformations""" self.mgrs = mgrs self.fops = [pg.frameworks.PetroModelling(m.fop, p) for p, m in zip(petros, mgrs)] super().__init__(fop=pg.frameworks.JointModelling(self.fops)) # just hold a local copy self.dataTrans = pg.trans.TransCumulative() def checkError(self, err, data=None): """Collect error values.""" if len(err) != len(self.mgrs): pg.critical("Please provide data for all managers") vals = pg.Vector(0) for i, mgr in enumerate(self.mgrs): # we get the data values again or we have to split data dataVals = mgr.checkData(self.fop._data[i]) vals = pg.cat(vals, mgr.checkError(err[i], dataVals)) return vals def checkData(self, data): """Collect data values.""" if len(data) != len(self.mgrs): pg.critical("Please provide data for all managers") self.dataTrans.clear() vals = pg.Vector(0) for i, mgr in enumerate(self.mgrs): self.dataTrans.add(mgr.inv.dataTrans, data[i].size()) vals = pg.cat(vals, mgr.checkData(data[i])) self.inv.dataTrans = self.dataTrans return vals def invert(self, data, **kwargs): """Run inversion""" limits = kwargs.pop('limits', [0., 1.]) self.fop.modelTrans.setLowerBound(limits[0]) self.fop.modelTrans.setUpperBound(limits[1]) kwargs['startModel'] = kwargs.pop('startModel', (limits[1]+limits[0])/2.) return super().invert(data, **kwargs)
random_line_split
methodManager.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Method Manager Provide the end user interface for method (geophysical) dependent modelling and inversion as well as data and model visualization. """ import numpy as np import pygimli as pg from pygimli.utils import prettyFloat as pf def fit(funct, data, err=None, **kwargs): """Generic function fitter. Fit data to a given function. TODO ---- * Dictionary support for funct to submit user data.. Parameters ---------- funct: callable Function with the first argmument as data space, e.g., x, t, f, Nr. .. Any following arguments are the parameters to be fit. Except if a verbose flag if used. data: iterable (float) Data values err: iterable (float) [None] Data error values in %/100. Default is 1% if None are given. Other Parameters ---------------- *dataSpace*: iterable Keyword argument of the data space of len(data). The name need to fit the first argument of funct. Returns ------- model: array Fitted model parameter. response: array Model response. Example ------- >>> import pygimli as pg >>> >>> func = lambda t, a, b: a*np.exp(b*t) >>> t = np.linspace(1, 2, 20) >>> data = func(t, 1.1, 2.2) >>> model, response = pg.frameworks.fit(func, data, t=t) >>> print(pg.core.round(model, 1e-5)) 2 [1.1, 2.2] >>> _ = pg.plt.plot(t, data, 'o', label='data') >>> _ = pg.plt.plot(t, response, label='response') >>> _ = pg.plt.legend() """ mgr = ParameterInversionManager(funct, **kwargs) model = mgr.invert(data, err, **kwargs) return model, mgr.fw.response # TG: harmonicFit does not really belong here as it is no curve fit # We should rather use a class Decomposition # Discuss .. rename to Framework or InversionFramework since he only manages # the union of Inversion/Modelling and RegionManager(later) class MethodManager(object): """General manager to maintenance a measurement method. Method Manager are the interface to end-user interaction and can be seen as simple but complete application classes which manage all tasks of geophysical data processing. The method manager holds one instance of a forward operator and an appropriate inversion framework to handle modelling and data inversion. Method Manager also helps with data import and export, handle measurement data error estimation as well as model and data visualization. Attributes ---------- verbose : bool Give verbose output. debug : bool Give debug output. fop : :py:mod:`pygimli.frameworks.Modelling` Forward Operator instance .. knows the physics. fop is initialized by :py:mod:`pygimli.manager.MethodManager.initForwardOperator` and calls a valid :py:mod:`pygimli.manager.MethodManager.createForwardOperator` method in any derived classes. inv : :py:mod:`pygimli.frameworks.Inversion`. Inversion framework instance .. knows the reconstruction approach. The attribute inv is initialized by default but can be changed overwriting :py:mod:`pygimli.manager.MethodManager.initInversionFramework` """ def __init__(self, fop=None, fw=None, data=None, **kwargs): """Constructor.""" self._fop = fop self._fw = fw # we hold our own copy of the data self._verbose = kwargs.pop('verbose', False) self._debug = kwargs.pop('debug', False) self.data = None if data is not None: if isinstance(data, str): self.load(data) else: self.data = data # The inversion framework self._initInversionFramework(verbose=self._verbose, debug=self._debug) # The forward operator is stored in self._fw self._initForwardOperator(verbose=self._verbose, **kwargs) # maybe obsolete self.figs = {} self.errIsAbsolute = False def __hash__(self): """Create a hash for Method Manager.""" return pg.utils.strHash(str(type(self))) ^ hash(self.fop) @property def verbose(self): return self._verbose @verbose.setter def verbose(self, v): self._verbose = v self.fw.verbose = self._verbose @property def debug(self): return self._debug @debug.setter def debug(self, v): self._debug = v self.fw.debug = self._debug @property def fw(self): return self._fw @property def fop(self): return self.fw.fop @property def inv(self): return self.fw @property def model(self): return self.fw.model def reinitForwardOperator(self, **kwargs): """Reinitialize the forward operator. Sometimes it can be useful to reinitialize the forward operator. Keyword arguments will be forwarded to 'self.createForwardOperator'. """ self._initForwardOperator(**kwargs) def _initForwardOperator(self, **kwargs): """Initialize or re-initialize the forward operator. Called once in the constructor to force the manager to create the necessary forward operator member. Can be recalled if you need to changed the mangers own forward operator object. If you want an own instance of a valid FOP call createForwardOperator. """ if self._fop is not None: fop = self._fop else: fop = self.createForwardOperator(**kwargs) if fop is None: pg.critical("It seems that createForwardOperator method " "does not return a valid forward operator.") if self.fw is not None: self.fw.reset() self.fw.setForwardOperator(fop) else: pg.critical("No inversion framework defined.") def createForwardOperator(self, **kwargs): """Mandatory interface for derived classes. Here you need to specify which kind of forward operator FOP you want to use. This is called by any initForwardOperator() call. Parameters ---------- **kwargs Any arguments that are necessary for your FOP creation. Returns ------- Modelling Instance of any kind of :py:mod:`pygimli.framework.Modelling`. """ pg.critical("No forward operator defined, either give one or " "overwrite in derived class") def _initInversionFramework(self, **kwargs): """Initialize or re-initialize the inversion framework. Called once in the constructor to force the manager to create the necessary Framework instance. """ self._fw = self.createInversionFramework(**kwargs) if self.fw is None: pg.critical("createInversionFramework does not return " "valid inversion framework.") def createInversionFramework(self, **kwargs): """Create default Inversion framework. Derived classes may overwrite this method. Parameters ---------- **kwargs Any arguments that are necessary for your creation. Returns ------- Inversion Instance of any kind of :py:mod:`pygimli.framework.Inversion`. """ if self._fw is None: return pg.frameworks.Inversion(**kwargs) else: return self._fw def load(self, fileName): """API, overwrite in derived classes.""" pg.critical('API, overwrite in derived classes', fileName) def estimateError(self, data, errLevel=0.01, absError=None): # TODO check, rel or abs in return. """Estimate data error. Create an error of estimated measurement error. On default it returns an array of constant relative errors. More sophisticated error estimation should be done in specialized derived classes. Parameters ---------- data : iterable Data values for which the errors should be estimated. errLevel : float (0.01) Error level in percent/100 (i.e., 3% = 0.03). absError : float (None) Absolute error in the unit of the data. Returns ------- err : array Returning array of size len(data) """ if absError is not None: return absError + data * errLevel return np.ones(len(data)) * errLevel def simulate(self, model, **kwargs): # """Run a simulation aka the forward task.""" ra = self.fop.response(par=model) noiseLevel = kwargs.pop('noiseLevel', 0.0) if noiseLevel > 0: err = self.estimateError(ra, errLevel=noiseLevel) ra *= 1. + pg.randn(ra.size(), seed=kwargs.pop('seed', None)) * err return ra, err return ra def setData(self, data): """Set a data and distribute it to the forward operator""" self.data = data self.applyData(data) def applyData(self, data): """ """ self.fop.data = data def checkData(self, data): """Overwrite for special checks to return data values""" # if self._dataToken == 'nan': # pg.critical('self._dataToken nan, should be set in class', self) # return data(self._dataToken) return data def _ensureData(self, data): """Check data validity""" if data is None: data = self.fw.dataVals vals = self.checkData(data) if vals is None: pg.critical("There are no data values.") if abs(min(vals)) < 1e-12: print(min(vals), max(vals)) pg.critical("There are zero data values.") return vals def checkError(self, err, dataVals=None): """Return relative error. Default we assume 'err' are relative values. Overwrite is derived class if needed. """ if isinstance(err, pg.DataContainer): if not err.haveData('err'): pg.error('Datacontainer have no "err" values. ' 'Fallback set to 0.01') return err['err'] return err def _ensureError(self, err, dataVals=None): """Check error validity""" if err is None: err = self.fw.errorVals vals = self.checkError(err, dataVals) if vals is None: pg.warn('No data error given, set Fallback set to 1%') vals = np.ones(len(dataVals)) * 0.01 try: if min(vals) <= 0: pg.critical("All error values need to be larger then 0. Either" " give and err argument or fill dataContainer " " with a valid 'err' ", min(vals), max(vals)) except ValueError: pg.critical("Can't estimate data error") return vals def preRun(self, *args, **kwargs): """Called just before the inversion run starts.""" pass def postRun(self, *args, **kwargs): """Called just after the inversion run.""" pass def invert(self, data=None, err=None, **kwargs): """Invert the data. Invert the data by calling self.inv.run() with mandatory data and error values. TODO *need dataVals mandatory? what about already loaded data Parameters ---------- dataVals : iterable Data values to be inverted. errVals : iterable | float Error value for the given data. If errVals is float we assume this means to be a global relative error and force self.estimateError to be called. """ if data is not None: self.data = data else: data = self.data dataVals = self._ensureData(data) errVals = self._ensureError(err, dataVals) self.preRun(**kwargs) self.fw.run(dataVals, errVals, **kwargs) self.postRun(**kwargs) return self.fw.model def showModel(self, model, ax=None, **kwargs): """Show a model. Draw model into a given axes or show inversion result from last run. Forwards on default to the self.fop.drawModel function of the modelling operator. If there is no function given, you have to override this method. Parameters ---------- ax : mpl axes Axes object to draw into. Create a new if its not given. model : iterable Model data to be draw. Returns ------- ax, cbar """ if ax is None: fig, ax = pg.plt.subplots() ax, cBar = self.fop.drawModel(ax, model, **kwargs) return ax, cBar def showData(self, data=None, ax=None, **kwargs): """Show the data. Draw data values into a given axes or show the data values from the last run. Forwards on default to the self.fop.drawData function of the modelling operator. If there is no given function given, you have to override this method. Parameters ---------- ax : mpl axes Axes object to draw into. Create a new if its not given. data : iterable | pg.DataContainer Data values to be draw. Returns ------- ax, cbar """ if ax is None: fig, ax = pg.plt.subplots() if data is None: data = self.data return self.fop.drawData(ax, data, **kwargs), None def showResult(self, model=None, ax=None, **kwargs): """Show the last inversion result. TODO ---- DRY: decide showModel or showResult Parameters ---------- ax : mpl axes Axes object to draw into. Create a new if its not given. model : iterable [None] Model values to be draw. Default is self.model from the last run Returns ------- ax, cbar """ if model is None: model = self.model return self.showModel(model, ax=ax, **kwargs) def showFit(self, ax=None, **kwargs): """Show the last inversion data and response.""" ax, cBar = self.showData(data=self.inv.dataVals, error=self.inv.errorVals, label='Data', ax=ax, **kwargs) ax, cBar = self.showData(data=self.inv.response, label='Response', ax=ax, **kwargs) if not kwargs.pop('hideFittingAnnotation', False): fittext = r"rrms: {0}, $\chi^2$: {1}".format( pf(self.fw.inv.relrms()), pf(self.fw.inv.chi2())) ax.text(0.99, 0.005, fittext, transform=ax.transAxes, horizontalalignment='right', verticalalignment='bottom', fontsize=8) if not kwargs.pop('hideLegend', False): ax.legend() return ax, cBar def showResultAndFit(self, **kwargs): """Calls showResults and showFit.""" fig = pg.plt.figure() ax = fig.add_subplot(1, 2, 1) self.showResult(ax=ax, model=self.model, **kwargs) ax1 = fig.add_subplot(2, 2, 2) ax2 = fig.add_subplot(2, 2, 4) self.showFit(axs=[ax1, ax2], **kwargs) fig.tight_layout() return fig @staticmethod def createArgParser(dataSuffix='dat'): """Create default argument parser. TODO move this to some kind of app class Create default argument parser for the following options: -Q, --quiet -R, --robustData: options.robustData -B, --blockyModel: options.blockyModel -l, --lambda: options.lam -i, --maxIter: options.maxIter --depth: options.depth """ import argparse parser = argparse.ArgumentParser( description="usage: %prog [options] *." + dataSuffix) parser.add_argument("-Q", "--quiet", dest="quiet", action="store_true", default=False, help="Be verbose.") # parser.add_argument("-R", "--robustData", dest="robustData", # action="store_true", default=False, # help="Robust data (L1 norm) minimization.") # parser.add_argument("-B", "--blockyModel", dest="blockyModel", # action="store_true", default=False, # help="Blocky model (L1 norm) regularization.") parser.add_argument('-l', "--lambda", dest="lam", type=float, default=100, help="Regularization strength.") parser.add_argument('-i', "--maxIter", dest="maxIter", type=int, default=20, help="Maximum iteration count.") # parser.add_argument("--depth", dest="depth", type=float, # default=None, # help="Depth of inversion domain. [None=auto].") parser.add_argument('dataFileName') return parser class ParameterInversionManager(MethodManager): """Framework to invert unconstrained parameters.""" def __init__(self, funct=None, fop=None, **kwargs): """Constructor.""" if fop is not None: if not isinstance(fop, pg.frameworks.ParameterModelling): pg.critical("We need a fop if type ", pg.frameworks.ParameterModelling) elif funct is not None: fop = pg.frameworks.ParameterModelling(funct) else: pg.critical("you should either give a valid fop or a function so " "I can create the fop for you") super(ParameterInversionManager, self).__init__(fop, **kwargs) def createInversionFramework(self, **kwargs): """ """ return pg.frameworks.MarquardtInversion(**kwargs) def invert(self, data=None, err=None, **kwargs): """ Parameters ---------- limits: {str: [min, max]} Set limits for parameter by parameter name. startModel: {str: startModel} Set the start value for parameter by parameter name. """ dataSpace = kwargs.pop(self.fop.dataSpaceName, None) if dataSpace is not None: self.fop.dataSpace = dataSpace limits = kwargs.pop('limits', {}) for k, v in limits.items(): self.fop.setRegionProperties(k, limits=v) startModel = kwargs.pop('startModel', {}) if isinstance(startModel, dict): for k, v in startModel.items(): self.fop.setRegionProperties(k, startModel=v) else: kwargs['startModel'] = startModel return super(ParameterInversionManager, self).invert(data=data, err=err, **kwargs) class MethodManager1d(MethodManager): """Method Manager base class for managers on a 1d discretization.""" def __init__(self, fop=None, **kwargs): """Constructor.""" super(MethodManager1d, self).__init__(fop, **kwargs) def createInversionFramework(self, **kwargs): """ """ return pg.frameworks.Block1DInversion(**kwargs) def invert(self, data=None, err=None, **kwargs): """ """ return super(MethodManager1d, self).invert(data=data, err=err, **kwargs) class MeshMethodManager(MethodManager): def __init__(self, **kwargs): """Constructor. Attribute --------- mesh: pg.Mesh Copy of the main mesh to be distributed to inversion and the fop. You can overwrite it with invert(mesh=mesh). """ super(MeshMethodManager, self).__init__(**kwargs) self.mesh = None @property def paraDomain(self): return self.fop.paraDomain def paraModel(self, model=None): """Give the model parameter regarding the parameter mesh.""" if model is None: model = self.fw.model return self.fop.paraModel(model) def createMesh(self, data=None, **kwargs): """API, implement in derived classes.""" pg.critical('no default mesh generation defined .. implement in ' 'derived class') def setMesh(self, mesh, **kwargs): """Set a mesh and distribute it to the forward operator""" self.mesh = mesh self.applyMesh(mesh, **kwargs) def applyMesh(self, mesh, ignoreRegionManager=False, **kwargs): """ """ if ignoreRegionManager: mesh = self.fop.createRefinedFwdMesh(mesh, **kwargs) self.fop.setMesh(mesh, ignoreRegionManager=ignoreRegionManager) def invert(self, data=None, mesh=None, zWeight=1.0, startModel=None, **kwargs): """Run the full inversion. Parameters ---------- data : pg.DataContainer mesh : pg.Mesh [None] zWeight : float [1.0] startModel : float | iterable [None] If set to None fop.createDefaultStartModel(dataValues) is called. Keyword Arguments ----------------- forwarded to Inversion.run Returns ------- model : array Model mapped for match the paraDomain Cell markers. The calculated model is in self.fw.model. """ if data is None: data = self.data if data is None: pg.critical('No data given for inversion') self.applyData(data) # no mesh given and there is no mesh known .. we create them if mesh is None and self.mesh is None: mesh = self.createMesh(data, **kwargs) # a mesh was given or created so we forward it to the fop if mesh is not None: self.setMesh(mesh) # remove unused keyword argument .. need better kwargfs self.fop._refineP2 = kwargs.pop('refineP2', False) dataVals = self._ensureData(self.fop.data) errorVals = self._ensureError(self.fop.data, dataVals) if self.fop.mesh() is None: pg.critical('Please provide a mesh') # inversion will call this itsself as default behaviour # if startModel is None: # startModel = self.fop.createStartModel(dataVals) # pg._g('invert-dats', dataVals) # pg._g('invert-err', errVals) # pg._g('invert-sm', startModel) kwargs['startModel'] = startModel self.fop.setRegionProperties('*', zWeight=zWeight) # Limits is no mesh related argument here or base?? limits = kwargs.pop('limits', None) if limits is not None:
self.preRun(**kwargs) self.fw.run(dataVals, errorVals, **kwargs) self.postRun(**kwargs) return self.paraModel(self.fw.model) def showFit(self, axs=None, **kwargs): """Show data and the inversion result model response.""" orientation = 'vertical' if axs is None: fig, axs = pg.plt.subplots(nrows=1, ncols=2) orientation = 'horizontal' self.showData(data=self.inv.dataVals, orientation=orientation, ax=axs[0], **kwargs) axs[0].text(0.0, 1.03, "Data", transform=axs[0].transAxes, horizontalalignment='left', verticalalignment='center') resp = None data = None if 'model' in kwargs: resp = self.fop.response(kwargs['model']) data = self._ensureData(self.fop.data) else: resp = self.inv.response data = self.fw.dataVals self.showData(data=resp, orientation=orientation, ax=axs[1], **kwargs) axs[1].text(0.0, 1.03, "Response", transform=axs[1].transAxes, horizontalalignment='left', verticalalignment='center') fittext = r"rrms: {0}%, $\chi^2$: {1}".format( pg.pf(pg.utils.rrms(data, resp)*100), pg.pf(self.fw.chi2History[-1])) axs[1].text(1.0, 1.03, fittext, transform=axs[1].transAxes, horizontalalignment='right', verticalalignment='center') # if not kwargs.pop('hideFittingAnnotation', False): # axs[0].text(0.01, 1.0025, "rrms: {0}, $\chi^2$: {1}" # .format(pg.utils.prettyFloat(self.fw.inv.relrms()), # pg.utils.prettyFloat(self.fw.inv.chi2())), # transform=axs[0].transAxes, # horizontalalignment='left', # verticalalignment='bottom') return axs def coverage(self): """Return coverage vector considering the logarithmic transformation. """ covTrans = pg.core.coverageDCtrans(self.fop.jacobian(), 1.0 / self.inv.response, 1.0 / self.inv.model) nCells = self.fop.paraDomain.cellCount() return np.log10(covTrans[:nCells] / self.fop.paraDomain.cellSizes()) def standardizedCoverage(self, threshhold=0.01): """Return standardized coverage vector (0|1) using thresholding. """ return 1.0*(abs(self.coverage()) > threshhold) class PetroInversionManager(MeshMethodManager): """Class for petrophysical inversion (s. Rücker et al. 2017).""" def __init__(self, petro, mgr=None, **kwargs): """Initialize instance with manager and petrophysical relation.""" petrofop = kwargs.pop('petrofop', None) if petrofop is None: fop = kwargs.pop('fop', None) if fop is None and mgr is not None: # Check! why I can't use mgr.fop # fop = mgr.fop fop = mgr.createForwardOperator() self.checkData = mgr.checkData self.checkError = mgr.checkError if fop is not None: if not isinstance(fop, pg.frameworks.PetroModelling): petrofop = pg.frameworks.PetroModelling(fop, petro) if petrofop is None: print(mgr) print(fop) pg.critical('implement me') super().__init__(fop=petrofop, **kwargs) # Really necessary? Should a combination of petro and joint do the same class JointPetroInversionManager(MeshMethodManager): """Joint inversion targeting at the same parameter through petrophysics.""" def __init__(self, petros, mgrs): """Initialize with lists of managers and transformations""" self.mgrs = mgrs self.fops = [pg.frameworks.PetroModelling(m.fop, p) for p, m in zip(petros, mgrs)] super().__init__(fop=pg.frameworks.JointModelling(self.fops)) # just hold a local copy self.dataTrans = pg.trans.TransCumulative() def checkError(self, err, data=None): """Collect error values.""" if len(err) != len(self.mgrs): pg.critical("Please provide data for all managers") vals = pg.Vector(0) for i, mgr in enumerate(self.mgrs): # we get the data values again or we have to split data dataVals = mgr.checkData(self.fop._data[i]) vals = pg.cat(vals, mgr.checkError(err[i], dataVals)) return vals def checkData(self, data): """Collect data values.""" if len(data) != len(self.mgrs): pg.critical("Please provide data for all managers") self.dataTrans.clear() vals = pg.Vector(0) for i, mgr in enumerate(self.mgrs): self.dataTrans.add(mgr.inv.dataTrans, data[i].size()) vals = pg.cat(vals, mgr.checkData(data[i])) self.inv.dataTrans = self.dataTrans return vals def invert(self, data, **kwargs): """Run inversion""" limits = kwargs.pop('limits', [0., 1.]) self.fop.modelTrans.setLowerBound(limits[0]) self.fop.modelTrans.setUpperBound(limits[1]) kwargs['startModel'] = kwargs.pop('startModel', (limits[1]+limits[0])/2.) return super().invert(data, **kwargs)
self.fop.setRegionProperties('*', limits=limits)
conditional_block
methodManager.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Method Manager Provide the end user interface for method (geophysical) dependent modelling and inversion as well as data and model visualization. """ import numpy as np import pygimli as pg from pygimli.utils import prettyFloat as pf def fit(funct, data, err=None, **kwargs): """Generic function fitter. Fit data to a given function. TODO ---- * Dictionary support for funct to submit user data.. Parameters ---------- funct: callable Function with the first argmument as data space, e.g., x, t, f, Nr. .. Any following arguments are the parameters to be fit. Except if a verbose flag if used. data: iterable (float) Data values err: iterable (float) [None] Data error values in %/100. Default is 1% if None are given. Other Parameters ---------------- *dataSpace*: iterable Keyword argument of the data space of len(data). The name need to fit the first argument of funct. Returns ------- model: array Fitted model parameter. response: array Model response. Example ------- >>> import pygimli as pg >>> >>> func = lambda t, a, b: a*np.exp(b*t) >>> t = np.linspace(1, 2, 20) >>> data = func(t, 1.1, 2.2) >>> model, response = pg.frameworks.fit(func, data, t=t) >>> print(pg.core.round(model, 1e-5)) 2 [1.1, 2.2] >>> _ = pg.plt.plot(t, data, 'o', label='data') >>> _ = pg.plt.plot(t, response, label='response') >>> _ = pg.plt.legend() """ mgr = ParameterInversionManager(funct, **kwargs) model = mgr.invert(data, err, **kwargs) return model, mgr.fw.response # TG: harmonicFit does not really belong here as it is no curve fit # We should rather use a class Decomposition # Discuss .. rename to Framework or InversionFramework since he only manages # the union of Inversion/Modelling and RegionManager(later) class MethodManager(object): """General manager to maintenance a measurement method. Method Manager are the interface to end-user interaction and can be seen as simple but complete application classes which manage all tasks of geophysical data processing. The method manager holds one instance of a forward operator and an appropriate inversion framework to handle modelling and data inversion. Method Manager also helps with data import and export, handle measurement data error estimation as well as model and data visualization. Attributes ---------- verbose : bool Give verbose output. debug : bool Give debug output. fop : :py:mod:`pygimli.frameworks.Modelling` Forward Operator instance .. knows the physics. fop is initialized by :py:mod:`pygimli.manager.MethodManager.initForwardOperator` and calls a valid :py:mod:`pygimli.manager.MethodManager.createForwardOperator` method in any derived classes. inv : :py:mod:`pygimli.frameworks.Inversion`. Inversion framework instance .. knows the reconstruction approach. The attribute inv is initialized by default but can be changed overwriting :py:mod:`pygimli.manager.MethodManager.initInversionFramework` """ def __init__(self, fop=None, fw=None, data=None, **kwargs): """Constructor.""" self._fop = fop self._fw = fw # we hold our own copy of the data self._verbose = kwargs.pop('verbose', False) self._debug = kwargs.pop('debug', False) self.data = None if data is not None: if isinstance(data, str): self.load(data) else: self.data = data # The inversion framework self._initInversionFramework(verbose=self._verbose, debug=self._debug) # The forward operator is stored in self._fw self._initForwardOperator(verbose=self._verbose, **kwargs) # maybe obsolete self.figs = {} self.errIsAbsolute = False def __hash__(self): """Create a hash for Method Manager.""" return pg.utils.strHash(str(type(self))) ^ hash(self.fop) @property def verbose(self): return self._verbose @verbose.setter def verbose(self, v): self._verbose = v self.fw.verbose = self._verbose @property def debug(self): return self._debug @debug.setter def debug(self, v): self._debug = v self.fw.debug = self._debug @property def fw(self): return self._fw @property def fop(self): return self.fw.fop @property def inv(self): return self.fw @property def model(self): return self.fw.model def reinitForwardOperator(self, **kwargs): """Reinitialize the forward operator. Sometimes it can be useful to reinitialize the forward operator. Keyword arguments will be forwarded to 'self.createForwardOperator'. """ self._initForwardOperator(**kwargs) def _initForwardOperator(self, **kwargs): """Initialize or re-initialize the forward operator. Called once in the constructor to force the manager to create the necessary forward operator member. Can be recalled if you need to changed the mangers own forward operator object. If you want an own instance of a valid FOP call createForwardOperator. """ if self._fop is not None: fop = self._fop else: fop = self.createForwardOperator(**kwargs) if fop is None: pg.critical("It seems that createForwardOperator method " "does not return a valid forward operator.") if self.fw is not None: self.fw.reset() self.fw.setForwardOperator(fop) else: pg.critical("No inversion framework defined.") def createForwardOperator(self, **kwargs): """Mandatory interface for derived classes. Here you need to specify which kind of forward operator FOP you want to use. This is called by any initForwardOperator() call. Parameters ---------- **kwargs Any arguments that are necessary for your FOP creation. Returns ------- Modelling Instance of any kind of :py:mod:`pygimli.framework.Modelling`. """ pg.critical("No forward operator defined, either give one or " "overwrite in derived class") def _initInversionFramework(self, **kwargs): """Initialize or re-initialize the inversion framework. Called once in the constructor to force the manager to create the necessary Framework instance. """ self._fw = self.createInversionFramework(**kwargs) if self.fw is None: pg.critical("createInversionFramework does not return " "valid inversion framework.") def createInversionFramework(self, **kwargs): """Create default Inversion framework. Derived classes may overwrite this method. Parameters ---------- **kwargs Any arguments that are necessary for your creation. Returns ------- Inversion Instance of any kind of :py:mod:`pygimli.framework.Inversion`. """ if self._fw is None: return pg.frameworks.Inversion(**kwargs) else: return self._fw def load(self, fileName): """API, overwrite in derived classes.""" pg.critical('API, overwrite in derived classes', fileName) def estimateError(self, data, errLevel=0.01, absError=None): # TODO check, rel or abs in return. """Estimate data error. Create an error of estimated measurement error. On default it returns an array of constant relative errors. More sophisticated error estimation should be done in specialized derived classes. Parameters ---------- data : iterable Data values for which the errors should be estimated. errLevel : float (0.01) Error level in percent/100 (i.e., 3% = 0.03). absError : float (None) Absolute error in the unit of the data. Returns ------- err : array Returning array of size len(data) """ if absError is not None: return absError + data * errLevel return np.ones(len(data)) * errLevel def simulate(self, model, **kwargs): # """Run a simulation aka the forward task."""
def setData(self, data): """Set a data and distribute it to the forward operator""" self.data = data self.applyData(data) def applyData(self, data): """ """ self.fop.data = data def checkData(self, data): """Overwrite for special checks to return data values""" # if self._dataToken == 'nan': # pg.critical('self._dataToken nan, should be set in class', self) # return data(self._dataToken) return data def _ensureData(self, data): """Check data validity""" if data is None: data = self.fw.dataVals vals = self.checkData(data) if vals is None: pg.critical("There are no data values.") if abs(min(vals)) < 1e-12: print(min(vals), max(vals)) pg.critical("There are zero data values.") return vals def checkError(self, err, dataVals=None): """Return relative error. Default we assume 'err' are relative values. Overwrite is derived class if needed. """ if isinstance(err, pg.DataContainer): if not err.haveData('err'): pg.error('Datacontainer have no "err" values. ' 'Fallback set to 0.01') return err['err'] return err def _ensureError(self, err, dataVals=None): """Check error validity""" if err is None: err = self.fw.errorVals vals = self.checkError(err, dataVals) if vals is None: pg.warn('No data error given, set Fallback set to 1%') vals = np.ones(len(dataVals)) * 0.01 try: if min(vals) <= 0: pg.critical("All error values need to be larger then 0. Either" " give and err argument or fill dataContainer " " with a valid 'err' ", min(vals), max(vals)) except ValueError: pg.critical("Can't estimate data error") return vals def preRun(self, *args, **kwargs): """Called just before the inversion run starts.""" pass def postRun(self, *args, **kwargs): """Called just after the inversion run.""" pass def invert(self, data=None, err=None, **kwargs): """Invert the data. Invert the data by calling self.inv.run() with mandatory data and error values. TODO *need dataVals mandatory? what about already loaded data Parameters ---------- dataVals : iterable Data values to be inverted. errVals : iterable | float Error value for the given data. If errVals is float we assume this means to be a global relative error and force self.estimateError to be called. """ if data is not None: self.data = data else: data = self.data dataVals = self._ensureData(data) errVals = self._ensureError(err, dataVals) self.preRun(**kwargs) self.fw.run(dataVals, errVals, **kwargs) self.postRun(**kwargs) return self.fw.model def showModel(self, model, ax=None, **kwargs): """Show a model. Draw model into a given axes or show inversion result from last run. Forwards on default to the self.fop.drawModel function of the modelling operator. If there is no function given, you have to override this method. Parameters ---------- ax : mpl axes Axes object to draw into. Create a new if its not given. model : iterable Model data to be draw. Returns ------- ax, cbar """ if ax is None: fig, ax = pg.plt.subplots() ax, cBar = self.fop.drawModel(ax, model, **kwargs) return ax, cBar def showData(self, data=None, ax=None, **kwargs): """Show the data. Draw data values into a given axes or show the data values from the last run. Forwards on default to the self.fop.drawData function of the modelling operator. If there is no given function given, you have to override this method. Parameters ---------- ax : mpl axes Axes object to draw into. Create a new if its not given. data : iterable | pg.DataContainer Data values to be draw. Returns ------- ax, cbar """ if ax is None: fig, ax = pg.plt.subplots() if data is None: data = self.data return self.fop.drawData(ax, data, **kwargs), None def showResult(self, model=None, ax=None, **kwargs): """Show the last inversion result. TODO ---- DRY: decide showModel or showResult Parameters ---------- ax : mpl axes Axes object to draw into. Create a new if its not given. model : iterable [None] Model values to be draw. Default is self.model from the last run Returns ------- ax, cbar """ if model is None: model = self.model return self.showModel(model, ax=ax, **kwargs) def showFit(self, ax=None, **kwargs): """Show the last inversion data and response.""" ax, cBar = self.showData(data=self.inv.dataVals, error=self.inv.errorVals, label='Data', ax=ax, **kwargs) ax, cBar = self.showData(data=self.inv.response, label='Response', ax=ax, **kwargs) if not kwargs.pop('hideFittingAnnotation', False): fittext = r"rrms: {0}, $\chi^2$: {1}".format( pf(self.fw.inv.relrms()), pf(self.fw.inv.chi2())) ax.text(0.99, 0.005, fittext, transform=ax.transAxes, horizontalalignment='right', verticalalignment='bottom', fontsize=8) if not kwargs.pop('hideLegend', False): ax.legend() return ax, cBar def showResultAndFit(self, **kwargs): """Calls showResults and showFit.""" fig = pg.plt.figure() ax = fig.add_subplot(1, 2, 1) self.showResult(ax=ax, model=self.model, **kwargs) ax1 = fig.add_subplot(2, 2, 2) ax2 = fig.add_subplot(2, 2, 4) self.showFit(axs=[ax1, ax2], **kwargs) fig.tight_layout() return fig @staticmethod def createArgParser(dataSuffix='dat'): """Create default argument parser. TODO move this to some kind of app class Create default argument parser for the following options: -Q, --quiet -R, --robustData: options.robustData -B, --blockyModel: options.blockyModel -l, --lambda: options.lam -i, --maxIter: options.maxIter --depth: options.depth """ import argparse parser = argparse.ArgumentParser( description="usage: %prog [options] *." + dataSuffix) parser.add_argument("-Q", "--quiet", dest="quiet", action="store_true", default=False, help="Be verbose.") # parser.add_argument("-R", "--robustData", dest="robustData", # action="store_true", default=False, # help="Robust data (L1 norm) minimization.") # parser.add_argument("-B", "--blockyModel", dest="blockyModel", # action="store_true", default=False, # help="Blocky model (L1 norm) regularization.") parser.add_argument('-l', "--lambda", dest="lam", type=float, default=100, help="Regularization strength.") parser.add_argument('-i', "--maxIter", dest="maxIter", type=int, default=20, help="Maximum iteration count.") # parser.add_argument("--depth", dest="depth", type=float, # default=None, # help="Depth of inversion domain. [None=auto].") parser.add_argument('dataFileName') return parser class ParameterInversionManager(MethodManager): """Framework to invert unconstrained parameters.""" def __init__(self, funct=None, fop=None, **kwargs): """Constructor.""" if fop is not None: if not isinstance(fop, pg.frameworks.ParameterModelling): pg.critical("We need a fop if type ", pg.frameworks.ParameterModelling) elif funct is not None: fop = pg.frameworks.ParameterModelling(funct) else: pg.critical("you should either give a valid fop or a function so " "I can create the fop for you") super(ParameterInversionManager, self).__init__(fop, **kwargs) def createInversionFramework(self, **kwargs): """ """ return pg.frameworks.MarquardtInversion(**kwargs) def invert(self, data=None, err=None, **kwargs): """ Parameters ---------- limits: {str: [min, max]} Set limits for parameter by parameter name. startModel: {str: startModel} Set the start value for parameter by parameter name. """ dataSpace = kwargs.pop(self.fop.dataSpaceName, None) if dataSpace is not None: self.fop.dataSpace = dataSpace limits = kwargs.pop('limits', {}) for k, v in limits.items(): self.fop.setRegionProperties(k, limits=v) startModel = kwargs.pop('startModel', {}) if isinstance(startModel, dict): for k, v in startModel.items(): self.fop.setRegionProperties(k, startModel=v) else: kwargs['startModel'] = startModel return super(ParameterInversionManager, self).invert(data=data, err=err, **kwargs) class MethodManager1d(MethodManager): """Method Manager base class for managers on a 1d discretization.""" def __init__(self, fop=None, **kwargs): """Constructor.""" super(MethodManager1d, self).__init__(fop, **kwargs) def createInversionFramework(self, **kwargs): """ """ return pg.frameworks.Block1DInversion(**kwargs) def invert(self, data=None, err=None, **kwargs): """ """ return super(MethodManager1d, self).invert(data=data, err=err, **kwargs) class MeshMethodManager(MethodManager): def __init__(self, **kwargs): """Constructor. Attribute --------- mesh: pg.Mesh Copy of the main mesh to be distributed to inversion and the fop. You can overwrite it with invert(mesh=mesh). """ super(MeshMethodManager, self).__init__(**kwargs) self.mesh = None @property def paraDomain(self): return self.fop.paraDomain def paraModel(self, model=None): """Give the model parameter regarding the parameter mesh.""" if model is None: model = self.fw.model return self.fop.paraModel(model) def createMesh(self, data=None, **kwargs): """API, implement in derived classes.""" pg.critical('no default mesh generation defined .. implement in ' 'derived class') def setMesh(self, mesh, **kwargs): """Set a mesh and distribute it to the forward operator""" self.mesh = mesh self.applyMesh(mesh, **kwargs) def applyMesh(self, mesh, ignoreRegionManager=False, **kwargs): """ """ if ignoreRegionManager: mesh = self.fop.createRefinedFwdMesh(mesh, **kwargs) self.fop.setMesh(mesh, ignoreRegionManager=ignoreRegionManager) def invert(self, data=None, mesh=None, zWeight=1.0, startModel=None, **kwargs): """Run the full inversion. Parameters ---------- data : pg.DataContainer mesh : pg.Mesh [None] zWeight : float [1.0] startModel : float | iterable [None] If set to None fop.createDefaultStartModel(dataValues) is called. Keyword Arguments ----------------- forwarded to Inversion.run Returns ------- model : array Model mapped for match the paraDomain Cell markers. The calculated model is in self.fw.model. """ if data is None: data = self.data if data is None: pg.critical('No data given for inversion') self.applyData(data) # no mesh given and there is no mesh known .. we create them if mesh is None and self.mesh is None: mesh = self.createMesh(data, **kwargs) # a mesh was given or created so we forward it to the fop if mesh is not None: self.setMesh(mesh) # remove unused keyword argument .. need better kwargfs self.fop._refineP2 = kwargs.pop('refineP2', False) dataVals = self._ensureData(self.fop.data) errorVals = self._ensureError(self.fop.data, dataVals) if self.fop.mesh() is None: pg.critical('Please provide a mesh') # inversion will call this itsself as default behaviour # if startModel is None: # startModel = self.fop.createStartModel(dataVals) # pg._g('invert-dats', dataVals) # pg._g('invert-err', errVals) # pg._g('invert-sm', startModel) kwargs['startModel'] = startModel self.fop.setRegionProperties('*', zWeight=zWeight) # Limits is no mesh related argument here or base?? limits = kwargs.pop('limits', None) if limits is not None: self.fop.setRegionProperties('*', limits=limits) self.preRun(**kwargs) self.fw.run(dataVals, errorVals, **kwargs) self.postRun(**kwargs) return self.paraModel(self.fw.model) def showFit(self, axs=None, **kwargs): """Show data and the inversion result model response.""" orientation = 'vertical' if axs is None: fig, axs = pg.plt.subplots(nrows=1, ncols=2) orientation = 'horizontal' self.showData(data=self.inv.dataVals, orientation=orientation, ax=axs[0], **kwargs) axs[0].text(0.0, 1.03, "Data", transform=axs[0].transAxes, horizontalalignment='left', verticalalignment='center') resp = None data = None if 'model' in kwargs: resp = self.fop.response(kwargs['model']) data = self._ensureData(self.fop.data) else: resp = self.inv.response data = self.fw.dataVals self.showData(data=resp, orientation=orientation, ax=axs[1], **kwargs) axs[1].text(0.0, 1.03, "Response", transform=axs[1].transAxes, horizontalalignment='left', verticalalignment='center') fittext = r"rrms: {0}%, $\chi^2$: {1}".format( pg.pf(pg.utils.rrms(data, resp)*100), pg.pf(self.fw.chi2History[-1])) axs[1].text(1.0, 1.03, fittext, transform=axs[1].transAxes, horizontalalignment='right', verticalalignment='center') # if not kwargs.pop('hideFittingAnnotation', False): # axs[0].text(0.01, 1.0025, "rrms: {0}, $\chi^2$: {1}" # .format(pg.utils.prettyFloat(self.fw.inv.relrms()), # pg.utils.prettyFloat(self.fw.inv.chi2())), # transform=axs[0].transAxes, # horizontalalignment='left', # verticalalignment='bottom') return axs def coverage(self): """Return coverage vector considering the logarithmic transformation. """ covTrans = pg.core.coverageDCtrans(self.fop.jacobian(), 1.0 / self.inv.response, 1.0 / self.inv.model) nCells = self.fop.paraDomain.cellCount() return np.log10(covTrans[:nCells] / self.fop.paraDomain.cellSizes()) def standardizedCoverage(self, threshhold=0.01): """Return standardized coverage vector (0|1) using thresholding. """ return 1.0*(abs(self.coverage()) > threshhold) class PetroInversionManager(MeshMethodManager): """Class for petrophysical inversion (s. Rücker et al. 2017).""" def __init__(self, petro, mgr=None, **kwargs): """Initialize instance with manager and petrophysical relation.""" petrofop = kwargs.pop('petrofop', None) if petrofop is None: fop = kwargs.pop('fop', None) if fop is None and mgr is not None: # Check! why I can't use mgr.fop # fop = mgr.fop fop = mgr.createForwardOperator() self.checkData = mgr.checkData self.checkError = mgr.checkError if fop is not None: if not isinstance(fop, pg.frameworks.PetroModelling): petrofop = pg.frameworks.PetroModelling(fop, petro) if petrofop is None: print(mgr) print(fop) pg.critical('implement me') super().__init__(fop=petrofop, **kwargs) # Really necessary? Should a combination of petro and joint do the same class JointPetroInversionManager(MeshMethodManager): """Joint inversion targeting at the same parameter through petrophysics.""" def __init__(self, petros, mgrs): """Initialize with lists of managers and transformations""" self.mgrs = mgrs self.fops = [pg.frameworks.PetroModelling(m.fop, p) for p, m in zip(petros, mgrs)] super().__init__(fop=pg.frameworks.JointModelling(self.fops)) # just hold a local copy self.dataTrans = pg.trans.TransCumulative() def checkError(self, err, data=None): """Collect error values.""" if len(err) != len(self.mgrs): pg.critical("Please provide data for all managers") vals = pg.Vector(0) for i, mgr in enumerate(self.mgrs): # we get the data values again or we have to split data dataVals = mgr.checkData(self.fop._data[i]) vals = pg.cat(vals, mgr.checkError(err[i], dataVals)) return vals def checkData(self, data): """Collect data values.""" if len(data) != len(self.mgrs): pg.critical("Please provide data for all managers") self.dataTrans.clear() vals = pg.Vector(0) for i, mgr in enumerate(self.mgrs): self.dataTrans.add(mgr.inv.dataTrans, data[i].size()) vals = pg.cat(vals, mgr.checkData(data[i])) self.inv.dataTrans = self.dataTrans return vals def invert(self, data, **kwargs): """Run inversion""" limits = kwargs.pop('limits', [0., 1.]) self.fop.modelTrans.setLowerBound(limits[0]) self.fop.modelTrans.setUpperBound(limits[1]) kwargs['startModel'] = kwargs.pop('startModel', (limits[1]+limits[0])/2.) return super().invert(data, **kwargs)
ra = self.fop.response(par=model) noiseLevel = kwargs.pop('noiseLevel', 0.0) if noiseLevel > 0: err = self.estimateError(ra, errLevel=noiseLevel) ra *= 1. + pg.randn(ra.size(), seed=kwargs.pop('seed', None)) * err return ra, err return ra
identifier_body
methodManager.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Method Manager Provide the end user interface for method (geophysical) dependent modelling and inversion as well as data and model visualization. """ import numpy as np import pygimli as pg from pygimli.utils import prettyFloat as pf def fit(funct, data, err=None, **kwargs): """Generic function fitter. Fit data to a given function. TODO ---- * Dictionary support for funct to submit user data.. Parameters ---------- funct: callable Function with the first argmument as data space, e.g., x, t, f, Nr. .. Any following arguments are the parameters to be fit. Except if a verbose flag if used. data: iterable (float) Data values err: iterable (float) [None] Data error values in %/100. Default is 1% if None are given. Other Parameters ---------------- *dataSpace*: iterable Keyword argument of the data space of len(data). The name need to fit the first argument of funct. Returns ------- model: array Fitted model parameter. response: array Model response. Example ------- >>> import pygimli as pg >>> >>> func = lambda t, a, b: a*np.exp(b*t) >>> t = np.linspace(1, 2, 20) >>> data = func(t, 1.1, 2.2) >>> model, response = pg.frameworks.fit(func, data, t=t) >>> print(pg.core.round(model, 1e-5)) 2 [1.1, 2.2] >>> _ = pg.plt.plot(t, data, 'o', label='data') >>> _ = pg.plt.plot(t, response, label='response') >>> _ = pg.plt.legend() """ mgr = ParameterInversionManager(funct, **kwargs) model = mgr.invert(data, err, **kwargs) return model, mgr.fw.response # TG: harmonicFit does not really belong here as it is no curve fit # We should rather use a class Decomposition # Discuss .. rename to Framework or InversionFramework since he only manages # the union of Inversion/Modelling and RegionManager(later) class MethodManager(object): """General manager to maintenance a measurement method. Method Manager are the interface to end-user interaction and can be seen as simple but complete application classes which manage all tasks of geophysical data processing. The method manager holds one instance of a forward operator and an appropriate inversion framework to handle modelling and data inversion. Method Manager also helps with data import and export, handle measurement data error estimation as well as model and data visualization. Attributes ---------- verbose : bool Give verbose output. debug : bool Give debug output. fop : :py:mod:`pygimli.frameworks.Modelling` Forward Operator instance .. knows the physics. fop is initialized by :py:mod:`pygimli.manager.MethodManager.initForwardOperator` and calls a valid :py:mod:`pygimli.manager.MethodManager.createForwardOperator` method in any derived classes. inv : :py:mod:`pygimli.frameworks.Inversion`. Inversion framework instance .. knows the reconstruction approach. The attribute inv is initialized by default but can be changed overwriting :py:mod:`pygimli.manager.MethodManager.initInversionFramework` """ def __init__(self, fop=None, fw=None, data=None, **kwargs): """Constructor.""" self._fop = fop self._fw = fw # we hold our own copy of the data self._verbose = kwargs.pop('verbose', False) self._debug = kwargs.pop('debug', False) self.data = None if data is not None: if isinstance(data, str): self.load(data) else: self.data = data # The inversion framework self._initInversionFramework(verbose=self._verbose, debug=self._debug) # The forward operator is stored in self._fw self._initForwardOperator(verbose=self._verbose, **kwargs) # maybe obsolete self.figs = {} self.errIsAbsolute = False def __hash__(self): """Create a hash for Method Manager.""" return pg.utils.strHash(str(type(self))) ^ hash(self.fop) @property def verbose(self): return self._verbose @verbose.setter def verbose(self, v): self._verbose = v self.fw.verbose = self._verbose @property def debug(self): return self._debug @debug.setter def debug(self, v): self._debug = v self.fw.debug = self._debug @property def fw(self): return self._fw @property def fop(self): return self.fw.fop @property def inv(self): return self.fw @property def model(self): return self.fw.model def reinitForwardOperator(self, **kwargs): """Reinitialize the forward operator. Sometimes it can be useful to reinitialize the forward operator. Keyword arguments will be forwarded to 'self.createForwardOperator'. """ self._initForwardOperator(**kwargs) def _initForwardOperator(self, **kwargs): """Initialize or re-initialize the forward operator. Called once in the constructor to force the manager to create the necessary forward operator member. Can be recalled if you need to changed the mangers own forward operator object. If you want an own instance of a valid FOP call createForwardOperator. """ if self._fop is not None: fop = self._fop else: fop = self.createForwardOperator(**kwargs) if fop is None: pg.critical("It seems that createForwardOperator method " "does not return a valid forward operator.") if self.fw is not None: self.fw.reset() self.fw.setForwardOperator(fop) else: pg.critical("No inversion framework defined.") def createForwardOperator(self, **kwargs): """Mandatory interface for derived classes. Here you need to specify which kind of forward operator FOP you want to use. This is called by any initForwardOperator() call. Parameters ---------- **kwargs Any arguments that are necessary for your FOP creation. Returns ------- Modelling Instance of any kind of :py:mod:`pygimli.framework.Modelling`. """ pg.critical("No forward operator defined, either give one or " "overwrite in derived class") def _initInversionFramework(self, **kwargs): """Initialize or re-initialize the inversion framework. Called once in the constructor to force the manager to create the necessary Framework instance. """ self._fw = self.createInversionFramework(**kwargs) if self.fw is None: pg.critical("createInversionFramework does not return " "valid inversion framework.") def createInversionFramework(self, **kwargs): """Create default Inversion framework. Derived classes may overwrite this method. Parameters ---------- **kwargs Any arguments that are necessary for your creation. Returns ------- Inversion Instance of any kind of :py:mod:`pygimli.framework.Inversion`. """ if self._fw is None: return pg.frameworks.Inversion(**kwargs) else: return self._fw def load(self, fileName): """API, overwrite in derived classes.""" pg.critical('API, overwrite in derived classes', fileName) def estimateError(self, data, errLevel=0.01, absError=None): # TODO check, rel or abs in return. """Estimate data error. Create an error of estimated measurement error. On default it returns an array of constant relative errors. More sophisticated error estimation should be done in specialized derived classes. Parameters ---------- data : iterable Data values for which the errors should be estimated. errLevel : float (0.01) Error level in percent/100 (i.e., 3% = 0.03). absError : float (None) Absolute error in the unit of the data. Returns ------- err : array Returning array of size len(data) """ if absError is not None: return absError + data * errLevel return np.ones(len(data)) * errLevel def simulate(self, model, **kwargs): # """Run a simulation aka the forward task.""" ra = self.fop.response(par=model) noiseLevel = kwargs.pop('noiseLevel', 0.0) if noiseLevel > 0: err = self.estimateError(ra, errLevel=noiseLevel) ra *= 1. + pg.randn(ra.size(), seed=kwargs.pop('seed', None)) * err return ra, err return ra def setData(self, data): """Set a data and distribute it to the forward operator""" self.data = data self.applyData(data) def applyData(self, data): """ """ self.fop.data = data def checkData(self, data): """Overwrite for special checks to return data values""" # if self._dataToken == 'nan': # pg.critical('self._dataToken nan, should be set in class', self) # return data(self._dataToken) return data def _ensureData(self, data): """Check data validity""" if data is None: data = self.fw.dataVals vals = self.checkData(data) if vals is None: pg.critical("There are no data values.") if abs(min(vals)) < 1e-12: print(min(vals), max(vals)) pg.critical("There are zero data values.") return vals def checkError(self, err, dataVals=None): """Return relative error. Default we assume 'err' are relative values. Overwrite is derived class if needed. """ if isinstance(err, pg.DataContainer): if not err.haveData('err'): pg.error('Datacontainer have no "err" values. ' 'Fallback set to 0.01') return err['err'] return err def _ensureError(self, err, dataVals=None): """Check error validity""" if err is None: err = self.fw.errorVals vals = self.checkError(err, dataVals) if vals is None: pg.warn('No data error given, set Fallback set to 1%') vals = np.ones(len(dataVals)) * 0.01 try: if min(vals) <= 0: pg.critical("All error values need to be larger then 0. Either" " give and err argument or fill dataContainer " " with a valid 'err' ", min(vals), max(vals)) except ValueError: pg.critical("Can't estimate data error") return vals def preRun(self, *args, **kwargs): """Called just before the inversion run starts.""" pass def postRun(self, *args, **kwargs): """Called just after the inversion run.""" pass def invert(self, data=None, err=None, **kwargs): """Invert the data. Invert the data by calling self.inv.run() with mandatory data and error values. TODO *need dataVals mandatory? what about already loaded data Parameters ---------- dataVals : iterable Data values to be inverted. errVals : iterable | float Error value for the given data. If errVals is float we assume this means to be a global relative error and force self.estimateError to be called. """ if data is not None: self.data = data else: data = self.data dataVals = self._ensureData(data) errVals = self._ensureError(err, dataVals) self.preRun(**kwargs) self.fw.run(dataVals, errVals, **kwargs) self.postRun(**kwargs) return self.fw.model def showModel(self, model, ax=None, **kwargs): """Show a model. Draw model into a given axes or show inversion result from last run. Forwards on default to the self.fop.drawModel function of the modelling operator. If there is no function given, you have to override this method. Parameters ---------- ax : mpl axes Axes object to draw into. Create a new if its not given. model : iterable Model data to be draw. Returns ------- ax, cbar """ if ax is None: fig, ax = pg.plt.subplots() ax, cBar = self.fop.drawModel(ax, model, **kwargs) return ax, cBar def showData(self, data=None, ax=None, **kwargs): """Show the data. Draw data values into a given axes or show the data values from the last run. Forwards on default to the self.fop.drawData function of the modelling operator. If there is no given function given, you have to override this method. Parameters ---------- ax : mpl axes Axes object to draw into. Create a new if its not given. data : iterable | pg.DataContainer Data values to be draw. Returns ------- ax, cbar """ if ax is None: fig, ax = pg.plt.subplots() if data is None: data = self.data return self.fop.drawData(ax, data, **kwargs), None def showResult(self, model=None, ax=None, **kwargs): """Show the last inversion result. TODO ---- DRY: decide showModel or showResult Parameters ---------- ax : mpl axes Axes object to draw into. Create a new if its not given. model : iterable [None] Model values to be draw. Default is self.model from the last run Returns ------- ax, cbar """ if model is None: model = self.model return self.showModel(model, ax=ax, **kwargs) def showFit(self, ax=None, **kwargs): """Show the last inversion data and response.""" ax, cBar = self.showData(data=self.inv.dataVals, error=self.inv.errorVals, label='Data', ax=ax, **kwargs) ax, cBar = self.showData(data=self.inv.response, label='Response', ax=ax, **kwargs) if not kwargs.pop('hideFittingAnnotation', False): fittext = r"rrms: {0}, $\chi^2$: {1}".format( pf(self.fw.inv.relrms()), pf(self.fw.inv.chi2())) ax.text(0.99, 0.005, fittext, transform=ax.transAxes, horizontalalignment='right', verticalalignment='bottom', fontsize=8) if not kwargs.pop('hideLegend', False): ax.legend() return ax, cBar def showResultAndFit(self, **kwargs): """Calls showResults and showFit.""" fig = pg.plt.figure() ax = fig.add_subplot(1, 2, 1) self.showResult(ax=ax, model=self.model, **kwargs) ax1 = fig.add_subplot(2, 2, 2) ax2 = fig.add_subplot(2, 2, 4) self.showFit(axs=[ax1, ax2], **kwargs) fig.tight_layout() return fig @staticmethod def createArgParser(dataSuffix='dat'): """Create default argument parser. TODO move this to some kind of app class Create default argument parser for the following options: -Q, --quiet -R, --robustData: options.robustData -B, --blockyModel: options.blockyModel -l, --lambda: options.lam -i, --maxIter: options.maxIter --depth: options.depth """ import argparse parser = argparse.ArgumentParser( description="usage: %prog [options] *." + dataSuffix) parser.add_argument("-Q", "--quiet", dest="quiet", action="store_true", default=False, help="Be verbose.") # parser.add_argument("-R", "--robustData", dest="robustData", # action="store_true", default=False, # help="Robust data (L1 norm) minimization.") # parser.add_argument("-B", "--blockyModel", dest="blockyModel", # action="store_true", default=False, # help="Blocky model (L1 norm) regularization.") parser.add_argument('-l', "--lambda", dest="lam", type=float, default=100, help="Regularization strength.") parser.add_argument('-i', "--maxIter", dest="maxIter", type=int, default=20, help="Maximum iteration count.") # parser.add_argument("--depth", dest="depth", type=float, # default=None, # help="Depth of inversion domain. [None=auto].") parser.add_argument('dataFileName') return parser class ParameterInversionManager(MethodManager): """Framework to invert unconstrained parameters.""" def __init__(self, funct=None, fop=None, **kwargs): """Constructor.""" if fop is not None: if not isinstance(fop, pg.frameworks.ParameterModelling): pg.critical("We need a fop if type ", pg.frameworks.ParameterModelling) elif funct is not None: fop = pg.frameworks.ParameterModelling(funct) else: pg.critical("you should either give a valid fop or a function so " "I can create the fop for you") super(ParameterInversionManager, self).__init__(fop, **kwargs) def createInversionFramework(self, **kwargs): """ """ return pg.frameworks.MarquardtInversion(**kwargs) def invert(self, data=None, err=None, **kwargs): """ Parameters ---------- limits: {str: [min, max]} Set limits for parameter by parameter name. startModel: {str: startModel} Set the start value for parameter by parameter name. """ dataSpace = kwargs.pop(self.fop.dataSpaceName, None) if dataSpace is not None: self.fop.dataSpace = dataSpace limits = kwargs.pop('limits', {}) for k, v in limits.items(): self.fop.setRegionProperties(k, limits=v) startModel = kwargs.pop('startModel', {}) if isinstance(startModel, dict): for k, v in startModel.items(): self.fop.setRegionProperties(k, startModel=v) else: kwargs['startModel'] = startModel return super(ParameterInversionManager, self).invert(data=data, err=err, **kwargs) class MethodManager1d(MethodManager): """Method Manager base class for managers on a 1d discretization.""" def __init__(self, fop=None, **kwargs): """Constructor.""" super(MethodManager1d, self).__init__(fop, **kwargs) def createInversionFramework(self, **kwargs): """ """ return pg.frameworks.Block1DInversion(**kwargs) def invert(self, data=None, err=None, **kwargs): """ """ return super(MethodManager1d, self).invert(data=data, err=err, **kwargs) class MeshMethodManager(MethodManager): def __init__(self, **kwargs): """Constructor. Attribute --------- mesh: pg.Mesh Copy of the main mesh to be distributed to inversion and the fop. You can overwrite it with invert(mesh=mesh). """ super(MeshMethodManager, self).__init__(**kwargs) self.mesh = None @property def paraDomain(self): return self.fop.paraDomain def paraModel(self, model=None): """Give the model parameter regarding the parameter mesh.""" if model is None: model = self.fw.model return self.fop.paraModel(model) def createMesh(self, data=None, **kwargs): """API, implement in derived classes.""" pg.critical('no default mesh generation defined .. implement in ' 'derived class') def setMesh(self, mesh, **kwargs): """Set a mesh and distribute it to the forward operator""" self.mesh = mesh self.applyMesh(mesh, **kwargs) def applyMesh(self, mesh, ignoreRegionManager=False, **kwargs): """ """ if ignoreRegionManager: mesh = self.fop.createRefinedFwdMesh(mesh, **kwargs) self.fop.setMesh(mesh, ignoreRegionManager=ignoreRegionManager) def invert(self, data=None, mesh=None, zWeight=1.0, startModel=None, **kwargs): """Run the full inversion. Parameters ---------- data : pg.DataContainer mesh : pg.Mesh [None] zWeight : float [1.0] startModel : float | iterable [None] If set to None fop.createDefaultStartModel(dataValues) is called. Keyword Arguments ----------------- forwarded to Inversion.run Returns ------- model : array Model mapped for match the paraDomain Cell markers. The calculated model is in self.fw.model. """ if data is None: data = self.data if data is None: pg.critical('No data given for inversion') self.applyData(data) # no mesh given and there is no mesh known .. we create them if mesh is None and self.mesh is None: mesh = self.createMesh(data, **kwargs) # a mesh was given or created so we forward it to the fop if mesh is not None: self.setMesh(mesh) # remove unused keyword argument .. need better kwargfs self.fop._refineP2 = kwargs.pop('refineP2', False) dataVals = self._ensureData(self.fop.data) errorVals = self._ensureError(self.fop.data, dataVals) if self.fop.mesh() is None: pg.critical('Please provide a mesh') # inversion will call this itsself as default behaviour # if startModel is None: # startModel = self.fop.createStartModel(dataVals) # pg._g('invert-dats', dataVals) # pg._g('invert-err', errVals) # pg._g('invert-sm', startModel) kwargs['startModel'] = startModel self.fop.setRegionProperties('*', zWeight=zWeight) # Limits is no mesh related argument here or base?? limits = kwargs.pop('limits', None) if limits is not None: self.fop.setRegionProperties('*', limits=limits) self.preRun(**kwargs) self.fw.run(dataVals, errorVals, **kwargs) self.postRun(**kwargs) return self.paraModel(self.fw.model) def showFit(self, axs=None, **kwargs): """Show data and the inversion result model response.""" orientation = 'vertical' if axs is None: fig, axs = pg.plt.subplots(nrows=1, ncols=2) orientation = 'horizontal' self.showData(data=self.inv.dataVals, orientation=orientation, ax=axs[0], **kwargs) axs[0].text(0.0, 1.03, "Data", transform=axs[0].transAxes, horizontalalignment='left', verticalalignment='center') resp = None data = None if 'model' in kwargs: resp = self.fop.response(kwargs['model']) data = self._ensureData(self.fop.data) else: resp = self.inv.response data = self.fw.dataVals self.showData(data=resp, orientation=orientation, ax=axs[1], **kwargs) axs[1].text(0.0, 1.03, "Response", transform=axs[1].transAxes, horizontalalignment='left', verticalalignment='center') fittext = r"rrms: {0}%, $\chi^2$: {1}".format( pg.pf(pg.utils.rrms(data, resp)*100), pg.pf(self.fw.chi2History[-1])) axs[1].text(1.0, 1.03, fittext, transform=axs[1].transAxes, horizontalalignment='right', verticalalignment='center') # if not kwargs.pop('hideFittingAnnotation', False): # axs[0].text(0.01, 1.0025, "rrms: {0}, $\chi^2$: {1}" # .format(pg.utils.prettyFloat(self.fw.inv.relrms()), # pg.utils.prettyFloat(self.fw.inv.chi2())), # transform=axs[0].transAxes, # horizontalalignment='left', # verticalalignment='bottom') return axs def coverage(self): """Return coverage vector considering the logarithmic transformation. """ covTrans = pg.core.coverageDCtrans(self.fop.jacobian(), 1.0 / self.inv.response, 1.0 / self.inv.model) nCells = self.fop.paraDomain.cellCount() return np.log10(covTrans[:nCells] / self.fop.paraDomain.cellSizes()) def standardizedCoverage(self, threshhold=0.01): """Return standardized coverage vector (0|1) using thresholding. """ return 1.0*(abs(self.coverage()) > threshhold) class PetroInversionManager(MeshMethodManager): """Class for petrophysical inversion (s. Rücker et al. 2017).""" def _
self, petro, mgr=None, **kwargs): """Initialize instance with manager and petrophysical relation.""" petrofop = kwargs.pop('petrofop', None) if petrofop is None: fop = kwargs.pop('fop', None) if fop is None and mgr is not None: # Check! why I can't use mgr.fop # fop = mgr.fop fop = mgr.createForwardOperator() self.checkData = mgr.checkData self.checkError = mgr.checkError if fop is not None: if not isinstance(fop, pg.frameworks.PetroModelling): petrofop = pg.frameworks.PetroModelling(fop, petro) if petrofop is None: print(mgr) print(fop) pg.critical('implement me') super().__init__(fop=petrofop, **kwargs) # Really necessary? Should a combination of petro and joint do the same class JointPetroInversionManager(MeshMethodManager): """Joint inversion targeting at the same parameter through petrophysics.""" def __init__(self, petros, mgrs): """Initialize with lists of managers and transformations""" self.mgrs = mgrs self.fops = [pg.frameworks.PetroModelling(m.fop, p) for p, m in zip(petros, mgrs)] super().__init__(fop=pg.frameworks.JointModelling(self.fops)) # just hold a local copy self.dataTrans = pg.trans.TransCumulative() def checkError(self, err, data=None): """Collect error values.""" if len(err) != len(self.mgrs): pg.critical("Please provide data for all managers") vals = pg.Vector(0) for i, mgr in enumerate(self.mgrs): # we get the data values again or we have to split data dataVals = mgr.checkData(self.fop._data[i]) vals = pg.cat(vals, mgr.checkError(err[i], dataVals)) return vals def checkData(self, data): """Collect data values.""" if len(data) != len(self.mgrs): pg.critical("Please provide data for all managers") self.dataTrans.clear() vals = pg.Vector(0) for i, mgr in enumerate(self.mgrs): self.dataTrans.add(mgr.inv.dataTrans, data[i].size()) vals = pg.cat(vals, mgr.checkData(data[i])) self.inv.dataTrans = self.dataTrans return vals def invert(self, data, **kwargs): """Run inversion""" limits = kwargs.pop('limits', [0., 1.]) self.fop.modelTrans.setLowerBound(limits[0]) self.fop.modelTrans.setUpperBound(limits[1]) kwargs['startModel'] = kwargs.pop('startModel', (limits[1]+limits[0])/2.) return super().invert(data, **kwargs)
_init__(
identifier_name
edu_dp_o.py
import sys import ctypes def popcount(N): if sys.platform.startswith('linux'): libc = ctypes.cdll.LoadLibrary('libc.so.6') return libc.__sched_cpucount(ctypes.sizeof(ctypes.c_long), (ctypes.c_long * 1)(N)) elif sys.platform == 'darwin': libc = ctypes.cdll.LoadLibrary('libSystem.dylib') return libc.__popcountdi2(N) else: assert(False) def main():
if __name__ == '__main__': main()
N = int(input()) mod = 10 ** 9 + 7 A = [[int(x) for x in input().split()] for _ in range(N)] dp = [0] * (1 << N) dp[0] = 1 for state in range(1 << N): dp[state] %= mod i = popcount(state) for j in range(N): if (state >> j & 1) == 0 and A[i][j]: dp[state | (1 << j)] += dp[state] print(dp[-1])
identifier_body
edu_dp_o.py
import sys import ctypes def popcount(N): if sys.platform.startswith('linux'): libc = ctypes.cdll.LoadLibrary('libc.so.6') return libc.__sched_cpucount(ctypes.sizeof(ctypes.c_long), (ctypes.c_long * 1)(N)) elif sys.platform == 'darwin': libc = ctypes.cdll.LoadLibrary('libSystem.dylib') return libc.__popcountdi2(N) else: assert(False) def
(): N = int(input()) mod = 10 ** 9 + 7 A = [[int(x) for x in input().split()] for _ in range(N)] dp = [0] * (1 << N) dp[0] = 1 for state in range(1 << N): dp[state] %= mod i = popcount(state) for j in range(N): if (state >> j & 1) == 0 and A[i][j]: dp[state | (1 << j)] += dp[state] print(dp[-1]) if __name__ == '__main__': main()
main
identifier_name
edu_dp_o.py
import sys import ctypes def popcount(N): if sys.platform.startswith('linux'):
elif sys.platform == 'darwin': libc = ctypes.cdll.LoadLibrary('libSystem.dylib') return libc.__popcountdi2(N) else: assert(False) def main(): N = int(input()) mod = 10 ** 9 + 7 A = [[int(x) for x in input().split()] for _ in range(N)] dp = [0] * (1 << N) dp[0] = 1 for state in range(1 << N): dp[state] %= mod i = popcount(state) for j in range(N): if (state >> j & 1) == 0 and A[i][j]: dp[state | (1 << j)] += dp[state] print(dp[-1]) if __name__ == '__main__': main()
libc = ctypes.cdll.LoadLibrary('libc.so.6') return libc.__sched_cpucount(ctypes.sizeof(ctypes.c_long), (ctypes.c_long * 1)(N))
conditional_block
edu_dp_o.py
import sys import ctypes def popcount(N): if sys.platform.startswith('linux'): libc = ctypes.cdll.LoadLibrary('libc.so.6') return libc.__sched_cpucount(ctypes.sizeof(ctypes.c_long), (ctypes.c_long * 1)(N)) elif sys.platform == 'darwin':
def main(): N = int(input()) mod = 10 ** 9 + 7 A = [[int(x) for x in input().split()] for _ in range(N)] dp = [0] * (1 << N) dp[0] = 1 for state in range(1 << N): dp[state] %= mod i = popcount(state) for j in range(N): if (state >> j & 1) == 0 and A[i][j]: dp[state | (1 << j)] += dp[state] print(dp[-1]) if __name__ == '__main__': main()
libc = ctypes.cdll.LoadLibrary('libSystem.dylib') return libc.__popcountdi2(N) else: assert(False)
random_line_split
tables.py
import logging from django.utils.html import format_html import django_tables2 as tables from django_tables2.rows import BoundPinnedRow, BoundRow logger = logging.getLogger(__name__) # A cheat to force BoundPinnedRows to use the same rendering as BoundRows # otherwise links don't work # BoundPinnedRow._get_and_render_with = BoundRow._get_and_render_with class MultiLinkColumn(tables.RelatedLinkColumn): """ Like RelatedLinkColumn but allows multiple choices of accessor to be rendered in a hierarchy, e.g. accessors = ['foo.bar', 'baz.bof'] text = '{instance.number}: {instance}' In this case if 'foo.bar' resolves, it will be rendered. Otherwise 'baz.bof' will be tested to resolve, and so on. If nothing renders, the column will be blank. The text string will resolve using instance. """ def __init__(self, accessors, **kwargs): """Here we force order by the accessors. By default MultiLinkColumns have empty_values: () to force calculation every time. """ defaults = { 'order_by': accessors, 'empty_values': (), } defaults.update(**kwargs) super().__init__(**defaults) self.accessors = [tables.A(a) for a in accessors] def compose_url(self, record, bound_column): """Resolve the first accessor which resolves. """ for a in self.accessors: try: return a.resolve(record).get_absolute_url() except (ValueError, AttributeError): continue return "" def text_value(self, record, value): """If self.text is set, it will be used as a format string for the instance returned by the accessor with the keyword `instance`. """ for a in self.accessors: try: instance = a.resolve(record) if instance is None:
except ValueError: continue # Use self.text as a format string if self.text: return self.text.format(instance=instance, record=record, value=value) else: return str(instance) # Finally if no accessors were resolved, return value or a blank string # return super().text_value(record, value) return value or "" class XeroLinkColumn(tables.Column): """Renders a badge link to the objects record in xero.""" def render(self, value, record=None): if record.xero_id: return format_html( '<span class="badge progress-bar-info">' '<a class="alert-link" role="button" target="_blank" ' 'href="{href}">View in Xero</a></span>', href=record.get_xero_url() ) class BaseTable(tables.Table): class Meta: attrs = {"class": "table table-bordered table-striped table-hover " "table-condensed"} # @classmethod # def set_header_color(cls, color): # """ # Sets all column headers to have this background colour. # """ # for column in cls.base_columns.values(): # try: # column.attrs['th'].update( # {'style': f'background-color:{color};'}) # except KeyError: # column.attrs['th'] = {'style': f'background-color:{color};'} def set_header_color(self, color): """ Sets all column headers to have this background colour. """ for column in self.columns.columns.values(): try: column.column.attrs['th'].update( {'style': f'background-color:{color};'}) except KeyError: column.column.attrs['th'] = { 'style': f'background-color:{color};'} class ModelTable(BaseTable): class Meta(BaseTable.Meta): exclude = ('id',) class CurrencyColumn(tables.Column): """Render a table column as GBP.""" def render(self, value): return f'£{value:,.2f}' class NumberColumn(tables.Column): """Only render decimal places if necessary.""" def render(self, value): if value is not None: return f'{value:n}' class ColorColumn(tables.Column): """Render the colour in a box.""" def __init__(self, *args, **kwargs): """This will ignore other attrs passed in.""" kwargs.setdefault('attrs', {'td': {'class': "small-width text-center"}}) super().__init__(*args, **kwargs) def render(self, value): if value: return format_html( '<div class="color-box" style="background:{};"></div>', value)
raise ValueError
conditional_block
tables.py
import logging from django.utils.html import format_html import django_tables2 as tables from django_tables2.rows import BoundPinnedRow, BoundRow logger = logging.getLogger(__name__) # A cheat to force BoundPinnedRows to use the same rendering as BoundRows # otherwise links don't work # BoundPinnedRow._get_and_render_with = BoundRow._get_and_render_with class MultiLinkColumn(tables.RelatedLinkColumn): """ Like RelatedLinkColumn but allows multiple choices of accessor to be rendered in a hierarchy, e.g. accessors = ['foo.bar', 'baz.bof'] text = '{instance.number}: {instance}' In this case if 'foo.bar' resolves, it will be rendered. Otherwise 'baz.bof' will be tested to resolve, and so on. If nothing renders, the column will be blank. The text string will resolve using instance. """ def __init__(self, accessors, **kwargs): """Here we force order by the accessors. By default MultiLinkColumns have empty_values: () to force calculation every time. """ defaults = { 'order_by': accessors, 'empty_values': (), } defaults.update(**kwargs) super().__init__(**defaults) self.accessors = [tables.A(a) for a in accessors] def compose_url(self, record, bound_column): """Resolve the first accessor which resolves. """ for a in self.accessors: try: return a.resolve(record).get_absolute_url() except (ValueError, AttributeError): continue return "" def text_value(self, record, value): """If self.text is set, it will be used as a format string for the instance returned by the accessor with the keyword `instance`. """ for a in self.accessors: try: instance = a.resolve(record) if instance is None: raise ValueError except ValueError: continue # Use self.text as a format string if self.text: return self.text.format(instance=instance, record=record, value=value) else: return str(instance) # Finally if no accessors were resolved, return value or a blank string # return super().text_value(record, value) return value or "" class XeroLinkColumn(tables.Column): """Renders a badge link to the objects record in xero.""" def render(self, value, record=None): if record.xero_id: return format_html( '<span class="badge progress-bar-info">' '<a class="alert-link" role="button" target="_blank" ' 'href="{href}">View in Xero</a></span>', href=record.get_xero_url() ) class BaseTable(tables.Table): class Meta: attrs = {"class": "table table-bordered table-striped table-hover " "table-condensed"} # @classmethod # def set_header_color(cls, color): # """ # Sets all column headers to have this background colour. # """ # for column in cls.base_columns.values(): # try: # column.attrs['th'].update( # {'style': f'background-color:{color};'}) # except KeyError: # column.attrs['th'] = {'style': f'background-color:{color};'} def set_header_color(self, color): """ Sets all column headers to have this background colour. """ for column in self.columns.columns.values(): try: column.column.attrs['th'].update( {'style': f'background-color:{color};'}) except KeyError: column.column.attrs['th'] = { 'style': f'background-color:{color};'} class ModelTable(BaseTable):
class CurrencyColumn(tables.Column): """Render a table column as GBP.""" def render(self, value): return f'£{value:,.2f}' class NumberColumn(tables.Column): """Only render decimal places if necessary.""" def render(self, value): if value is not None: return f'{value:n}' class ColorColumn(tables.Column): """Render the colour in a box.""" def __init__(self, *args, **kwargs): """This will ignore other attrs passed in.""" kwargs.setdefault('attrs', {'td': {'class': "small-width text-center"}}) super().__init__(*args, **kwargs) def render(self, value): if value: return format_html( '<div class="color-box" style="background:{};"></div>', value)
class Meta(BaseTable.Meta): exclude = ('id',)
identifier_body
tables.py
import logging from django.utils.html import format_html import django_tables2 as tables from django_tables2.rows import BoundPinnedRow, BoundRow logger = logging.getLogger(__name__) # A cheat to force BoundPinnedRows to use the same rendering as BoundRows # otherwise links don't work # BoundPinnedRow._get_and_render_with = BoundRow._get_and_render_with class MultiLinkColumn(tables.RelatedLinkColumn): """ Like RelatedLinkColumn but allows multiple choices of accessor to be rendered in a hierarchy, e.g. accessors = ['foo.bar', 'baz.bof'] text = '{instance.number}: {instance}' In this case if 'foo.bar' resolves, it will be rendered. Otherwise 'baz.bof' will be tested to resolve, and so on. If nothing renders, the column will be blank. The text string will resolve using instance. """ def __init__(self, accessors, **kwargs): """Here we force order by the accessors. By default MultiLinkColumns have empty_values: () to force calculation every time. """ defaults = { 'order_by': accessors, 'empty_values': (), } defaults.update(**kwargs) super().__init__(**defaults) self.accessors = [tables.A(a) for a in accessors] def compose_url(self, record, bound_column): """Resolve the first accessor which resolves. """ for a in self.accessors: try: return a.resolve(record).get_absolute_url() except (ValueError, AttributeError): continue return "" def text_value(self, record, value): """If self.text is set, it will be used as a format string for the instance returned by the accessor with the keyword `instance`. """ for a in self.accessors: try: instance = a.resolve(record) if instance is None: raise ValueError except ValueError: continue # Use self.text as a format string if self.text: return self.text.format(instance=instance, record=record, value=value) else: return str(instance) # Finally if no accessors were resolved, return value or a blank string # return super().text_value(record, value) return value or "" class XeroLinkColumn(tables.Column): """Renders a badge link to the objects record in xero.""" def render(self, value, record=None): if record.xero_id: return format_html( '<span class="badge progress-bar-info">' '<a class="alert-link" role="button" target="_blank" ' 'href="{href}">View in Xero</a></span>', href=record.get_xero_url() ) class BaseTable(tables.Table): class Meta: attrs = {"class": "table table-bordered table-striped table-hover " "table-condensed"} # @classmethod # def set_header_color(cls, color): # """ # Sets all column headers to have this background colour. # """ # for column in cls.base_columns.values(): # try: # column.attrs['th'].update( # {'style': f'background-color:{color};'}) # except KeyError: # column.attrs['th'] = {'style': f'background-color:{color};'} def set_header_color(self, color): """ Sets all column headers to have this background colour. """ for column in self.columns.columns.values(): try: column.column.attrs['th'].update( {'style': f'background-color:{color};'}) except KeyError: column.column.attrs['th'] = { 'style': f'background-color:{color};'} class ModelTable(BaseTable):
exclude = ('id',) class CurrencyColumn(tables.Column): """Render a table column as GBP.""" def render(self, value): return f'£{value:,.2f}' class NumberColumn(tables.Column): """Only render decimal places if necessary.""" def render(self, value): if value is not None: return f'{value:n}' class ColorColumn(tables.Column): """Render the colour in a box.""" def __init__(self, *args, **kwargs): """This will ignore other attrs passed in.""" kwargs.setdefault('attrs', {'td': {'class': "small-width text-center"}}) super().__init__(*args, **kwargs) def render(self, value): if value: return format_html( '<div class="color-box" style="background:{};"></div>', value)
class Meta(BaseTable.Meta):
random_line_split
tables.py
import logging from django.utils.html import format_html import django_tables2 as tables from django_tables2.rows import BoundPinnedRow, BoundRow logger = logging.getLogger(__name__) # A cheat to force BoundPinnedRows to use the same rendering as BoundRows # otherwise links don't work # BoundPinnedRow._get_and_render_with = BoundRow._get_and_render_with class MultiLinkColumn(tables.RelatedLinkColumn): """ Like RelatedLinkColumn but allows multiple choices of accessor to be rendered in a hierarchy, e.g. accessors = ['foo.bar', 'baz.bof'] text = '{instance.number}: {instance}' In this case if 'foo.bar' resolves, it will be rendered. Otherwise 'baz.bof' will be tested to resolve, and so on. If nothing renders, the column will be blank. The text string will resolve using instance. """ def __init__(self, accessors, **kwargs): """Here we force order by the accessors. By default MultiLinkColumns have empty_values: () to force calculation every time. """ defaults = { 'order_by': accessors, 'empty_values': (), } defaults.update(**kwargs) super().__init__(**defaults) self.accessors = [tables.A(a) for a in accessors] def compose_url(self, record, bound_column): """Resolve the first accessor which resolves. """ for a in self.accessors: try: return a.resolve(record).get_absolute_url() except (ValueError, AttributeError): continue return "" def text_value(self, record, value): """If self.text is set, it will be used as a format string for the instance returned by the accessor with the keyword `instance`. """ for a in self.accessors: try: instance = a.resolve(record) if instance is None: raise ValueError except ValueError: continue # Use self.text as a format string if self.text: return self.text.format(instance=instance, record=record, value=value) else: return str(instance) # Finally if no accessors were resolved, return value or a blank string # return super().text_value(record, value) return value or "" class XeroLinkColumn(tables.Column): """Renders a badge link to the objects record in xero.""" def render(self, value, record=None): if record.xero_id: return format_html( '<span class="badge progress-bar-info">' '<a class="alert-link" role="button" target="_blank" ' 'href="{href}">View in Xero</a></span>', href=record.get_xero_url() ) class BaseTable(tables.Table): class Meta: attrs = {"class": "table table-bordered table-striped table-hover " "table-condensed"} # @classmethod # def set_header_color(cls, color): # """ # Sets all column headers to have this background colour. # """ # for column in cls.base_columns.values(): # try: # column.attrs['th'].update( # {'style': f'background-color:{color};'}) # except KeyError: # column.attrs['th'] = {'style': f'background-color:{color};'} def set_header_color(self, color): """ Sets all column headers to have this background colour. """ for column in self.columns.columns.values(): try: column.column.attrs['th'].update( {'style': f'background-color:{color};'}) except KeyError: column.column.attrs['th'] = { 'style': f'background-color:{color};'} class ModelTable(BaseTable): class Meta(BaseTable.Meta): exclude = ('id',) class CurrencyColumn(tables.Column): """Render a table column as GBP.""" def render(self, value): return f'£{value:,.2f}' class NumberColumn(tables.Column): """Only render decimal places if necessary.""" def r
self, value): if value is not None: return f'{value:n}' class ColorColumn(tables.Column): """Render the colour in a box.""" def __init__(self, *args, **kwargs): """This will ignore other attrs passed in.""" kwargs.setdefault('attrs', {'td': {'class': "small-width text-center"}}) super().__init__(*args, **kwargs) def render(self, value): if value: return format_html( '<div class="color-box" style="background:{};"></div>', value)
ender(
identifier_name
game.js
/* Game namespace */ var game = { // an object where to store game information data : { // score score : 0 }, // Run on page load. "onload" : function () { // Initialize the video. if (!me.video.init("screen", me.video.CANVAS, 1067, 600, true, '1.0')) { alert("Your browser does not support HTML5 canvas."); return; }
} // Initialize the audio. me.audio.init("mp3,ogg"); // Set a callback to run when loading is complete. me.loader.onload = this.loaded.bind(this); // Load the resources. me.loader.preload(game.resources); // Initialize melonJS and display a loading screen. me.state.change(me.state.LOADING); }, // Run on game resources loaded. "loaded" : function () { me.pool.register("player", game.PlayerEntity, true); me.state.set(me.state.MENU, new game.TitleScreen()); me.state.set(me.state.PLAY, new game.PlayScreen()); // Start the game. me.state.change(me.state.PLAY); } };
// add "#debug" to the URL to enable the debug Panel if (document.location.hash === "#debug") { window.onReady(function () { me.plugin.register.defer(this, debugPanel, "debug"); });
random_line_split
game.js
/* Game namespace */ var game = { // an object where to store game information data : { // score score : 0 }, // Run on page load. "onload" : function () { // Initialize the video. if (!me.video.init("screen", me.video.CANVAS, 1067, 600, true, '1.0'))
// add "#debug" to the URL to enable the debug Panel if (document.location.hash === "#debug") { window.onReady(function () { me.plugin.register.defer(this, debugPanel, "debug"); }); } // Initialize the audio. me.audio.init("mp3,ogg"); // Set a callback to run when loading is complete. me.loader.onload = this.loaded.bind(this); // Load the resources. me.loader.preload(game.resources); // Initialize melonJS and display a loading screen. me.state.change(me.state.LOADING); }, // Run on game resources loaded. "loaded" : function () { me.pool.register("player", game.PlayerEntity, true); me.state.set(me.state.MENU, new game.TitleScreen()); me.state.set(me.state.PLAY, new game.PlayScreen()); // Start the game. me.state.change(me.state.PLAY); } };
{ alert("Your browser does not support HTML5 canvas."); return; }
conditional_block
declaration.js
'use strict'; exports.__esModule = true; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _warnOnce = require('./warn-once'); var _warnOnce2 = _interopRequireDefault(_warnOnce); var _node = require('./node'); var _node2 = _interopRequireDefault(_node); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Declaration = function (_Node) { _inherits(Declaration, _Node); function Declaration(defaults) { _classCallCheck(this, Declaration); var _this = _possibleConstructorReturn(this, _Node.call(this, defaults)); _this.type = 'decl'; return _this; } /* istanbul ignore next */ _createClass(Declaration, [{ key: '_value', get: function get() { (0, _warnOnce2.default)('Node#_value was deprecated. Use Node#raws.value'); return this.raws.value;
, set: function set(val) { (0, _warnOnce2.default)('Node#_value was deprecated. Use Node#raws.value'); this.raws.value = val; } /* istanbul ignore next */ }, { key: '_important', get: function get() { (0, _warnOnce2.default)('Node#_important was deprecated. Use Node#raws.important'); return this.raws.important; } /* istanbul ignore next */ , set: function set(val) { (0, _warnOnce2.default)('Node#_important was deprecated. Use Node#raws.important'); this.raws.important = val; } }]); return Declaration; }(_node2.default); exports.default = Declaration; module.exports = exports['default'];
} /* istanbul ignore next */
random_line_split
declaration.js
'use strict'; exports.__esModule = true; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _warnOnce = require('./warn-once'); var _warnOnce2 = _interopRequireDefault(_warnOnce); var _node = require('./node'); var _node2 = _interopRequireDefault(_node); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Declaration = function (_Node) { _inherits(Declaration, _Node); function
(defaults) { _classCallCheck(this, Declaration); var _this = _possibleConstructorReturn(this, _Node.call(this, defaults)); _this.type = 'decl'; return _this; } /* istanbul ignore next */ _createClass(Declaration, [{ key: '_value', get: function get() { (0, _warnOnce2.default)('Node#_value was deprecated. Use Node#raws.value'); return this.raws.value; } /* istanbul ignore next */ , set: function set(val) { (0, _warnOnce2.default)('Node#_value was deprecated. Use Node#raws.value'); this.raws.value = val; } /* istanbul ignore next */ }, { key: '_important', get: function get() { (0, _warnOnce2.default)('Node#_important was deprecated. Use Node#raws.important'); return this.raws.important; } /* istanbul ignore next */ , set: function set(val) { (0, _warnOnce2.default)('Node#_important was deprecated. Use Node#raws.important'); this.raws.important = val; } }]); return Declaration; }(_node2.default); exports.default = Declaration; module.exports = exports['default'];
Declaration
identifier_name
declaration.js
'use strict'; exports.__esModule = true; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _warnOnce = require('./warn-once'); var _warnOnce2 = _interopRequireDefault(_warnOnce); var _node = require('./node'); var _node2 = _interopRequireDefault(_node); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass)
var Declaration = function (_Node) { _inherits(Declaration, _Node); function Declaration(defaults) { _classCallCheck(this, Declaration); var _this = _possibleConstructorReturn(this, _Node.call(this, defaults)); _this.type = 'decl'; return _this; } /* istanbul ignore next */ _createClass(Declaration, [{ key: '_value', get: function get() { (0, _warnOnce2.default)('Node#_value was deprecated. Use Node#raws.value'); return this.raws.value; } /* istanbul ignore next */ , set: function set(val) { (0, _warnOnce2.default)('Node#_value was deprecated. Use Node#raws.value'); this.raws.value = val; } /* istanbul ignore next */ }, { key: '_important', get: function get() { (0, _warnOnce2.default)('Node#_important was deprecated. Use Node#raws.important'); return this.raws.important; } /* istanbul ignore next */ , set: function set(val) { (0, _warnOnce2.default)('Node#_important was deprecated. Use Node#raws.important'); this.raws.important = val; } }]); return Declaration; }(_node2.default); exports.default = Declaration; module.exports = exports['default'];
{ if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
identifier_body
pico.js
/** * Pico's Default Theme - JavaScript helper * * Pico is a stupidly simple, blazing fast, flat file CMS. * * @author Daniel Rudolf * @link http://picocms.org * @license http://opensource.org/licenses/MIT The MIT License * @version 1.1 */ function main() { // capability CSS classes document.documentElement.className = 'js'; // wrap tables var tables = document.querySelectorAll('#main > .container > table'); for (var i = 0; i < tables.length; i++) { if (!/\btable-responsive\b/.test(tables[i].parentElement.className)) { var tableWrapper = document.createElement('div'); tableWrapper.className = 'table-responsive'; tables[i].parentElement.insertBefore(tableWrapper, tables[i]); tableWrapper.appendChild(tables[i]); } } // responsive menu var menu = document.getElementById('nav'), menuToggle = document.getElementById('nav-toggle'), toggleMenuEvent = function (event) { if (event.type === 'keydown') { if ((event.keyCode != 13) && (event.keyCode != 32)) { return; } } event.preventDefault(); if (menuToggle.getAttribute('aria-expanded') === 'false') { menuToggle.setAttribute('aria-expanded', 'true'); utils.slideDown(menu, null, function () { if (event.type === 'keydown') { menu.focus(); } }); } else { menuToggle.setAttribute('aria-expanded', 'false'); utils.slideUp(menu); } }, onResizeEvent = function () { if (utils.isElementVisible(menuToggle)) { menu.className = 'hidden'; menuToggle.addEventListener('click', toggleMenuEvent); menuToggle.addEventListener('keydown', toggleMenuEvent); } else
}; window.addEventListener('resize', onResizeEvent); onResizeEvent(); } main();
{ menu.className = ''; menu.removeAttribute('data-slide-id'); menuToggle.removeEventListener('click', toggleMenuEvent); menuToggle.removeEventListener('keydown', toggleMenuEvent); }
conditional_block
pico.js
/** * Pico's Default Theme - JavaScript helper * * Pico is a stupidly simple, blazing fast, flat file CMS. * * @author Daniel Rudolf * @link http://picocms.org * @license http://opensource.org/licenses/MIT The MIT License * @version 1.1 */ function main() { // capability CSS classes document.documentElement.className = 'js'; // wrap tables var tables = document.querySelectorAll('#main > .container > table'); for (var i = 0; i < tables.length; i++) { if (!/\btable-responsive\b/.test(tables[i].parentElement.className)) {
tableWrapper.appendChild(tables[i]); } } // responsive menu var menu = document.getElementById('nav'), menuToggle = document.getElementById('nav-toggle'), toggleMenuEvent = function (event) { if (event.type === 'keydown') { if ((event.keyCode != 13) && (event.keyCode != 32)) { return; } } event.preventDefault(); if (menuToggle.getAttribute('aria-expanded') === 'false') { menuToggle.setAttribute('aria-expanded', 'true'); utils.slideDown(menu, null, function () { if (event.type === 'keydown') { menu.focus(); } }); } else { menuToggle.setAttribute('aria-expanded', 'false'); utils.slideUp(menu); } }, onResizeEvent = function () { if (utils.isElementVisible(menuToggle)) { menu.className = 'hidden'; menuToggle.addEventListener('click', toggleMenuEvent); menuToggle.addEventListener('keydown', toggleMenuEvent); } else { menu.className = ''; menu.removeAttribute('data-slide-id'); menuToggle.removeEventListener('click', toggleMenuEvent); menuToggle.removeEventListener('keydown', toggleMenuEvent); } }; window.addEventListener('resize', onResizeEvent); onResizeEvent(); } main();
var tableWrapper = document.createElement('div'); tableWrapper.className = 'table-responsive'; tables[i].parentElement.insertBefore(tableWrapper, tables[i]);
random_line_split
pico.js
/** * Pico's Default Theme - JavaScript helper * * Pico is a stupidly simple, blazing fast, flat file CMS. * * @author Daniel Rudolf * @link http://picocms.org * @license http://opensource.org/licenses/MIT The MIT License * @version 1.1 */ function main()
main();
{ // capability CSS classes document.documentElement.className = 'js'; // wrap tables var tables = document.querySelectorAll('#main > .container > table'); for (var i = 0; i < tables.length; i++) { if (!/\btable-responsive\b/.test(tables[i].parentElement.className)) { var tableWrapper = document.createElement('div'); tableWrapper.className = 'table-responsive'; tables[i].parentElement.insertBefore(tableWrapper, tables[i]); tableWrapper.appendChild(tables[i]); } } // responsive menu var menu = document.getElementById('nav'), menuToggle = document.getElementById('nav-toggle'), toggleMenuEvent = function (event) { if (event.type === 'keydown') { if ((event.keyCode != 13) && (event.keyCode != 32)) { return; } } event.preventDefault(); if (menuToggle.getAttribute('aria-expanded') === 'false') { menuToggle.setAttribute('aria-expanded', 'true'); utils.slideDown(menu, null, function () { if (event.type === 'keydown') { menu.focus(); } }); } else { menuToggle.setAttribute('aria-expanded', 'false'); utils.slideUp(menu); } }, onResizeEvent = function () { if (utils.isElementVisible(menuToggle)) { menu.className = 'hidden'; menuToggle.addEventListener('click', toggleMenuEvent); menuToggle.addEventListener('keydown', toggleMenuEvent); } else { menu.className = ''; menu.removeAttribute('data-slide-id'); menuToggle.removeEventListener('click', toggleMenuEvent); menuToggle.removeEventListener('keydown', toggleMenuEvent); } }; window.addEventListener('resize', onResizeEvent); onResizeEvent(); }
identifier_body
pico.js
/** * Pico's Default Theme - JavaScript helper * * Pico is a stupidly simple, blazing fast, flat file CMS. * * @author Daniel Rudolf * @link http://picocms.org * @license http://opensource.org/licenses/MIT The MIT License * @version 1.1 */ function
() { // capability CSS classes document.documentElement.className = 'js'; // wrap tables var tables = document.querySelectorAll('#main > .container > table'); for (var i = 0; i < tables.length; i++) { if (!/\btable-responsive\b/.test(tables[i].parentElement.className)) { var tableWrapper = document.createElement('div'); tableWrapper.className = 'table-responsive'; tables[i].parentElement.insertBefore(tableWrapper, tables[i]); tableWrapper.appendChild(tables[i]); } } // responsive menu var menu = document.getElementById('nav'), menuToggle = document.getElementById('nav-toggle'), toggleMenuEvent = function (event) { if (event.type === 'keydown') { if ((event.keyCode != 13) && (event.keyCode != 32)) { return; } } event.preventDefault(); if (menuToggle.getAttribute('aria-expanded') === 'false') { menuToggle.setAttribute('aria-expanded', 'true'); utils.slideDown(menu, null, function () { if (event.type === 'keydown') { menu.focus(); } }); } else { menuToggle.setAttribute('aria-expanded', 'false'); utils.slideUp(menu); } }, onResizeEvent = function () { if (utils.isElementVisible(menuToggle)) { menu.className = 'hidden'; menuToggle.addEventListener('click', toggleMenuEvent); menuToggle.addEventListener('keydown', toggleMenuEvent); } else { menu.className = ''; menu.removeAttribute('data-slide-id'); menuToggle.removeEventListener('click', toggleMenuEvent); menuToggle.removeEventListener('keydown', toggleMenuEvent); } }; window.addEventListener('resize', onResizeEvent); onResizeEvent(); } main();
main
identifier_name
test_tahoelafs.py
#!/usr/bin/python """ Test the TahoeLAFS @author: Marek Palatinus <marek@palatinus.cz> """ import sys import logging import unittest from fs.base import FS import fs.errors as errors from fs.tests import FSTestCases, ThreadingTestCases from fs.contrib.tahoelafs import TahoeLAFS, Connection logging.getLogger().setLevel(logging.DEBUG) logging.getLogger('fs.tahoelafs').addHandler(logging.StreamHandler(sys.stdout)) WEBAPI = 'http://insecure.tahoe-lafs.org' # The public grid is too slow for threading testcases, disabling for now... class TestTahoeLAFS(unittest.TestCase,FSTestCases):#,ThreadingTestCases): # Disabled by default because it takes a *really* long time. __test__ = False def setUp(self):
def tearDown(self): self.fs.close() def test_dircap(self): # Is dircap in correct format? self.assert_(self.dircap.startswith('URI:DIR2:') and len(self.dircap) > 50) def test_concurrent_copydir(self): # makedir() on TahoeLAFS is currently not atomic pass def test_makedir_winner(self): # makedir() on TahoeLAFS is currently not atomic pass def test_big_file(self): pass if __name__ == '__main__': unittest.main()
self.dircap = TahoeLAFS.createdircap(WEBAPI) self.fs = TahoeLAFS(self.dircap, cache_timeout=0, webapi=WEBAPI)
identifier_body
test_tahoelafs.py
#!/usr/bin/python """ Test the TahoeLAFS @author: Marek Palatinus <marek@palatinus.cz> """ import sys import logging import unittest from fs.base import FS import fs.errors as errors from fs.tests import FSTestCases, ThreadingTestCases from fs.contrib.tahoelafs import TahoeLAFS, Connection logging.getLogger().setLevel(logging.DEBUG) logging.getLogger('fs.tahoelafs').addHandler(logging.StreamHandler(sys.stdout)) WEBAPI = 'http://insecure.tahoe-lafs.org' # The public grid is too slow for threading testcases, disabling for now... class TestTahoeLAFS(unittest.TestCase,FSTestCases):#,ThreadingTestCases): # Disabled by default because it takes a *really* long time. __test__ = False def setUp(self): self.dircap = TahoeLAFS.createdircap(WEBAPI) self.fs = TahoeLAFS(self.dircap, cache_timeout=0, webapi=WEBAPI) def tearDown(self): self.fs.close() def test_dircap(self): # Is dircap in correct format? self.assert_(self.dircap.startswith('URI:DIR2:') and len(self.dircap) > 50) def test_concurrent_copydir(self): # makedir() on TahoeLAFS is currently not atomic pass def test_makedir_winner(self): # makedir() on TahoeLAFS is currently not atomic pass def test_big_file(self): pass if __name__ == '__main__':
unittest.main()
conditional_block
test_tahoelafs.py
#!/usr/bin/python """ Test the TahoeLAFS @author: Marek Palatinus <marek@palatinus.cz> """ import sys import logging import unittest from fs.base import FS import fs.errors as errors from fs.tests import FSTestCases, ThreadingTestCases from fs.contrib.tahoelafs import TahoeLAFS, Connection logging.getLogger().setLevel(logging.DEBUG) logging.getLogger('fs.tahoelafs').addHandler(logging.StreamHandler(sys.stdout)) WEBAPI = 'http://insecure.tahoe-lafs.org' # The public grid is too slow for threading testcases, disabling for now... class TestTahoeLAFS(unittest.TestCase,FSTestCases):#,ThreadingTestCases): # Disabled by default because it takes a *really* long time. __test__ = False def setUp(self): self.dircap = TahoeLAFS.createdircap(WEBAPI) self.fs = TahoeLAFS(self.dircap, cache_timeout=0, webapi=WEBAPI) def tearDown(self): self.fs.close() def test_dircap(self): # Is dircap in correct format? self.assert_(self.dircap.startswith('URI:DIR2:') and len(self.dircap) > 50) def test_concurrent_copydir(self): # makedir() on TahoeLAFS is currently not atomic pass def test_makedir_winner(self): # makedir() on TahoeLAFS is currently not atomic pass def
(self): pass if __name__ == '__main__': unittest.main()
test_big_file
identifier_name
test_tahoelafs.py
#!/usr/bin/python """ Test the TahoeLAFS @author: Marek Palatinus <marek@palatinus.cz> """ import sys import logging import unittest from fs.base import FS import fs.errors as errors from fs.tests import FSTestCases, ThreadingTestCases from fs.contrib.tahoelafs import TahoeLAFS, Connection logging.getLogger().setLevel(logging.DEBUG) logging.getLogger('fs.tahoelafs').addHandler(logging.StreamHandler(sys.stdout)) WEBAPI = 'http://insecure.tahoe-lafs.org' # The public grid is too slow for threading testcases, disabling for now... class TestTahoeLAFS(unittest.TestCase,FSTestCases):#,ThreadingTestCases): # Disabled by default because it takes a *really* long time. __test__ = False def setUp(self): self.dircap = TahoeLAFS.createdircap(WEBAPI) self.fs = TahoeLAFS(self.dircap, cache_timeout=0, webapi=WEBAPI) def tearDown(self): self.fs.close() def test_dircap(self): # Is dircap in correct format? self.assert_(self.dircap.startswith('URI:DIR2:') and len(self.dircap) > 50) def test_concurrent_copydir(self): # makedir() on TahoeLAFS is currently not atomic pass def test_makedir_winner(self): # makedir() on TahoeLAFS is currently not atomic pass
def test_big_file(self): pass if __name__ == '__main__': unittest.main()
random_line_split
models.py
from django.db import models from django.core.exceptions import ValidationError from django.db.models.fields.related import ForeignObject try: from django.db.models.fields.related_descriptors import ForwardManyToOneDescriptor except ImportError: from django.db.models.fields.related import ReverseSingleRelatedObjectDescriptor as ForwardManyToOneDescriptor from django.utils.encoding import python_2_unicode_compatible import logging logger = logging.getLogger(__name__) # Python 3 fixes. import sys if sys.version > '3': long = int basestring = (str, bytes) unicode = str __all__ = ['Country', 'State', 'Locality', 'Address', 'AddressField'] class InconsistentDictError(Exception): pass def _to_python(value): raw = value.get('raw', '') country = value.get('country', '') country_code = value.get('country_code', '') state = value.get('state', '') state_code = value.get('state_code', '') locality = value.get('locality', '') postal_code = value.get('postal_code', '') street_number = value.get('street_number', '') route = value.get('route', '') formatted = value.get('formatted', '') latitude = value.get('latitude', None) longitude = value.get('longitude', None) # If there is no value (empty raw) then return None. if not raw: return None # If we have an inconsistent set of value bail out now. if (country or state or locality) and not (country and state and locality): raise InconsistentDictError # Handle the country. try: country_obj = Country.objects.get(name=country) except Country.DoesNotExist: if country: if len(country_code) > Country._meta.get_field('code').max_length: if country_code != country: raise ValueError('Invalid country code (too long): %s'%country_code) country_code = '' country_obj = Country.objects.create(name=country, code=country_code) else: country_obj = None # Handle the state. try: state_obj = State.objects.get(name=state, country=country_obj) except State.DoesNotExist: if state: if len(state_code) > State._meta.get_field('code').max_length: if state_code != state: raise ValueError('Invalid state code (too long): %s'%state_code) state_code = '' state_obj = State.objects.create(name=state, code=state_code, country=country_obj) else: state_obj = None # Handle the locality. try: locality_obj = Locality.objects.get(name=locality, state=state_obj) except Locality.DoesNotExist: if locality: locality_obj = Locality.objects.create(name=locality, postal_code=postal_code, state=state_obj) else: locality_obj = None # Handle the address. try: if not (street_number or route or locality): address_obj = Address.objects.get(raw=raw) else: address_obj = Address.objects.get( street_number=street_number, route=route, locality=locality_obj ) except Address.DoesNotExist: address_obj = Address( street_number=street_number, route=route, raw=raw, locality=locality_obj, formatted=formatted, latitude=latitude, longitude=longitude, ) # If "formatted" is empty try to construct it from other values. if not address_obj.formatted: address_obj.formatted = unicode(address_obj) # Need to save. address_obj.save() # Done. return address_obj ## ## Convert a dictionary to an address. ## def to_python(value): # Keep `None`s. if value is None: return None # Is it already an address object? if isinstance(value, Address): return value # If we have an integer, assume it is a model primary key. This is mostly for # Django being a cunt. elif isinstance(value, (int, long)): return value # A string is considered a raw value. elif isinstance(value, basestring): obj = Address(raw=value) obj.save() return obj # A dictionary of named address components. elif isinstance(value, dict): # Attempt a conversion. try: return _to_python(value) except InconsistentDictError: return Address.objects.create(raw=value['raw']) # Not in any of the formats I recognise. raise ValidationError('Invalid address value.') ## ## A country. ## @python_2_unicode_compatible class Country(models.Model): name = models.CharField(max_length=40, unique=True, blank=True) code = models.CharField(max_length=2, blank=True) # not unique as there are duplicates (IT) class Meta: verbose_name_plural = 'Countries' ordering = ('name',) def __str__(self): return '%s'%(self.name or self.code) ## ## A state. Google refers to this as `administration_level_1`. ## @python_2_unicode_compatible class State(models.Model): name = models.CharField(max_length=165, blank=True) code = models.CharField(max_length=3, blank=True) country = models.ForeignKey(Country, related_name='states') class Meta: unique_together = ('name', 'country') ordering = ('country', 'name') def __str__(self): txt = self.to_str() country = '%s'%self.country if country and txt: txt += ', ' txt += country return txt def to_str(self): return '%s'%(self.name or self.code) ## ## A locality (suburb). ## @python_2_unicode_compatible class Locality(models.Model): name = models.CharField(max_length=165, blank=True) postal_code = models.CharField(max_length=10, blank=True) state = models.ForeignKey(State, related_name='localities') class Meta: verbose_name_plural = 'Localities' unique_together = ('name', 'state') ordering = ('state', 'name') def __str__(self): txt = '%s'%self.name state = self.state.to_str() if self.state else '' if txt and state: txt += ', ' txt += state if self.postal_code: txt += ' %s'%self.postal_code cntry = '%s'%(self.state.country if self.state and self.state.country else '') if cntry: txt += ', %s'%cntry return txt ## ## An address. If for any reason we are unable to find a matching ## decomposed address we will store the raw address string in `raw`. ## @python_2_unicode_compatible class Address(models.Model): street_number = models.CharField(max_length=20, blank=True) route = models.CharField(max_length=100, blank=True) locality = models.ForeignKey(Locality, related_name='addresses', blank=True, null=True) raw = models.CharField(max_length=200) formatted = models.CharField(max_length=200, blank=True) latitude = models.FloatField(blank=True, null=True) longitude = models.FloatField(blank=True, null=True) class Meta: verbose_name_plural = 'Addresses' ordering = ('locality', 'route', 'street_number') # unique_together = ('locality', 'route', 'street_number') def
(self): if self.formatted != '': txt = '%s'%self.formatted elif self.locality: txt = '' if self.street_number: txt = '%s'%self.street_number if self.route: if txt: txt += ' %s'%self.route locality = '%s'%self.locality if txt and locality: txt += ', ' txt += locality else: txt = '%s'%self.raw return txt def clean(self): if not self.raw: raise ValidationError('Addresses may not have a blank `raw` field.') def as_dict(self): ad = dict( street_number=self.street_number, route=self.route, raw=self.raw, formatted=self.formatted, latitude=self.latitude if self.latitude else '', longitude=self.longitude if self.longitude else '', ) if self.locality: ad['locality'] = self.locality.name ad['postal_code'] = self.locality.postal_code if self.locality.state: ad['state'] = self.locality.state.name ad['state_code'] = self.locality.state.code if self.locality.state.country: ad['country'] = self.locality.state.country.name ad['country_code'] = self.locality.state.country.code return ad class AddressDescriptor(ForwardManyToOneDescriptor): def __set__(self, inst, value): super(AddressDescriptor, self).__set__(inst, to_python(value)) ## ## A field for addresses in other models. ## class AddressField(models.ForeignKey): description = 'An address' def __init__(self, **kwargs): kwargs['to'] = 'address.Address' super(AddressField, self).__init__(**kwargs) def contribute_to_class(self, cls, name, virtual_only=False): super(ForeignObject, self).contribute_to_class(cls, name, virtual_only=virtual_only) setattr(cls, self.name, AddressDescriptor(self)) # def deconstruct(self): # name, path, args, kwargs = super(AddressField, self).deconstruct() # del kwargs['to'] # return name, path, args, kwargs def formfield(self, **kwargs): from .forms import AddressField as AddressFormField defaults = dict(form_class=AddressFormField) defaults.update(kwargs) return super(AddressField, self).formfield(**defaults)
__str__
identifier_name
models.py
from django.db import models from django.core.exceptions import ValidationError from django.db.models.fields.related import ForeignObject try: from django.db.models.fields.related_descriptors import ForwardManyToOneDescriptor except ImportError: from django.db.models.fields.related import ReverseSingleRelatedObjectDescriptor as ForwardManyToOneDescriptor from django.utils.encoding import python_2_unicode_compatible import logging logger = logging.getLogger(__name__) # Python 3 fixes. import sys if sys.version > '3': long = int basestring = (str, bytes) unicode = str __all__ = ['Country', 'State', 'Locality', 'Address', 'AddressField'] class InconsistentDictError(Exception): pass def _to_python(value): raw = value.get('raw', '') country = value.get('country', '') country_code = value.get('country_code', '') state = value.get('state', '') state_code = value.get('state_code', '') locality = value.get('locality', '') postal_code = value.get('postal_code', '') street_number = value.get('street_number', '') route = value.get('route', '') formatted = value.get('formatted', '') latitude = value.get('latitude', None) longitude = value.get('longitude', None) # If there is no value (empty raw) then return None. if not raw: return None # If we have an inconsistent set of value bail out now. if (country or state or locality) and not (country and state and locality): raise InconsistentDictError # Handle the country. try: country_obj = Country.objects.get(name=country) except Country.DoesNotExist: if country: if len(country_code) > Country._meta.get_field('code').max_length: if country_code != country: raise ValueError('Invalid country code (too long): %s'%country_code) country_code = '' country_obj = Country.objects.create(name=country, code=country_code) else: country_obj = None # Handle the state. try: state_obj = State.objects.get(name=state, country=country_obj) except State.DoesNotExist: if state:
else: state_obj = None # Handle the locality. try: locality_obj = Locality.objects.get(name=locality, state=state_obj) except Locality.DoesNotExist: if locality: locality_obj = Locality.objects.create(name=locality, postal_code=postal_code, state=state_obj) else: locality_obj = None # Handle the address. try: if not (street_number or route or locality): address_obj = Address.objects.get(raw=raw) else: address_obj = Address.objects.get( street_number=street_number, route=route, locality=locality_obj ) except Address.DoesNotExist: address_obj = Address( street_number=street_number, route=route, raw=raw, locality=locality_obj, formatted=formatted, latitude=latitude, longitude=longitude, ) # If "formatted" is empty try to construct it from other values. if not address_obj.formatted: address_obj.formatted = unicode(address_obj) # Need to save. address_obj.save() # Done. return address_obj ## ## Convert a dictionary to an address. ## def to_python(value): # Keep `None`s. if value is None: return None # Is it already an address object? if isinstance(value, Address): return value # If we have an integer, assume it is a model primary key. This is mostly for # Django being a cunt. elif isinstance(value, (int, long)): return value # A string is considered a raw value. elif isinstance(value, basestring): obj = Address(raw=value) obj.save() return obj # A dictionary of named address components. elif isinstance(value, dict): # Attempt a conversion. try: return _to_python(value) except InconsistentDictError: return Address.objects.create(raw=value['raw']) # Not in any of the formats I recognise. raise ValidationError('Invalid address value.') ## ## A country. ## @python_2_unicode_compatible class Country(models.Model): name = models.CharField(max_length=40, unique=True, blank=True) code = models.CharField(max_length=2, blank=True) # not unique as there are duplicates (IT) class Meta: verbose_name_plural = 'Countries' ordering = ('name',) def __str__(self): return '%s'%(self.name or self.code) ## ## A state. Google refers to this as `administration_level_1`. ## @python_2_unicode_compatible class State(models.Model): name = models.CharField(max_length=165, blank=True) code = models.CharField(max_length=3, blank=True) country = models.ForeignKey(Country, related_name='states') class Meta: unique_together = ('name', 'country') ordering = ('country', 'name') def __str__(self): txt = self.to_str() country = '%s'%self.country if country and txt: txt += ', ' txt += country return txt def to_str(self): return '%s'%(self.name or self.code) ## ## A locality (suburb). ## @python_2_unicode_compatible class Locality(models.Model): name = models.CharField(max_length=165, blank=True) postal_code = models.CharField(max_length=10, blank=True) state = models.ForeignKey(State, related_name='localities') class Meta: verbose_name_plural = 'Localities' unique_together = ('name', 'state') ordering = ('state', 'name') def __str__(self): txt = '%s'%self.name state = self.state.to_str() if self.state else '' if txt and state: txt += ', ' txt += state if self.postal_code: txt += ' %s'%self.postal_code cntry = '%s'%(self.state.country if self.state and self.state.country else '') if cntry: txt += ', %s'%cntry return txt ## ## An address. If for any reason we are unable to find a matching ## decomposed address we will store the raw address string in `raw`. ## @python_2_unicode_compatible class Address(models.Model): street_number = models.CharField(max_length=20, blank=True) route = models.CharField(max_length=100, blank=True) locality = models.ForeignKey(Locality, related_name='addresses', blank=True, null=True) raw = models.CharField(max_length=200) formatted = models.CharField(max_length=200, blank=True) latitude = models.FloatField(blank=True, null=True) longitude = models.FloatField(blank=True, null=True) class Meta: verbose_name_plural = 'Addresses' ordering = ('locality', 'route', 'street_number') # unique_together = ('locality', 'route', 'street_number') def __str__(self): if self.formatted != '': txt = '%s'%self.formatted elif self.locality: txt = '' if self.street_number: txt = '%s'%self.street_number if self.route: if txt: txt += ' %s'%self.route locality = '%s'%self.locality if txt and locality: txt += ', ' txt += locality else: txt = '%s'%self.raw return txt def clean(self): if not self.raw: raise ValidationError('Addresses may not have a blank `raw` field.') def as_dict(self): ad = dict( street_number=self.street_number, route=self.route, raw=self.raw, formatted=self.formatted, latitude=self.latitude if self.latitude else '', longitude=self.longitude if self.longitude else '', ) if self.locality: ad['locality'] = self.locality.name ad['postal_code'] = self.locality.postal_code if self.locality.state: ad['state'] = self.locality.state.name ad['state_code'] = self.locality.state.code if self.locality.state.country: ad['country'] = self.locality.state.country.name ad['country_code'] = self.locality.state.country.code return ad class AddressDescriptor(ForwardManyToOneDescriptor): def __set__(self, inst, value): super(AddressDescriptor, self).__set__(inst, to_python(value)) ## ## A field for addresses in other models. ## class AddressField(models.ForeignKey): description = 'An address' def __init__(self, **kwargs): kwargs['to'] = 'address.Address' super(AddressField, self).__init__(**kwargs) def contribute_to_class(self, cls, name, virtual_only=False): super(ForeignObject, self).contribute_to_class(cls, name, virtual_only=virtual_only) setattr(cls, self.name, AddressDescriptor(self)) # def deconstruct(self): # name, path, args, kwargs = super(AddressField, self).deconstruct() # del kwargs['to'] # return name, path, args, kwargs def formfield(self, **kwargs): from .forms import AddressField as AddressFormField defaults = dict(form_class=AddressFormField) defaults.update(kwargs) return super(AddressField, self).formfield(**defaults)
if len(state_code) > State._meta.get_field('code').max_length: if state_code != state: raise ValueError('Invalid state code (too long): %s'%state_code) state_code = '' state_obj = State.objects.create(name=state, code=state_code, country=country_obj)
conditional_block
models.py
from django.db import models from django.core.exceptions import ValidationError from django.db.models.fields.related import ForeignObject try: from django.db.models.fields.related_descriptors import ForwardManyToOneDescriptor except ImportError: from django.db.models.fields.related import ReverseSingleRelatedObjectDescriptor as ForwardManyToOneDescriptor from django.utils.encoding import python_2_unicode_compatible import logging logger = logging.getLogger(__name__) # Python 3 fixes. import sys if sys.version > '3': long = int basestring = (str, bytes) unicode = str __all__ = ['Country', 'State', 'Locality', 'Address', 'AddressField'] class InconsistentDictError(Exception): pass def _to_python(value): raw = value.get('raw', '') country = value.get('country', '') country_code = value.get('country_code', '') state = value.get('state', '') state_code = value.get('state_code', '') locality = value.get('locality', '') postal_code = value.get('postal_code', '') street_number = value.get('street_number', '') route = value.get('route', '') formatted = value.get('formatted', '') latitude = value.get('latitude', None) longitude = value.get('longitude', None) # If there is no value (empty raw) then return None. if not raw: return None # If we have an inconsistent set of value bail out now. if (country or state or locality) and not (country and state and locality): raise InconsistentDictError # Handle the country. try: country_obj = Country.objects.get(name=country) except Country.DoesNotExist: if country: if len(country_code) > Country._meta.get_field('code').max_length: if country_code != country: raise ValueError('Invalid country code (too long): %s'%country_code) country_code = '' country_obj = Country.objects.create(name=country, code=country_code) else: country_obj = None # Handle the state. try: state_obj = State.objects.get(name=state, country=country_obj) except State.DoesNotExist: if state: if len(state_code) > State._meta.get_field('code').max_length: if state_code != state: raise ValueError('Invalid state code (too long): %s'%state_code) state_code = '' state_obj = State.objects.create(name=state, code=state_code, country=country_obj) else: state_obj = None # Handle the locality. try: locality_obj = Locality.objects.get(name=locality, state=state_obj) except Locality.DoesNotExist: if locality: locality_obj = Locality.objects.create(name=locality, postal_code=postal_code, state=state_obj) else: locality_obj = None # Handle the address. try: if not (street_number or route or locality): address_obj = Address.objects.get(raw=raw) else: address_obj = Address.objects.get( street_number=street_number, route=route, locality=locality_obj ) except Address.DoesNotExist: address_obj = Address( street_number=street_number, route=route, raw=raw, locality=locality_obj, formatted=formatted, latitude=latitude, longitude=longitude, ) # If "formatted" is empty try to construct it from other values. if not address_obj.formatted: address_obj.formatted = unicode(address_obj) # Need to save. address_obj.save() # Done. return address_obj ## ## Convert a dictionary to an address. ## def to_python(value): # Keep `None`s. if value is None: return None # Is it already an address object? if isinstance(value, Address): return value # If we have an integer, assume it is a model primary key. This is mostly for # Django being a cunt. elif isinstance(value, (int, long)): return value # A string is considered a raw value. elif isinstance(value, basestring): obj = Address(raw=value) obj.save() return obj # A dictionary of named address components. elif isinstance(value, dict): # Attempt a conversion. try: return _to_python(value) except InconsistentDictError: return Address.objects.create(raw=value['raw']) # Not in any of the formats I recognise. raise ValidationError('Invalid address value.') ## ## A country. ## @python_2_unicode_compatible class Country(models.Model): name = models.CharField(max_length=40, unique=True, blank=True) code = models.CharField(max_length=2, blank=True) # not unique as there are duplicates (IT) class Meta: verbose_name_plural = 'Countries' ordering = ('name',) def __str__(self): return '%s'%(self.name or self.code) ## ## A state. Google refers to this as `administration_level_1`. ## @python_2_unicode_compatible class State(models.Model): name = models.CharField(max_length=165, blank=True) code = models.CharField(max_length=3, blank=True) country = models.ForeignKey(Country, related_name='states') class Meta: unique_together = ('name', 'country') ordering = ('country', 'name') def __str__(self): txt = self.to_str() country = '%s'%self.country if country and txt: txt += ', ' txt += country return txt def to_str(self): return '%s'%(self.name or self.code) ## ## A locality (suburb). ## @python_2_unicode_compatible class Locality(models.Model): name = models.CharField(max_length=165, blank=True) postal_code = models.CharField(max_length=10, blank=True) state = models.ForeignKey(State, related_name='localities') class Meta:
def __str__(self): txt = '%s'%self.name state = self.state.to_str() if self.state else '' if txt and state: txt += ', ' txt += state if self.postal_code: txt += ' %s'%self.postal_code cntry = '%s'%(self.state.country if self.state and self.state.country else '') if cntry: txt += ', %s'%cntry return txt ## ## An address. If for any reason we are unable to find a matching ## decomposed address we will store the raw address string in `raw`. ## @python_2_unicode_compatible class Address(models.Model): street_number = models.CharField(max_length=20, blank=True) route = models.CharField(max_length=100, blank=True) locality = models.ForeignKey(Locality, related_name='addresses', blank=True, null=True) raw = models.CharField(max_length=200) formatted = models.CharField(max_length=200, blank=True) latitude = models.FloatField(blank=True, null=True) longitude = models.FloatField(blank=True, null=True) class Meta: verbose_name_plural = 'Addresses' ordering = ('locality', 'route', 'street_number') # unique_together = ('locality', 'route', 'street_number') def __str__(self): if self.formatted != '': txt = '%s'%self.formatted elif self.locality: txt = '' if self.street_number: txt = '%s'%self.street_number if self.route: if txt: txt += ' %s'%self.route locality = '%s'%self.locality if txt and locality: txt += ', ' txt += locality else: txt = '%s'%self.raw return txt def clean(self): if not self.raw: raise ValidationError('Addresses may not have a blank `raw` field.') def as_dict(self): ad = dict( street_number=self.street_number, route=self.route, raw=self.raw, formatted=self.formatted, latitude=self.latitude if self.latitude else '', longitude=self.longitude if self.longitude else '', ) if self.locality: ad['locality'] = self.locality.name ad['postal_code'] = self.locality.postal_code if self.locality.state: ad['state'] = self.locality.state.name ad['state_code'] = self.locality.state.code if self.locality.state.country: ad['country'] = self.locality.state.country.name ad['country_code'] = self.locality.state.country.code return ad class AddressDescriptor(ForwardManyToOneDescriptor): def __set__(self, inst, value): super(AddressDescriptor, self).__set__(inst, to_python(value)) ## ## A field for addresses in other models. ## class AddressField(models.ForeignKey): description = 'An address' def __init__(self, **kwargs): kwargs['to'] = 'address.Address' super(AddressField, self).__init__(**kwargs) def contribute_to_class(self, cls, name, virtual_only=False): super(ForeignObject, self).contribute_to_class(cls, name, virtual_only=virtual_only) setattr(cls, self.name, AddressDescriptor(self)) # def deconstruct(self): # name, path, args, kwargs = super(AddressField, self).deconstruct() # del kwargs['to'] # return name, path, args, kwargs def formfield(self, **kwargs): from .forms import AddressField as AddressFormField defaults = dict(form_class=AddressFormField) defaults.update(kwargs) return super(AddressField, self).formfield(**defaults)
verbose_name_plural = 'Localities' unique_together = ('name', 'state') ordering = ('state', 'name')
identifier_body
models.py
from django.db import models from django.core.exceptions import ValidationError from django.db.models.fields.related import ForeignObject try: from django.db.models.fields.related_descriptors import ForwardManyToOneDescriptor except ImportError: from django.db.models.fields.related import ReverseSingleRelatedObjectDescriptor as ForwardManyToOneDescriptor from django.utils.encoding import python_2_unicode_compatible import logging logger = logging.getLogger(__name__) # Python 3 fixes. import sys if sys.version > '3': long = int basestring = (str, bytes) unicode = str __all__ = ['Country', 'State', 'Locality', 'Address', 'AddressField'] class InconsistentDictError(Exception): pass def _to_python(value): raw = value.get('raw', '') country = value.get('country', '') country_code = value.get('country_code', '') state = value.get('state', '') state_code = value.get('state_code', '') locality = value.get('locality', '') postal_code = value.get('postal_code', '') street_number = value.get('street_number', '') route = value.get('route', '') formatted = value.get('formatted', '') latitude = value.get('latitude', None) longitude = value.get('longitude', None) # If there is no value (empty raw) then return None. if not raw: return None # If we have an inconsistent set of value bail out now. if (country or state or locality) and not (country and state and locality): raise InconsistentDictError # Handle the country. try: country_obj = Country.objects.get(name=country) except Country.DoesNotExist: if country: if len(country_code) > Country._meta.get_field('code').max_length: if country_code != country: raise ValueError('Invalid country code (too long): %s'%country_code) country_code = '' country_obj = Country.objects.create(name=country, code=country_code) else: country_obj = None # Handle the state. try: state_obj = State.objects.get(name=state, country=country_obj) except State.DoesNotExist: if state: if len(state_code) > State._meta.get_field('code').max_length: if state_code != state: raise ValueError('Invalid state code (too long): %s'%state_code) state_code = '' state_obj = State.objects.create(name=state, code=state_code, country=country_obj) else: state_obj = None # Handle the locality. try: locality_obj = Locality.objects.get(name=locality, state=state_obj) except Locality.DoesNotExist: if locality: locality_obj = Locality.objects.create(name=locality, postal_code=postal_code, state=state_obj) else: locality_obj = None # Handle the address. try: if not (street_number or route or locality): address_obj = Address.objects.get(raw=raw) else: address_obj = Address.objects.get( street_number=street_number, route=route, locality=locality_obj ) except Address.DoesNotExist: address_obj = Address( street_number=street_number, route=route, raw=raw, locality=locality_obj, formatted=formatted, latitude=latitude, longitude=longitude,
if not address_obj.formatted: address_obj.formatted = unicode(address_obj) # Need to save. address_obj.save() # Done. return address_obj ## ## Convert a dictionary to an address. ## def to_python(value): # Keep `None`s. if value is None: return None # Is it already an address object? if isinstance(value, Address): return value # If we have an integer, assume it is a model primary key. This is mostly for # Django being a cunt. elif isinstance(value, (int, long)): return value # A string is considered a raw value. elif isinstance(value, basestring): obj = Address(raw=value) obj.save() return obj # A dictionary of named address components. elif isinstance(value, dict): # Attempt a conversion. try: return _to_python(value) except InconsistentDictError: return Address.objects.create(raw=value['raw']) # Not in any of the formats I recognise. raise ValidationError('Invalid address value.') ## ## A country. ## @python_2_unicode_compatible class Country(models.Model): name = models.CharField(max_length=40, unique=True, blank=True) code = models.CharField(max_length=2, blank=True) # not unique as there are duplicates (IT) class Meta: verbose_name_plural = 'Countries' ordering = ('name',) def __str__(self): return '%s'%(self.name or self.code) ## ## A state. Google refers to this as `administration_level_1`. ## @python_2_unicode_compatible class State(models.Model): name = models.CharField(max_length=165, blank=True) code = models.CharField(max_length=3, blank=True) country = models.ForeignKey(Country, related_name='states') class Meta: unique_together = ('name', 'country') ordering = ('country', 'name') def __str__(self): txt = self.to_str() country = '%s'%self.country if country and txt: txt += ', ' txt += country return txt def to_str(self): return '%s'%(self.name or self.code) ## ## A locality (suburb). ## @python_2_unicode_compatible class Locality(models.Model): name = models.CharField(max_length=165, blank=True) postal_code = models.CharField(max_length=10, blank=True) state = models.ForeignKey(State, related_name='localities') class Meta: verbose_name_plural = 'Localities' unique_together = ('name', 'state') ordering = ('state', 'name') def __str__(self): txt = '%s'%self.name state = self.state.to_str() if self.state else '' if txt and state: txt += ', ' txt += state if self.postal_code: txt += ' %s'%self.postal_code cntry = '%s'%(self.state.country if self.state and self.state.country else '') if cntry: txt += ', %s'%cntry return txt ## ## An address. If for any reason we are unable to find a matching ## decomposed address we will store the raw address string in `raw`. ## @python_2_unicode_compatible class Address(models.Model): street_number = models.CharField(max_length=20, blank=True) route = models.CharField(max_length=100, blank=True) locality = models.ForeignKey(Locality, related_name='addresses', blank=True, null=True) raw = models.CharField(max_length=200) formatted = models.CharField(max_length=200, blank=True) latitude = models.FloatField(blank=True, null=True) longitude = models.FloatField(blank=True, null=True) class Meta: verbose_name_plural = 'Addresses' ordering = ('locality', 'route', 'street_number') # unique_together = ('locality', 'route', 'street_number') def __str__(self): if self.formatted != '': txt = '%s'%self.formatted elif self.locality: txt = '' if self.street_number: txt = '%s'%self.street_number if self.route: if txt: txt += ' %s'%self.route locality = '%s'%self.locality if txt and locality: txt += ', ' txt += locality else: txt = '%s'%self.raw return txt def clean(self): if not self.raw: raise ValidationError('Addresses may not have a blank `raw` field.') def as_dict(self): ad = dict( street_number=self.street_number, route=self.route, raw=self.raw, formatted=self.formatted, latitude=self.latitude if self.latitude else '', longitude=self.longitude if self.longitude else '', ) if self.locality: ad['locality'] = self.locality.name ad['postal_code'] = self.locality.postal_code if self.locality.state: ad['state'] = self.locality.state.name ad['state_code'] = self.locality.state.code if self.locality.state.country: ad['country'] = self.locality.state.country.name ad['country_code'] = self.locality.state.country.code return ad class AddressDescriptor(ForwardManyToOneDescriptor): def __set__(self, inst, value): super(AddressDescriptor, self).__set__(inst, to_python(value)) ## ## A field for addresses in other models. ## class AddressField(models.ForeignKey): description = 'An address' def __init__(self, **kwargs): kwargs['to'] = 'address.Address' super(AddressField, self).__init__(**kwargs) def contribute_to_class(self, cls, name, virtual_only=False): super(ForeignObject, self).contribute_to_class(cls, name, virtual_only=virtual_only) setattr(cls, self.name, AddressDescriptor(self)) # def deconstruct(self): # name, path, args, kwargs = super(AddressField, self).deconstruct() # del kwargs['to'] # return name, path, args, kwargs def formfield(self, **kwargs): from .forms import AddressField as AddressFormField defaults = dict(form_class=AddressFormField) defaults.update(kwargs) return super(AddressField, self).formfield(**defaults)
) # If "formatted" is empty try to construct it from other values.
random_line_split
utils.py
# -*- coding: utf-8 -*- # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- import array from hashlib import md5 import os import platform import sys PY2 = sys.version_info.major == 2 WIN = platform.system() == 'Windows' if WIN: datadir = os.path.join(os.environ['APPDATA'], 'azure-datalake-store') else: datadir = os.sep.join([os.path.expanduser("~"), '.config', 'azure-datalake-store']) try: os.makedirs(datadir) except: pass def ensure_writable(b): if PY2 and isinstance(b, array.array): return b.tostring() return b def write_stdout(data): """ Write bytes or strings to standard output """ try: sys.stdout.buffer.write(data) except AttributeError: sys.stdout.write(data.decode('ascii', 'replace')) def read_block(f, offset, length, delimiter=None): """ Read a block of bytes from a file Parameters ---------- fn: file object a file object that supports seek, tell and read. offset: int Byte offset to start read length: int Maximum number of bytes to read delimiter: bytes (optional) Ensure reading stops at delimiter bytestring If using the ``delimiter=`` keyword argument we ensure that the read stops at or before the delimiter boundaries that follow the location ``offset + length``. For ADL, if no delimiter is found and the data requested is > 4MB an exception is raised, since a single record cannot exceed 4MB and be guaranteed to land contiguously in ADL. The bytestring returned WILL include the terminating delimiter string. Examples -------- >>> from io import BytesIO # doctest: +SKIP >>> f = BytesIO(b'Alice, 100\\nBob, 200\\nCharlie, 300') # doctest: +SKIP >>> read_block(f, 0, 13) # doctest: +SKIP b'Alice, 100\\nBo' >>> read_block(f, 0, 13, delimiter=b'\\n') # doctest: +SKIP b'Alice, 100\\n' >>> read_block(f, 10, 10, delimiter=b'\\n') # doctest: +SKIP b'\\nCharlie, 300' >>> f = BytesIO(bytearray(2**22)) # doctest: +SKIP >>> read_block(f,0,2**22, delimiter=b'\\n') # doctest: +SKIP IndexError: No delimiter found within max record size of 4MB. Transfer without specifying a delimiter (as binary) instead. """ f.seek(offset) bytes = f.read(length) if delimiter: # max record size is 4MB max_record = 2**22 if length > max_record: raise IndexError('Records larger than ' + str(max_record) + ' bytes are not supported. The length requested was: ' + str(length) + 'bytes') # get the last index of the delimiter if it exists try: last_delim_index = len(bytes) -1 - bytes[::-1].index(delimiter) # this ensures the length includes all of the last delimiter (in the event that it is more than one character) length = last_delim_index + len(delimiter) return bytes[0:length] except ValueError: # TODO: Before delimters can be supported through the ADLUploader logic, the number of chunks being uploaded # needs to be visible to this method, since it needs to throw if: # 1. We cannot find a delimiter in <= 4MB of data # 2. If the remaining size is less than 4MB but there are multiple chunks that need to be stitched together, # since the delimiter could be split across chunks. # 3. If delimiters are specified, there must be logic during segment determination that ensures all chunks # terminate at the end of a record (on a new line), even if that makes the chunk < 256MB. if length >= max_record: raise IndexError('No delimiter found within max record size of ' + str(max_record) + ' bytes. Transfer without specifying a delimiter (as binary) instead.') return bytes def tokenize(*args, **kwargs):
def commonprefix(paths): """ Find common directory for all paths Python's ``os.path.commonprefix`` will not return a valid directory path in some cases, so we wrote this convenience method. Examples -------- >>> # os.path.commonprefix returns '/disk1/foo' >>> commonprefix(['/disk1/foobar', '/disk1/foobaz']) '/disk1' >>> commonprefix(['a/b/c', 'a/b/d', 'a/c/d']) 'a' >>> commonprefix(['a/b/c', 'd/e/f', 'g/h/i']) '' """ return os.path.dirname(os.path.commonprefix(paths)) def clamp(n, smallest, largest): """ Limit a value to a given range This is equivalent to smallest <= n <= largest. Examples -------- >>> clamp(0, 1, 100) 1 >>> clamp(42, 2, 128) 42 >>> clamp(1024, 1, 32) 32 """ return max(smallest, min(n, largest))
""" Deterministic token >>> tokenize('Hello') == tokenize('Hello') True """ if kwargs: args = args + (kwargs,) return md5(str(tuple(args)).encode()).hexdigest()
identifier_body
utils.py
# -*- coding: utf-8 -*- # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- import array from hashlib import md5 import os import platform import sys PY2 = sys.version_info.major == 2 WIN = platform.system() == 'Windows' if WIN: datadir = os.path.join(os.environ['APPDATA'], 'azure-datalake-store') else: datadir = os.sep.join([os.path.expanduser("~"), '.config', 'azure-datalake-store']) try: os.makedirs(datadir) except: pass def ensure_writable(b): if PY2 and isinstance(b, array.array): return b.tostring() return b def write_stdout(data): """ Write bytes or strings to standard output """ try: sys.stdout.buffer.write(data) except AttributeError: sys.stdout.write(data.decode('ascii', 'replace')) def read_block(f, offset, length, delimiter=None): """ Read a block of bytes from a file Parameters ---------- fn: file object a file object that supports seek, tell and read. offset: int Byte offset to start read length: int Maximum number of bytes to read delimiter: bytes (optional) Ensure reading stops at delimiter bytestring If using the ``delimiter=`` keyword argument we ensure that the read stops at or before the delimiter boundaries that follow the location ``offset + length``. For ADL, if no delimiter is found and the data requested is > 4MB an exception is raised, since a single record cannot exceed 4MB and be guaranteed to land contiguously in ADL. The bytestring returned WILL include the terminating delimiter string. Examples -------- >>> from io import BytesIO # doctest: +SKIP >>> f = BytesIO(b'Alice, 100\\nBob, 200\\nCharlie, 300') # doctest: +SKIP >>> read_block(f, 0, 13) # doctest: +SKIP b'Alice, 100\\nBo' >>> read_block(f, 0, 13, delimiter=b'\\n') # doctest: +SKIP b'Alice, 100\\n' >>> read_block(f, 10, 10, delimiter=b'\\n') # doctest: +SKIP b'\\nCharlie, 300' >>> f = BytesIO(bytearray(2**22)) # doctest: +SKIP >>> read_block(f,0,2**22, delimiter=b'\\n') # doctest: +SKIP IndexError: No delimiter found within max record size of 4MB. Transfer without specifying a delimiter (as binary) instead. """ f.seek(offset) bytes = f.read(length) if delimiter: # max record size is 4MB
return bytes def tokenize(*args, **kwargs): """ Deterministic token >>> tokenize('Hello') == tokenize('Hello') True """ if kwargs: args = args + (kwargs,) return md5(str(tuple(args)).encode()).hexdigest() def commonprefix(paths): """ Find common directory for all paths Python's ``os.path.commonprefix`` will not return a valid directory path in some cases, so we wrote this convenience method. Examples -------- >>> # os.path.commonprefix returns '/disk1/foo' >>> commonprefix(['/disk1/foobar', '/disk1/foobaz']) '/disk1' >>> commonprefix(['a/b/c', 'a/b/d', 'a/c/d']) 'a' >>> commonprefix(['a/b/c', 'd/e/f', 'g/h/i']) '' """ return os.path.dirname(os.path.commonprefix(paths)) def clamp(n, smallest, largest): """ Limit a value to a given range This is equivalent to smallest <= n <= largest. Examples -------- >>> clamp(0, 1, 100) 1 >>> clamp(42, 2, 128) 42 >>> clamp(1024, 1, 32) 32 """ return max(smallest, min(n, largest))
max_record = 2**22 if length > max_record: raise IndexError('Records larger than ' + str(max_record) + ' bytes are not supported. The length requested was: ' + str(length) + 'bytes') # get the last index of the delimiter if it exists try: last_delim_index = len(bytes) -1 - bytes[::-1].index(delimiter) # this ensures the length includes all of the last delimiter (in the event that it is more than one character) length = last_delim_index + len(delimiter) return bytes[0:length] except ValueError: # TODO: Before delimters can be supported through the ADLUploader logic, the number of chunks being uploaded # needs to be visible to this method, since it needs to throw if: # 1. We cannot find a delimiter in <= 4MB of data # 2. If the remaining size is less than 4MB but there are multiple chunks that need to be stitched together, # since the delimiter could be split across chunks. # 3. If delimiters are specified, there must be logic during segment determination that ensures all chunks # terminate at the end of a record (on a new line), even if that makes the chunk < 256MB. if length >= max_record: raise IndexError('No delimiter found within max record size of ' + str(max_record) + ' bytes. Transfer without specifying a delimiter (as binary) instead.')
conditional_block
utils.py
# -*- coding: utf-8 -*- # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- import array from hashlib import md5 import os import platform import sys PY2 = sys.version_info.major == 2 WIN = platform.system() == 'Windows' if WIN: datadir = os.path.join(os.environ['APPDATA'], 'azure-datalake-store') else: datadir = os.sep.join([os.path.expanduser("~"), '.config', 'azure-datalake-store']) try: os.makedirs(datadir) except: pass def ensure_writable(b): if PY2 and isinstance(b, array.array): return b.tostring() return b def write_stdout(data): """ Write bytes or strings to standard output """ try: sys.stdout.buffer.write(data) except AttributeError: sys.stdout.write(data.decode('ascii', 'replace')) def read_block(f, offset, length, delimiter=None): """ Read a block of bytes from a file Parameters ---------- fn: file object a file object that supports seek, tell and read. offset: int Byte offset to start read length: int Maximum number of bytes to read delimiter: bytes (optional) Ensure reading stops at delimiter bytestring If using the ``delimiter=`` keyword argument we ensure that the read stops at or before the delimiter boundaries that follow the location ``offset + length``. For ADL, if no delimiter is found and the data requested is > 4MB an exception is raised, since a single record cannot exceed 4MB and be guaranteed to land contiguously in ADL. The bytestring returned WILL include the terminating delimiter string. Examples -------- >>> from io import BytesIO # doctest: +SKIP >>> f = BytesIO(b'Alice, 100\\nBob, 200\\nCharlie, 300') # doctest: +SKIP >>> read_block(f, 0, 13) # doctest: +SKIP b'Alice, 100\\nBo' >>> read_block(f, 0, 13, delimiter=b'\\n') # doctest: +SKIP b'Alice, 100\\n' >>> read_block(f, 10, 10, delimiter=b'\\n') # doctest: +SKIP b'\\nCharlie, 300' >>> f = BytesIO(bytearray(2**22)) # doctest: +SKIP >>> read_block(f,0,2**22, delimiter=b'\\n') # doctest: +SKIP IndexError: No delimiter found within max record size of 4MB. Transfer without specifying a delimiter (as binary) instead. """ f.seek(offset) bytes = f.read(length) if delimiter: # max record size is 4MB max_record = 2**22 if length > max_record: raise IndexError('Records larger than ' + str(max_record) + ' bytes are not supported. The length requested was: ' + str(length) + 'bytes') # get the last index of the delimiter if it exists try: last_delim_index = len(bytes) -1 - bytes[::-1].index(delimiter) # this ensures the length includes all of the last delimiter (in the event that it is more than one character) length = last_delim_index + len(delimiter) return bytes[0:length] except ValueError: # TODO: Before delimters can be supported through the ADLUploader logic, the number of chunks being uploaded # needs to be visible to this method, since it needs to throw if: # 1. We cannot find a delimiter in <= 4MB of data # 2. If the remaining size is less than 4MB but there are multiple chunks that need to be stitched together, # since the delimiter could be split across chunks. # 3. If delimiters are specified, there must be logic during segment determination that ensures all chunks # terminate at the end of a record (on a new line), even if that makes the chunk < 256MB. if length >= max_record: raise IndexError('No delimiter found within max record size of ' + str(max_record) + ' bytes. Transfer without specifying a delimiter (as binary) instead.') return bytes def
(*args, **kwargs): """ Deterministic token >>> tokenize('Hello') == tokenize('Hello') True """ if kwargs: args = args + (kwargs,) return md5(str(tuple(args)).encode()).hexdigest() def commonprefix(paths): """ Find common directory for all paths Python's ``os.path.commonprefix`` will not return a valid directory path in some cases, so we wrote this convenience method. Examples -------- >>> # os.path.commonprefix returns '/disk1/foo' >>> commonprefix(['/disk1/foobar', '/disk1/foobaz']) '/disk1' >>> commonprefix(['a/b/c', 'a/b/d', 'a/c/d']) 'a' >>> commonprefix(['a/b/c', 'd/e/f', 'g/h/i']) '' """ return os.path.dirname(os.path.commonprefix(paths)) def clamp(n, smallest, largest): """ Limit a value to a given range This is equivalent to smallest <= n <= largest. Examples -------- >>> clamp(0, 1, 100) 1 >>> clamp(42, 2, 128) 42 >>> clamp(1024, 1, 32) 32 """ return max(smallest, min(n, largest))
tokenize
identifier_name
utils.py
# -*- coding: utf-8 -*- # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- import array from hashlib import md5 import os import platform import sys PY2 = sys.version_info.major == 2 WIN = platform.system() == 'Windows' if WIN: datadir = os.path.join(os.environ['APPDATA'], 'azure-datalake-store') else: datadir = os.sep.join([os.path.expanduser("~"), '.config', 'azure-datalake-store']) try: os.makedirs(datadir) except: pass def ensure_writable(b): if PY2 and isinstance(b, array.array): return b.tostring() return b def write_stdout(data): """ Write bytes or strings to standard output """ try: sys.stdout.buffer.write(data) except AttributeError: sys.stdout.write(data.decode('ascii', 'replace')) def read_block(f, offset, length, delimiter=None): """ Read a block of bytes from a file Parameters ---------- fn: file object a file object that supports seek, tell and read. offset: int Byte offset to start read length: int Maximum number of bytes to read delimiter: bytes (optional) Ensure reading stops at delimiter bytestring If using the ``delimiter=`` keyword argument we ensure that the read stops at or before the delimiter boundaries that follow the location ``offset + length``. For ADL, if no delimiter is found and the data requested is > 4MB an exception is raised, since a single record cannot exceed 4MB and be guaranteed to land contiguously in ADL. The bytestring returned WILL include the terminating delimiter string. Examples -------- >>> from io import BytesIO # doctest: +SKIP >>> f = BytesIO(b'Alice, 100\\nBob, 200\\nCharlie, 300') # doctest: +SKIP >>> read_block(f, 0, 13) # doctest: +SKIP b'Alice, 100\\nBo' >>> read_block(f, 0, 13, delimiter=b'\\n') # doctest: +SKIP b'Alice, 100\\n' >>> read_block(f, 10, 10, delimiter=b'\\n') # doctest: +SKIP b'\\nCharlie, 300' >>> f = BytesIO(bytearray(2**22)) # doctest: +SKIP >>> read_block(f,0,2**22, delimiter=b'\\n') # doctest: +SKIP IndexError: No delimiter found within max record size of 4MB. Transfer without specifying a delimiter (as binary) instead. """ f.seek(offset) bytes = f.read(length) if delimiter: # max record size is 4MB max_record = 2**22 if length > max_record: raise IndexError('Records larger than ' + str(max_record) + ' bytes are not supported. The length requested was: ' + str(length) + 'bytes') # get the last index of the delimiter if it exists try: last_delim_index = len(bytes) -1 - bytes[::-1].index(delimiter) # this ensures the length includes all of the last delimiter (in the event that it is more than one character) length = last_delim_index + len(delimiter) return bytes[0:length] except ValueError: # TODO: Before delimters can be supported through the ADLUploader logic, the number of chunks being uploaded # needs to be visible to this method, since it needs to throw if: # 1. We cannot find a delimiter in <= 4MB of data # 2. If the remaining size is less than 4MB but there are multiple chunks that need to be stitched together, # since the delimiter could be split across chunks. # 3. If delimiters are specified, there must be logic during segment determination that ensures all chunks # terminate at the end of a record (on a new line), even if that makes the chunk < 256MB. if length >= max_record: raise IndexError('No delimiter found within max record size of ' + str(max_record) + ' bytes. Transfer without specifying a delimiter (as binary) instead.') return bytes def tokenize(*args, **kwargs): """ Deterministic token >>> tokenize('Hello') == tokenize('Hello') True """ if kwargs: args = args + (kwargs,) return md5(str(tuple(args)).encode()).hexdigest() def commonprefix(paths): """ Find common directory for all paths Python's ``os.path.commonprefix`` will not return a valid directory path in some cases, so we wrote this convenience method. Examples -------- >>> # os.path.commonprefix returns '/disk1/foo' >>> commonprefix(['/disk1/foobar', '/disk1/foobaz'])
>>> commonprefix(['a/b/c', 'd/e/f', 'g/h/i']) '' """ return os.path.dirname(os.path.commonprefix(paths)) def clamp(n, smallest, largest): """ Limit a value to a given range This is equivalent to smallest <= n <= largest. Examples -------- >>> clamp(0, 1, 100) 1 >>> clamp(42, 2, 128) 42 >>> clamp(1024, 1, 32) 32 """ return max(smallest, min(n, largest))
'/disk1' >>> commonprefix(['a/b/c', 'a/b/d', 'a/c/d']) 'a'
random_line_split
client_stress_test.rs
// Copyright 2016 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // By contributing code to the SAFE Network Software, or to this project generally, you agree to be // bound by the terms of the MaidSafe Contributor Agreement. This, along with the Licenses can be // found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR. // // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. // // Please review the Licences for the specific language governing permissions and limitations // relating to use of the SAFE Network Software. //! Safe client example. // For explanation of lint checks, run `rustc -W help` or see // https://github. // com/maidsafe/QA/blob/master/Documentation/Rust%20Lint%20Checks.md #![forbid(bad_style, exceeding_bitshifts, mutable_transmutes, no_mangle_const_items, unknown_crate_types, warnings)] #![deny(deprecated, improper_ctypes, missing_docs, non_shorthand_field_patterns, overflowing_literals, plugin_as_library, private_no_mangle_fns, private_no_mangle_statics, stable_features, unconditional_recursion, unknown_lints, unsafe_code, unused, unused_allocation, unused_attributes, unused_comparisons, unused_features, unused_parens, while_true)] #![warn(trivial_casts, trivial_numeric_casts, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #![allow(box_pointers, fat_ptr_transmutes, missing_copy_implementations, missing_debug_implementations, variant_size_differences)] #![cfg_attr(feature="cargo-clippy", deny(clippy, clippy_pedantic))] #![cfg_attr(feature="cargo-clippy", allow(use_debug, print_stdout, missing_docs_in_private_items))] extern crate docopt; extern crate rand; extern crate rustc_serialize; extern crate futures; extern crate routing; extern crate rust_sodium; #[macro_use] extern crate safe_core; extern crate tokio_core; extern crate maidsafe_utilities; #[macro_use] extern crate unwrap; use docopt::Docopt; use futures::Future; use futures::stream::{self, Stream}; use futures::sync::mpsc; use rand::{Rng, SeedableRng}; use routing::{ImmutableData, MutableData}; use rust_sodium::crypto::sign::PublicKey; use safe_core::{Client, CoreMsg, FutureExt, event_loop}; use tokio_core::reactor::Core; #[cfg_attr(rustfmt, rustfmt_skip)] static USAGE: &'static str = " Usage: client_stress_test [options] Options: -i <count>, --immutable=<count> Number of ImmutableData chunks to Put and Get [default: 100]. -m <count>, --mutable=<count> Number of MutableData chunks to Put and Get [default: 100]. --seed <seed> Seed for a pseudo-random number generator. --get-only Only Get the data, don't Put it. --invite INVITATION Use the given invite. -h, --help Display this help message and exit. "; #[derive(Debug, RustcDecodable)] struct Args { flag_immutable: Option<usize>, flag_mutable: Option<usize>, flag_seed: Option<u32>, flag_get_only: bool, flag_invite: Option<String>, flag_help: bool, } fn random_mutable_data<R: Rng>(type_tag: u64, public_key: &PublicKey, rng: &mut R) -> MutableData { let permissions = btree_map![]; let data = btree_map![]; unwrap!(MutableData::new( rng.gen(), type_tag, permissions, data, btree_set![*public_key], )) } enum Data { Mutable(MutableData), Immutable(ImmutableData), } fn main() { unwrap!(maidsafe_utilities::log::init(true)); let args: Args = Docopt::new(USAGE) .and_then(|docopt| docopt.decode()) .unwrap_or_else(|error| error.exit()); let immutable_data_count = unwrap!(args.flag_immutable); let mutable_data_count = unwrap!(args.flag_mutable); let mut rng = rand::XorShiftRng::from_seed(match args.flag_seed { Some(seed) => [0, 0, 0, seed], None => { [ rand::random(), rand::random(), rand::random(), rand::random(), ] } }); let el = unwrap!(Core::new()); let el_h = el.handle(); let (core_tx, core_rx) = mpsc::unbounded(); let (net_tx, _net_rx) = mpsc::unbounded(); // Create account let secret_0: String = rng.gen_ascii_chars().take(20).collect(); let secret_1: String = rng.gen_ascii_chars().take(20).collect(); let mut invitation = rng.gen_ascii_chars().take(20).collect(); if let Some(i) = args.flag_invite.clone() { invitation = i; } let client = if args.flag_get_only
else { println!("\n\tAccount Creation"); println!("\t================"); println!("\nTrying to create an account ..."); unwrap!(Client::registered( &secret_0, &secret_1, &invitation, el_h, core_tx.clone(), net_tx, )) }; println!("Logged in successfully!"); let public_key = unwrap!(client.public_signing_key()); let core_tx_clone = core_tx.clone(); unwrap!(core_tx.unbounded_send(CoreMsg::new(move |client, _| { let mut stored_data = Vec::with_capacity(mutable_data_count + immutable_data_count); for _ in 0..immutable_data_count { // Construct data let data = ImmutableData::new(rng.gen_iter().take(1024).collect()); stored_data.push(Data::Immutable(data)); } for _ in immutable_data_count..(immutable_data_count + mutable_data_count) { // Construct data let mutable_data = random_mutable_data(100000, &public_key, &mut rng); stored_data.push(Data::Mutable(mutable_data)); } let message = format!( "Generated {} items ({} immutable, {} mutable)", stored_data.len(), immutable_data_count, mutable_data_count ); let underline = (0..message.len()).map(|_| "=").collect::<String>(); println!("\n\t{}\n\t{}", message, underline); stream::iter_ok(stored_data.into_iter().enumerate()) .fold((client.clone(), args, rng), |(client, args, rng), (i, data)| { let c2 = client.clone(); let c3 = client.clone(); let c4 = client.clone(); match data { Data::Immutable(data) => { let fut = if args.flag_get_only { futures::finished(data).into_box() } else { // Put the data to the network c2.put_idata(data.clone()) .and_then(move |_| { println!("Put ImmutableData chunk #{}: {:?}", i, data.name()); // Get the data c3.get_idata(*data.name()).map(move |retrieved_data| { assert_eq!(data, retrieved_data); retrieved_data }) }) .and_then(move |retrieved_data| { println!( "Retrieved ImmutableData chunk #{}: {:?}", i, retrieved_data.name() ); Ok(retrieved_data) }) .into_box() }; fut.and_then(move |data| { // Get all the chunks again c4.get_idata(*data.name()).map(move |retrieved_data| { assert_eq!(data, retrieved_data); println!("Retrieved chunk #{}: {:?}", i, data.name()); (args, rng) }) }).map(move |(args, rng)| (client, args, rng)) .map_err(|e| println!("Error: {:?}", e)) .into_box() } Data::Mutable(data) => { let fut = if args.flag_get_only { futures::finished(data).into_box() } else { // Put the data to the network c2.put_mdata(data.clone()) .and_then(move |_| { println!("Put MutableData chunk #{}: {:?}", i, data.name()); // Get the data c3.get_mdata_shell(*data.name(), data.tag()).map( move |retrieved_data| { assert_eq!(data, retrieved_data); retrieved_data }, ) }) .and_then(move |retrieved_data| { println!( "Retrieved MutableData chunk #{}: {:?}", i, retrieved_data.name() ); Ok(retrieved_data) }) .into_box() }; // TODO(nbaksalyar): stress test mutate_mdata and get_mdata_value here fut.and_then(move |data| { // Get all the chunks again c4.get_mdata_shell(*data.name(), data.tag()).map( move |retrieved_data| { assert_eq!(data, retrieved_data); println!("Retrieved chunk #{}: {:?}", i, data.name()); (args, rng) }, ) }).map(move |(args, rng)| (client, args, rng)) .map_err(|e| println!("Error: {:?}", e)) .into_box() } } }) .map(move |_| { unwrap!(core_tx_clone.unbounded_send(CoreMsg::build_terminator())) }) .into_box() .into() }))); event_loop::run(el, &client, &(), core_rx); }
{ unwrap!(Client::login( &secret_0, &secret_1, el_h, core_tx.clone(), net_tx, )) }
conditional_block
client_stress_test.rs
// Copyright 2016 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // By contributing code to the SAFE Network Software, or to this project generally, you agree to be // bound by the terms of the MaidSafe Contributor Agreement. This, along with the Licenses can be // found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR. // // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. // // Please review the Licences for the specific language governing permissions and limitations // relating to use of the SAFE Network Software. //! Safe client example. // For explanation of lint checks, run `rustc -W help` or see // https://github. // com/maidsafe/QA/blob/master/Documentation/Rust%20Lint%20Checks.md #![forbid(bad_style, exceeding_bitshifts, mutable_transmutes, no_mangle_const_items, unknown_crate_types, warnings)] #![deny(deprecated, improper_ctypes, missing_docs, non_shorthand_field_patterns, overflowing_literals, plugin_as_library, private_no_mangle_fns, private_no_mangle_statics, stable_features, unconditional_recursion, unknown_lints, unsafe_code, unused, unused_allocation, unused_attributes, unused_comparisons, unused_features, unused_parens, while_true)] #![warn(trivial_casts, trivial_numeric_casts, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #![allow(box_pointers, fat_ptr_transmutes, missing_copy_implementations, missing_debug_implementations, variant_size_differences)] #![cfg_attr(feature="cargo-clippy", deny(clippy, clippy_pedantic))] #![cfg_attr(feature="cargo-clippy", allow(use_debug, print_stdout, missing_docs_in_private_items))] extern crate docopt; extern crate rand; extern crate rustc_serialize; extern crate futures; extern crate routing; extern crate rust_sodium; #[macro_use] extern crate safe_core; extern crate tokio_core; extern crate maidsafe_utilities; #[macro_use] extern crate unwrap; use docopt::Docopt; use futures::Future; use futures::stream::{self, Stream}; use futures::sync::mpsc; use rand::{Rng, SeedableRng}; use routing::{ImmutableData, MutableData}; use rust_sodium::crypto::sign::PublicKey; use safe_core::{Client, CoreMsg, FutureExt, event_loop}; use tokio_core::reactor::Core; #[cfg_attr(rustfmt, rustfmt_skip)] static USAGE: &'static str = " Usage: client_stress_test [options] Options: -i <count>, --immutable=<count> Number of ImmutableData chunks to Put and Get [default: 100]. -m <count>, --mutable=<count> Number of MutableData chunks to Put and Get [default: 100]. --seed <seed> Seed for a pseudo-random number generator. --get-only Only Get the data, don't Put it. --invite INVITATION Use the given invite. -h, --help Display this help message and exit. "; #[derive(Debug, RustcDecodable)] struct Args { flag_immutable: Option<usize>, flag_mutable: Option<usize>, flag_seed: Option<u32>, flag_get_only: bool, flag_invite: Option<String>, flag_help: bool, } fn random_mutable_data<R: Rng>(type_tag: u64, public_key: &PublicKey, rng: &mut R) -> MutableData { let permissions = btree_map![]; let data = btree_map![]; unwrap!(MutableData::new( rng.gen(), type_tag, permissions, data, btree_set![*public_key], )) } enum Data { Mutable(MutableData), Immutable(ImmutableData), } fn main() { unwrap!(maidsafe_utilities::log::init(true)); let args: Args = Docopt::new(USAGE) .and_then(|docopt| docopt.decode()) .unwrap_or_else(|error| error.exit()); let immutable_data_count = unwrap!(args.flag_immutable); let mutable_data_count = unwrap!(args.flag_mutable); let mut rng = rand::XorShiftRng::from_seed(match args.flag_seed { Some(seed) => [0, 0, 0, seed], None => { [ rand::random(), rand::random(), rand::random(), rand::random(), ] } }); let el = unwrap!(Core::new()); let el_h = el.handle(); let (core_tx, core_rx) = mpsc::unbounded(); let (net_tx, _net_rx) = mpsc::unbounded(); // Create account let secret_0: String = rng.gen_ascii_chars().take(20).collect(); let secret_1: String = rng.gen_ascii_chars().take(20).collect(); let mut invitation = rng.gen_ascii_chars().take(20).collect(); if let Some(i) = args.flag_invite.clone() { invitation = i; } let client = if args.flag_get_only { unwrap!(Client::login( &secret_0, &secret_1, el_h, core_tx.clone(), net_tx, )) } else { println!("\n\tAccount Creation"); println!("\t================"); println!("\nTrying to create an account ..."); unwrap!(Client::registered( &secret_0, &secret_1, &invitation, el_h, core_tx.clone(), net_tx, )) }; println!("Logged in successfully!"); let public_key = unwrap!(client.public_signing_key()); let core_tx_clone = core_tx.clone(); unwrap!(core_tx.unbounded_send(CoreMsg::new(move |client, _| { let mut stored_data = Vec::with_capacity(mutable_data_count + immutable_data_count); for _ in 0..immutable_data_count { // Construct data let data = ImmutableData::new(rng.gen_iter().take(1024).collect()); stored_data.push(Data::Immutable(data)); } for _ in immutable_data_count..(immutable_data_count + mutable_data_count) { // Construct data let mutable_data = random_mutable_data(100000, &public_key, &mut rng); stored_data.push(Data::Mutable(mutable_data)); } let message = format!( "Generated {} items ({} immutable, {} mutable)", stored_data.len(), immutable_data_count, mutable_data_count ); let underline = (0..message.len()).map(|_| "=").collect::<String>(); println!("\n\t{}\n\t{}", message, underline); stream::iter_ok(stored_data.into_iter().enumerate()) .fold((client.clone(), args, rng), |(client, args, rng), (i, data)| { let c2 = client.clone(); let c3 = client.clone(); let c4 = client.clone(); match data { Data::Immutable(data) => { let fut = if args.flag_get_only { futures::finished(data).into_box() } else { // Put the data to the network c2.put_idata(data.clone()) .and_then(move |_| { println!("Put ImmutableData chunk #{}: {:?}", i, data.name()); // Get the data c3.get_idata(*data.name()).map(move |retrieved_data| { assert_eq!(data, retrieved_data); retrieved_data }) }) .and_then(move |retrieved_data| { println!( "Retrieved ImmutableData chunk #{}: {:?}", i, retrieved_data.name() ); Ok(retrieved_data) }) .into_box() }; fut.and_then(move |data| { // Get all the chunks again c4.get_idata(*data.name()).map(move |retrieved_data| { assert_eq!(data, retrieved_data); println!("Retrieved chunk #{}: {:?}", i, data.name()); (args, rng) }) }).map(move |(args, rng)| (client, args, rng)) .map_err(|e| println!("Error: {:?}", e)) .into_box() } Data::Mutable(data) => { let fut = if args.flag_get_only { futures::finished(data).into_box() } else { // Put the data to the network c2.put_mdata(data.clone()) .and_then(move |_| { println!("Put MutableData chunk #{}: {:?}", i, data.name()); // Get the data c3.get_mdata_shell(*data.name(), data.tag()).map( move |retrieved_data| { assert_eq!(data, retrieved_data); retrieved_data }, ) }) .and_then(move |retrieved_data| { println!( "Retrieved MutableData chunk #{}: {:?}", i, retrieved_data.name() ); Ok(retrieved_data) }) .into_box() }; // TODO(nbaksalyar): stress test mutate_mdata and get_mdata_value here fut.and_then(move |data| { // Get all the chunks again c4.get_mdata_shell(*data.name(), data.tag()).map( move |retrieved_data| { assert_eq!(data, retrieved_data); println!("Retrieved chunk #{}: {:?}", i, data.name()); (args, rng) }, ) }).map(move |(args, rng)| (client, args, rng)) .map_err(|e| println!("Error: {:?}", e)) .into_box() } } }) .map(move |_| { unwrap!(core_tx_clone.unbounded_send(CoreMsg::build_terminator())) })
}))); event_loop::run(el, &client, &(), core_rx); }
.into_box() .into()
random_line_split
client_stress_test.rs
// Copyright 2016 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // By contributing code to the SAFE Network Software, or to this project generally, you agree to be // bound by the terms of the MaidSafe Contributor Agreement. This, along with the Licenses can be // found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR. // // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. // // Please review the Licences for the specific language governing permissions and limitations // relating to use of the SAFE Network Software. //! Safe client example. // For explanation of lint checks, run `rustc -W help` or see // https://github. // com/maidsafe/QA/blob/master/Documentation/Rust%20Lint%20Checks.md #![forbid(bad_style, exceeding_bitshifts, mutable_transmutes, no_mangle_const_items, unknown_crate_types, warnings)] #![deny(deprecated, improper_ctypes, missing_docs, non_shorthand_field_patterns, overflowing_literals, plugin_as_library, private_no_mangle_fns, private_no_mangle_statics, stable_features, unconditional_recursion, unknown_lints, unsafe_code, unused, unused_allocation, unused_attributes, unused_comparisons, unused_features, unused_parens, while_true)] #![warn(trivial_casts, trivial_numeric_casts, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #![allow(box_pointers, fat_ptr_transmutes, missing_copy_implementations, missing_debug_implementations, variant_size_differences)] #![cfg_attr(feature="cargo-clippy", deny(clippy, clippy_pedantic))] #![cfg_attr(feature="cargo-clippy", allow(use_debug, print_stdout, missing_docs_in_private_items))] extern crate docopt; extern crate rand; extern crate rustc_serialize; extern crate futures; extern crate routing; extern crate rust_sodium; #[macro_use] extern crate safe_core; extern crate tokio_core; extern crate maidsafe_utilities; #[macro_use] extern crate unwrap; use docopt::Docopt; use futures::Future; use futures::stream::{self, Stream}; use futures::sync::mpsc; use rand::{Rng, SeedableRng}; use routing::{ImmutableData, MutableData}; use rust_sodium::crypto::sign::PublicKey; use safe_core::{Client, CoreMsg, FutureExt, event_loop}; use tokio_core::reactor::Core; #[cfg_attr(rustfmt, rustfmt_skip)] static USAGE: &'static str = " Usage: client_stress_test [options] Options: -i <count>, --immutable=<count> Number of ImmutableData chunks to Put and Get [default: 100]. -m <count>, --mutable=<count> Number of MutableData chunks to Put and Get [default: 100]. --seed <seed> Seed for a pseudo-random number generator. --get-only Only Get the data, don't Put it. --invite INVITATION Use the given invite. -h, --help Display this help message and exit. "; #[derive(Debug, RustcDecodable)] struct Args { flag_immutable: Option<usize>, flag_mutable: Option<usize>, flag_seed: Option<u32>, flag_get_only: bool, flag_invite: Option<String>, flag_help: bool, } fn random_mutable_data<R: Rng>(type_tag: u64, public_key: &PublicKey, rng: &mut R) -> MutableData { let permissions = btree_map![]; let data = btree_map![]; unwrap!(MutableData::new( rng.gen(), type_tag, permissions, data, btree_set![*public_key], )) } enum Data { Mutable(MutableData), Immutable(ImmutableData), } fn
() { unwrap!(maidsafe_utilities::log::init(true)); let args: Args = Docopt::new(USAGE) .and_then(|docopt| docopt.decode()) .unwrap_or_else(|error| error.exit()); let immutable_data_count = unwrap!(args.flag_immutable); let mutable_data_count = unwrap!(args.flag_mutable); let mut rng = rand::XorShiftRng::from_seed(match args.flag_seed { Some(seed) => [0, 0, 0, seed], None => { [ rand::random(), rand::random(), rand::random(), rand::random(), ] } }); let el = unwrap!(Core::new()); let el_h = el.handle(); let (core_tx, core_rx) = mpsc::unbounded(); let (net_tx, _net_rx) = mpsc::unbounded(); // Create account let secret_0: String = rng.gen_ascii_chars().take(20).collect(); let secret_1: String = rng.gen_ascii_chars().take(20).collect(); let mut invitation = rng.gen_ascii_chars().take(20).collect(); if let Some(i) = args.flag_invite.clone() { invitation = i; } let client = if args.flag_get_only { unwrap!(Client::login( &secret_0, &secret_1, el_h, core_tx.clone(), net_tx, )) } else { println!("\n\tAccount Creation"); println!("\t================"); println!("\nTrying to create an account ..."); unwrap!(Client::registered( &secret_0, &secret_1, &invitation, el_h, core_tx.clone(), net_tx, )) }; println!("Logged in successfully!"); let public_key = unwrap!(client.public_signing_key()); let core_tx_clone = core_tx.clone(); unwrap!(core_tx.unbounded_send(CoreMsg::new(move |client, _| { let mut stored_data = Vec::with_capacity(mutable_data_count + immutable_data_count); for _ in 0..immutable_data_count { // Construct data let data = ImmutableData::new(rng.gen_iter().take(1024).collect()); stored_data.push(Data::Immutable(data)); } for _ in immutable_data_count..(immutable_data_count + mutable_data_count) { // Construct data let mutable_data = random_mutable_data(100000, &public_key, &mut rng); stored_data.push(Data::Mutable(mutable_data)); } let message = format!( "Generated {} items ({} immutable, {} mutable)", stored_data.len(), immutable_data_count, mutable_data_count ); let underline = (0..message.len()).map(|_| "=").collect::<String>(); println!("\n\t{}\n\t{}", message, underline); stream::iter_ok(stored_data.into_iter().enumerate()) .fold((client.clone(), args, rng), |(client, args, rng), (i, data)| { let c2 = client.clone(); let c3 = client.clone(); let c4 = client.clone(); match data { Data::Immutable(data) => { let fut = if args.flag_get_only { futures::finished(data).into_box() } else { // Put the data to the network c2.put_idata(data.clone()) .and_then(move |_| { println!("Put ImmutableData chunk #{}: {:?}", i, data.name()); // Get the data c3.get_idata(*data.name()).map(move |retrieved_data| { assert_eq!(data, retrieved_data); retrieved_data }) }) .and_then(move |retrieved_data| { println!( "Retrieved ImmutableData chunk #{}: {:?}", i, retrieved_data.name() ); Ok(retrieved_data) }) .into_box() }; fut.and_then(move |data| { // Get all the chunks again c4.get_idata(*data.name()).map(move |retrieved_data| { assert_eq!(data, retrieved_data); println!("Retrieved chunk #{}: {:?}", i, data.name()); (args, rng) }) }).map(move |(args, rng)| (client, args, rng)) .map_err(|e| println!("Error: {:?}", e)) .into_box() } Data::Mutable(data) => { let fut = if args.flag_get_only { futures::finished(data).into_box() } else { // Put the data to the network c2.put_mdata(data.clone()) .and_then(move |_| { println!("Put MutableData chunk #{}: {:?}", i, data.name()); // Get the data c3.get_mdata_shell(*data.name(), data.tag()).map( move |retrieved_data| { assert_eq!(data, retrieved_data); retrieved_data }, ) }) .and_then(move |retrieved_data| { println!( "Retrieved MutableData chunk #{}: {:?}", i, retrieved_data.name() ); Ok(retrieved_data) }) .into_box() }; // TODO(nbaksalyar): stress test mutate_mdata and get_mdata_value here fut.and_then(move |data| { // Get all the chunks again c4.get_mdata_shell(*data.name(), data.tag()).map( move |retrieved_data| { assert_eq!(data, retrieved_data); println!("Retrieved chunk #{}: {:?}", i, data.name()); (args, rng) }, ) }).map(move |(args, rng)| (client, args, rng)) .map_err(|e| println!("Error: {:?}", e)) .into_box() } } }) .map(move |_| { unwrap!(core_tx_clone.unbounded_send(CoreMsg::build_terminator())) }) .into_box() .into() }))); event_loop::run(el, &client, &(), core_rx); }
main
identifier_name
page.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DOMRefCell; use dom::bindings::js::{JS, Root}; use dom::document::Document; use dom::window::Window; use msg::constellation_msg::PipelineId; use std::cell::Cell; use std::rc::Rc; /// Encapsulates a handle to a frame in a frame tree. #[derive(JSTraceable, HeapSizeOf)] #[allow(unrooted_must_root)] // FIXME(#6687) this is wrong pub struct Page { /// Pipeline id associated with this page.
/// Indicates if reflow is required when reloading. needs_reflow: Cell<bool>, // Child Pages. pub children: DOMRefCell<Vec<Rc<Page>>>, } pub struct PageIterator { stack: Vec<Rc<Page>>, } pub trait IterablePage { fn iter(&self) -> PageIterator; fn find(&self, id: PipelineId) -> Option<Rc<Page>>; } impl IterablePage for Rc<Page> { fn iter(&self) -> PageIterator { PageIterator { stack: vec!(self.clone()), } } fn find(&self, id: PipelineId) -> Option<Rc<Page>> { if self.id == id { return Some(self.clone()); } for page in &*self.children.borrow() { let found = page.find(id); if found.is_some() { return found; } } None } } impl Page { pub fn new(id: PipelineId) -> Page { Page { id: id, frame: DOMRefCell::new(None), needs_reflow: Cell::new(true), children: DOMRefCell::new(vec!()), } } pub fn pipeline(&self) -> PipelineId { self.id } pub fn window(&self) -> Root<Window> { self.frame.borrow().as_ref().unwrap().window.root() } pub fn document(&self) -> Root<Document> { self.frame.borrow().as_ref().unwrap().document.root() } // must handle root case separately pub fn remove(&self, id: PipelineId) -> Option<Rc<Page>> { let remove_idx = { self.children .borrow_mut() .iter_mut() .position(|page_tree| page_tree.id == id) }; match remove_idx { Some(idx) => Some(self.children.borrow_mut().remove(idx)), None => { self.children .borrow_mut() .iter_mut() .filter_map(|page_tree| page_tree.remove(id)) .next() } } } } impl Iterator for PageIterator { type Item = Rc<Page>; fn next(&mut self) -> Option<Rc<Page>> { match self.stack.pop() { Some(next) => { for child in &*next.children.borrow() { self.stack.push(child.clone()); } Some(next) }, None => None, } } } impl Page { pub fn set_reflow_status(&self, status: bool) -> bool { let old = self.needs_reflow.get(); self.needs_reflow.set(status); old } pub fn set_frame(&self, frame: Option<Frame>) { *self.frame.borrow_mut() = frame; } } /// Information for one frame in the browsing context. #[derive(JSTraceable, HeapSizeOf)] #[must_root] pub struct Frame { /// The document for this frame. pub document: JS<Document>, /// The window object for this frame. pub window: JS<Window>, }
id: PipelineId, /// The outermost frame containing the document and window. frame: DOMRefCell<Option<Frame>>,
random_line_split
page.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DOMRefCell; use dom::bindings::js::{JS, Root}; use dom::document::Document; use dom::window::Window; use msg::constellation_msg::PipelineId; use std::cell::Cell; use std::rc::Rc; /// Encapsulates a handle to a frame in a frame tree. #[derive(JSTraceable, HeapSizeOf)] #[allow(unrooted_must_root)] // FIXME(#6687) this is wrong pub struct Page { /// Pipeline id associated with this page. id: PipelineId, /// The outermost frame containing the document and window. frame: DOMRefCell<Option<Frame>>, /// Indicates if reflow is required when reloading. needs_reflow: Cell<bool>, // Child Pages. pub children: DOMRefCell<Vec<Rc<Page>>>, } pub struct PageIterator { stack: Vec<Rc<Page>>, } pub trait IterablePage { fn iter(&self) -> PageIterator; fn find(&self, id: PipelineId) -> Option<Rc<Page>>; } impl IterablePage for Rc<Page> { fn iter(&self) -> PageIterator { PageIterator { stack: vec!(self.clone()), } } fn find(&self, id: PipelineId) -> Option<Rc<Page>> { if self.id == id { return Some(self.clone()); } for page in &*self.children.borrow() { let found = page.find(id); if found.is_some() { return found; } } None } } impl Page { pub fn new(id: PipelineId) -> Page { Page { id: id, frame: DOMRefCell::new(None), needs_reflow: Cell::new(true), children: DOMRefCell::new(vec!()), } } pub fn pipeline(&self) -> PipelineId { self.id } pub fn window(&self) -> Root<Window> { self.frame.borrow().as_ref().unwrap().window.root() } pub fn document(&self) -> Root<Document> { self.frame.borrow().as_ref().unwrap().document.root() } // must handle root case separately pub fn
(&self, id: PipelineId) -> Option<Rc<Page>> { let remove_idx = { self.children .borrow_mut() .iter_mut() .position(|page_tree| page_tree.id == id) }; match remove_idx { Some(idx) => Some(self.children.borrow_mut().remove(idx)), None => { self.children .borrow_mut() .iter_mut() .filter_map(|page_tree| page_tree.remove(id)) .next() } } } } impl Iterator for PageIterator { type Item = Rc<Page>; fn next(&mut self) -> Option<Rc<Page>> { match self.stack.pop() { Some(next) => { for child in &*next.children.borrow() { self.stack.push(child.clone()); } Some(next) }, None => None, } } } impl Page { pub fn set_reflow_status(&self, status: bool) -> bool { let old = self.needs_reflow.get(); self.needs_reflow.set(status); old } pub fn set_frame(&self, frame: Option<Frame>) { *self.frame.borrow_mut() = frame; } } /// Information for one frame in the browsing context. #[derive(JSTraceable, HeapSizeOf)] #[must_root] pub struct Frame { /// The document for this frame. pub document: JS<Document>, /// The window object for this frame. pub window: JS<Window>, }
remove
identifier_name
plugin.py
# -*- coding: utf-8 -*- """ Base Class for InvenTree plugins """ import warnings from django.db.utils import OperationalError, ProgrammingError from django.utils.text import slugify class InvenTreePluginBase(): """ Base class for a plugin DO NOT USE THIS DIRECTLY, USE plugin.IntegrationPluginBase """ def __init__(self): pass # Override the plugin name for each concrete plugin instance PLUGIN_NAME = '' PLUGIN_SLUG = None PLUGIN_TITLE = None def plugin_name(self): """ Name of plugin """ return self.PLUGIN_NAME def plugin_slug(self): """ Slug of plugin If not set plugin name slugified """ slug = getattr(self, 'PLUGIN_SLUG', None) if slug is None: slug = self.plugin_name() return slugify(slug.lower()) def plugin_title(self): """ Title of plugin """ if self.PLUGIN_TITLE: return self.PLUGIN_TITLE else: return self.plugin_name() def plugin_config(self, raise_error=False): """ Return the PluginConfig object associated with this plugin """ try: import plugin.models cfg, _ = plugin.models.PluginConfig.objects.get_or_create( key=self.plugin_slug(), name=self.plugin_name(), ) except (OperationalError, ProgrammingError) as error: cfg = None if raise_error: raise error return cfg def is_active(self): """ Return True if this plugin is currently active """ cfg = self.plugin_config() if cfg: return cfg.active else:
# TODO @matmair remove after InvenTree 0.7.0 release class InvenTreePlugin(InvenTreePluginBase): """ This is here for leagcy reasons and will be removed in the next major release """ def __init__(self): warnings.warn("Using the InvenTreePlugin is depreceated", DeprecationWarning) super().__init__()
return False
conditional_block
plugin.py
# -*- coding: utf-8 -*- """ Base Class for InvenTree plugins """ import warnings from django.db.utils import OperationalError, ProgrammingError from django.utils.text import slugify class InvenTreePluginBase(): """ Base class for a plugin DO NOT USE THIS DIRECTLY, USE plugin.IntegrationPluginBase """ def __init__(self): pass # Override the plugin name for each concrete plugin instance PLUGIN_NAME = '' PLUGIN_SLUG = None PLUGIN_TITLE = None def plugin_name(self): """ Name of plugin """ return self.PLUGIN_NAME def plugin_slug(self): """ Slug of plugin If not set plugin name slugified """ slug = getattr(self, 'PLUGIN_SLUG', None) if slug is None: slug = self.plugin_name() return slugify(slug.lower()) def plugin_title(self): """ Title of plugin """ if self.PLUGIN_TITLE: return self.PLUGIN_TITLE else: return self.plugin_name() def plugin_config(self, raise_error=False): """ Return the PluginConfig object associated with this plugin """ try: import plugin.models cfg, _ = plugin.models.PluginConfig.objects.get_or_create( key=self.plugin_slug(), name=self.plugin_name(), ) except (OperationalError, ProgrammingError) as error: cfg = None if raise_error: raise error return cfg
""" cfg = self.plugin_config() if cfg: return cfg.active else: return False # TODO @matmair remove after InvenTree 0.7.0 release class InvenTreePlugin(InvenTreePluginBase): """ This is here for leagcy reasons and will be removed in the next major release """ def __init__(self): warnings.warn("Using the InvenTreePlugin is depreceated", DeprecationWarning) super().__init__()
def is_active(self): """ Return True if this plugin is currently active
random_line_split
plugin.py
# -*- coding: utf-8 -*- """ Base Class for InvenTree plugins """ import warnings from django.db.utils import OperationalError, ProgrammingError from django.utils.text import slugify class InvenTreePluginBase(): """ Base class for a plugin DO NOT USE THIS DIRECTLY, USE plugin.IntegrationPluginBase """ def __init__(self): pass # Override the plugin name for each concrete plugin instance PLUGIN_NAME = '' PLUGIN_SLUG = None PLUGIN_TITLE = None def plugin_name(self): """ Name of plugin """ return self.PLUGIN_NAME def plugin_slug(self): """ Slug of plugin If not set plugin name slugified """ slug = getattr(self, 'PLUGIN_SLUG', None) if slug is None: slug = self.plugin_name() return slugify(slug.lower()) def plugin_title(self): """ Title of plugin """ if self.PLUGIN_TITLE: return self.PLUGIN_TITLE else: return self.plugin_name() def
(self, raise_error=False): """ Return the PluginConfig object associated with this plugin """ try: import plugin.models cfg, _ = plugin.models.PluginConfig.objects.get_or_create( key=self.plugin_slug(), name=self.plugin_name(), ) except (OperationalError, ProgrammingError) as error: cfg = None if raise_error: raise error return cfg def is_active(self): """ Return True if this plugin is currently active """ cfg = self.plugin_config() if cfg: return cfg.active else: return False # TODO @matmair remove after InvenTree 0.7.0 release class InvenTreePlugin(InvenTreePluginBase): """ This is here for leagcy reasons and will be removed in the next major release """ def __init__(self): warnings.warn("Using the InvenTreePlugin is depreceated", DeprecationWarning) super().__init__()
plugin_config
identifier_name