INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Return a dictionary containing the key/values read from filename. Raises IOError if the file does not exit etcetera.
def _actually_populate_keyvals(filename): """Return a dictionary containing the key/values read from filename. Raises IOError if the file does not exit etcetera. """ assert isinstance(filename, str) keyvals = {} with open(filename, 'r') as f: for line in f: ...
Read the key/values if the file exists. returns -- a dictionary with key/values, or empty dictionary if the file does not exist.
def _read_keyvals(filename): """Read the key/values if the file exists. returns -- a dictionary with key/values, or empty dictionary if the file does not exist. """ assert isinstance(filename, str) if os.path.exists(filename): return _KeyValuePers...
Add an event and its corresponding key to the store.
def add_event(self, key, event): """Add an event and its corresponding key to the store.""" if key in self.keys or key in self.events: raise EventStore.EventKeyAlreadyExistError( "The key already existed: {0}".format(key)) self.keys.append(key) # Important no ...
Query a slice of the events. Events are always returned in the order the were added. Parameters: from_ -- if not None, return only events added after the event with id `from_`. If None, return from the start of history. to -- if not None, return only events ad...
def get_events(self, from_=None, to=None): """Query a slice of the events. Events are always returned in the order the were added. Parameters: from_ -- if not None, return only events added after the event with id `from_`. If None, return from the start of history....
Instantiate an SQLite event store from config. Parameters: _config -- the configuration file options read from file(s). Not used. **options -- various options given to the specific event store. Shall not be used with this event store. Warning will be ...
def from_config(_config, **options): """Instantiate an SQLite event store from config. Parameters: _config -- the configuration file options read from file(s). Not used. **options -- various options given to the specific event store. Shall not...
Add an event and its corresponding key to the store.
def add_event(self, key, event): """Add an event and its corresponding key to the store.""" assert isinstance(key, str) assert isinstance(event, bytes) self.conn.execute('INSERT INTO events(uuid,event) VALUES (?,?)', (key, event.decode('utf-8')))
Query a slice of the events. Events are always returned in the order the were added. Parameters: from_ -- if not None, return only events added after the event with id `from_`. If None, return from the start of history. to -- if not None, return only events ad...
def get_events(self, from_=None, to=None): """Query a slice of the events. Events are always returned in the order the were added. Parameters: from_ -- if not None, return only events added after the event with id `from_`. If None, return from the start of history....
Check whether a key exists in the event store. Returns True if it does, False otherwise.
def key_exists(self, key): """Check whether a key exists in the event store. Returns True if it does, False otherwise. """ assert isinstance(key, str) cursor = self.conn.cursor() with contextlib.closing(cursor): cursor.execute('SELECT COUNT(*) FROM events WH...
Return the number of events in the db.
def count(self): """Return the number of events in the db.""" cursor = self.conn.cursor() with contextlib.closing(cursor): cursor.execute('SELECT COUNT(*) FROM events') res = cursor.fetchone() return res[0]
Close the event store. Important to close to not have any file descriptor leakages.
def close(self): """Close the event store. Important to close to not have any file descriptor leakages. """ if self.conn: self.conn.close() self.conn = None fname = os.path.basename(self._path) checksum_persister = _get_checksum_persister(self._...
Instantiate an `LogEventStore` from config. Parameters: _config -- the configuration file options read from file(s). **options -- various options given to the specific event store. Shall not be used with this event store. Warning will be logged for e...
def from_config(config, **options): """Instantiate an `LogEventStore` from config. Parameters: _config -- the configuration file options read from file(s). **options -- various options given to the specific event store. Shall not be used with this event store. Wa...
Add an event and its corresponding key to the store.
def add_event(self, key, event): """Add an event and its corresponding key to the store.""" assert isinstance(key, str) assert isinstance(event, bytes) if all([char.isalnum() or char == '-' for char in key]): safe_key = key else: raise ValueError("Key must...
Query a slice of the events. Events are always returned in the order the were added. Does never throw EventOrderError because it is hard to detect from an append-only file. Parameters: from_ -- if not None, return only events added after the event with id ...
def get_events(self, from_=None, to=None): """Query a slice of the events. Events are always returned in the order the were added. Does never throw EventOrderError because it is hard to detect from an append-only file. Parameters: from_ -- if not None, return only ev...
Check if key has previously been added to this store. This function makes a linear search through the log file and is very slow. Returns True if the event has previously been added, False otherwise.
def key_exists(self, key): """Check if key has previously been added to this store. This function makes a linear search through the log file and is very slow. Returns True if the event has previously been added, False otherwise. """ assert isinstance(key, str) ...
Persist a checksum and close the file.
def close(self): """Persist a checksum and close the file.""" fname = os.path.basename(self._path) checksum_persister = _get_checksum_persister(self._path) with contextlib.closing(checksum_persister): checksum_persister[fname] = self._hasher.hexdigest() self._close()
Instantiate an `RotatedEventStore` from config. Parameters: _config -- the configuration file options read from file(s). **options -- various options given to the specific event store. Shall not be used with this event store. Warning will be logged f...
def from_config(config, **options): """Instantiate an `RotatedEventStore` from config. Parameters: _config -- the configuration file options read from file(s). **options -- various options given to the specific event store. Shall not be used with this event store...
Construct a filename for a database. Parameters: batchno -- batch number for the rotated database. Returns the constructed path as a string.
def _construct_filename(self, batchno): """Construct a filename for a database. Parameters: batchno -- batch number for the rotated database. Returns the constructed path as a string. """ return os.path.join(self.dirpath, "{0}.{1}".format(se...
Rotate the files to disk. This is done by calling `store.close()` on each store, bumping the batchno and reopening the stores using their factories.
def rotate(self): """Rotate the files to disk. This is done by calling `store.close()` on each store, bumping the batchno and reopening the stores using their factories. """ self._logger.info('Rotating data files. New batch number will be: %s', self.ba...
Find the batch number that contains a certain event. Parameters: uuid -- the event uuid to search for. returns -- a batch number, or None if not found.
def _find_batch_containing_event(self, uuid): """Find the batch number that contains a certain event. Parameters: uuid -- the event uuid to search for. returns -- a batch number, or None if not found. """ if self.estore.key_exists(uuid): # Reusing alread...
Query a slice of the events. Events are always returned in the order the were added. It also queries older event archives until it finds the event UUIDs necessary. Parameters: from_ -- if not None, return only events added after the event with id `from_`. ...
def get_events(self, from_=None, to=None): """Query a slice of the events. Events are always returned in the order the were added. It also queries older event archives until it finds the event UUIDs necessary. Parameters: from_ -- if not None, return only events adde...
Instantiate an `SyncedRotationEventStores` from config. Parameters: config -- the configuration file options read from file(s). **options -- various options given to the specific event store. Shall not be used with this event store. Warning will be logged ...
def from_config(config, **options): """Instantiate an `SyncedRotationEventStores` from config. Parameters: config -- the configuration file options read from file(s). **options -- various options given to the specific event store. Shall not be used with this even...
Add an event and its corresponding key to the store.
def add_event(self, key, event): """Add an event and its corresponding key to the store.""" if self.key_exists(key): # This check might actually also be done further up in the chain # (read: SQLiteEventStore). Could potentially be removed if it # requires a lot of pro...
Get the current terminal size, returns a ``(height, width)`` tuple.
def _termsize(): ''' Get the current terminal size, returns a ``(height, width)`` tuple. ''' try: return struct.unpack( 'hh', fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, '1234') ) except: return ( int(os.environ.get('LINES', 25)),...
Display stream contents in hexadecimal and ASCII format. The ``stream`` specified must either be a file-like object that supports the ``read`` method to receive bytes, or it can be a string. To dump a file:: >>> hexdump(file(filename)) # doctest: +SKIP Or to dump stdin:: >>> impo...
def hexdump(stream): ''' Display stream contents in hexadecimal and ASCII format. The ``stream`` specified must either be a file-like object that supports the ``read`` method to receive bytes, or it can be a string. To dump a file:: >>> hexdump(file(filename)) # doctest: +SKIP Or ...
Return a printable string from the input ``sequence`` :param sequence: byte or string sequence >>> print(printable('\\x1b[1;34mtest\\x1b[0m')) .[1;34mtest.[0m >>> printable('\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x06') == '........' True >>> print(printable('12345678')) 12345678 >>> pri...
def printable(sequence): ''' Return a printable string from the input ``sequence`` :param sequence: byte or string sequence >>> print(printable('\\x1b[1;34mtest\\x1b[0m')) .[1;34mtest.[0m >>> printable('\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x06') == '........' True >>> print(printable(...
Return a spark line for the given data set. :value data: sequence of numeric values >>> print sparkline([1, 2, 3, 4, 5, 6, 5, 4, 3, 1, 5, 6]) # doctest: +SKIP ▁▂▃▄▅▆▅▄▃▁▅▆
def sparkline(data): ''' Return a spark line for the given data set. :value data: sequence of numeric values >>> print sparkline([1, 2, 3, 4, 5, 6, 5, 4, 3, 1, 5, 6]) # doctest: +SKIP ▁▂▃▄▅▆▅▄▃▁▅▆ ''' min_value = float(min(data)) max_value = float(max(data)) steps = (max_value -...
Return the throughput in (intelli)bytes per second. :param sample: number of samples sent :param window: default 1, sample window in seconds or :class:`datetime.timedelta` object :param format: default 'decimal', see :func:`natural.size.filesize` >>> print(throughput(123456, 42)) ...
def throughput(sample, window=1, format='decimal'): ''' Return the throughput in (intelli)bytes per second. :param sample: number of samples sent :param window: default 1, sample window in seconds or :class:`datetime.timedelta` object :param format: default 'decimal', see :func:`...
Retrieves the SnowballStemmer for a particular language. Args: language (str): ISO-639-1 code of the language.
def get_language_stemmer(language): """Retrieves the SnowballStemmer for a particular language. Args: language (str): ISO-639-1 code of the language. """ from lunr.languages import SUPPORTED_LANGUAGES from nltk.stem.snowball import SnowballStemmer return SnowballStemmer(SUPPORTED_LANGU...
Wrapper around a NLTK SnowballStemmer, which includes stop words for each language. Args: stemmer (SnowballStemmer): Stemmer instance that performs the stemming. token (lunr.Token): The token to stem. i (int): The index of the token in a set. tokens (list): A list of tokens repr...
def nltk_stemmer(stemmer, token, i=None, tokens=None): """Wrapper around a NLTK SnowballStemmer, which includes stop words for each language. Args: stemmer (SnowballStemmer): Stemmer instance that performs the stemming. token (lunr.Token): The token to stem. i (int): The index of th...
Returns True if object is not a string but is iterable
def is_seq(obj): """ Returns True if object is not a string but is iterable """ if not hasattr(obj, '__iter__'): return False if isinstance(obj, basestring): return False return True
Decorate a migration function with this method to make it available for migrating cases.
def register(cls, func): """ Decorate a migration function with this method to make it available for migrating cases. """ cls._add_version_info(func) cls._upgrade_funcs.add(func) return func
Add .source and .target attributes to the registered function.
def _add_version_info(func): """ Add .source and .target attributes to the registered function. """ pattern = r'v(?P<source>\d+)_to_(?P<target>\d+)$' match = re.match(pattern, func.__name__) if not match: raise ValueError("migration function name must match " + pattern) func.source, func.target = map(i...
Migrate the doc from its current version to the target version and return it.
def migrate_doc(self, doc): """ Migrate the doc from its current version to the target version and return it. """ orig_ver = doc.get(self.version_attribute_name, 0) funcs = self._get_migrate_funcs(orig_ver, self.target_version) for func in funcs: func(self, doc) doc[self.version_attribute_name] = fu...
>>> @Manager.register ... def v1_to_2(manager, doc): ... doc['foo'] = 'bar' >>> @Manager.register ... def v2_to_1(manager, doc): ... del doc['foo'] >>> @Manager.register ... def v2_to_3(manager, doc): ... doc['foo'] = doc['foo'] + ' baz' >>> funcs = list(Manager._get_migrate_funcs(1, 3)) ...
def _get_migrate_funcs(cls, orig_version, target_version): """ >>> @Manager.register ... def v1_to_2(manager, doc): ... doc['foo'] = 'bar' >>> @Manager.register ... def v2_to_1(manager, doc): ... del doc['foo'] >>> @Manager.register ... def v2_to_3(manager, doc): ... doc['foo'] = doc['fo...
Return exactly one function to convert from source to target
def _get_func(cls, source_ver, target_ver): """ Return exactly one function to convert from source to target """ matches = ( func for func in cls._upgrade_funcs if func.source == source_ver and func.target == target_ver ) try: match, = matches except ValueError: raise ValueError( f"No migr...
Get the full content object :param brain_or_object: A single catalog brain or content object :type brain_or_object: PortalObject/ATContentType/DexterityContentType /CatalogBrain :returns: The full object
def get_object(brain_or_object): """Get the full content object :param brain_or_object: A single catalog brain or content object :type brain_or_object: PortalObject/ATContentType/DexterityContentType /CatalogBrain :returns: The full object """ if not is_object(brain_or_object): fail...
Get the Plone UID for this object :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: Plone UID :rtype: string
def get_uid(brain_or_object): """Get the Plone UID for this object :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: Plone UID :rtype: string """ if is_portal(brain_or_object): return '0'...
Get the icon of the content object :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :param html_tag: A value of 'True' returns the HTML tag, else the image url :type html_tag: bool :returns: HTML '<img>' tag if '...
def get_icon(brain_or_object, html_tag=True): """Get the icon of the content object :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :param html_tag: A value of 'True' returns the HTML tag, else the image url :ty...
Find an object by a given UID :param uid: The UID of the object to find :type uid: string :returns: Found Object or None
def get_object_by_uid(uid, default=_marker): """Find an object by a given UID :param uid: The UID of the object to find :type uid: string :returns: Found Object or None """ # nothing to do here if not uid: if default is not _marker: return default fail("get_obje...
Find an object by a given physical path or absolute_url :param path: The physical path of the object to find :type path: string :returns: Found Object or None
def get_object_by_path(path, default=_marker): """Find an object by a given physical path or absolute_url :param path: The physical path of the object to find :type path: string :returns: Found Object or None """ # nothing to do here if not path: if default is not _marker: ...
Calculate the physical path of this object :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: Physical path of the object :rtype: string
def get_path(brain_or_object): """Calculate the physical path of this object :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: Physical path of the object :rtype: string """ if is_brain(brain_or_...
Get the review history for the given brain or context. :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: Workflow history :rtype: [{}, ...]
def get_review_history(brain_or_object, rev=True): """Get the review history for the given brain or context. :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: Workflow history :rtype: [{}, ...] """ ...
Get the current workflow status of the given brain or context. :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :param state_var: The name of the state variable :type state_var: string :returns: Status :rtype...
def get_workflow_status_of(brain_or_object, state_var="review_state"): """Get the current workflow status of the given brain or context. :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :param state_var: The name of ...
Get the `cancellation_state` of an object :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: Value of the review_status variable :rtype: String
def get_cancellation_status(brain_or_object, default="active"): """Get the `cancellation_state` of an object :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: Value of the review_status variable :rtype: ...
Get the `cancellation_state` of an objct :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: Value of the review_status variable :rtype: String
def get_inactive_status(brain_or_object, default="active"): """Get the `cancellation_state` of an objct :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: Value of the review_status variable :rtype: Strin...
Performs a workflow transition for the passed in object. :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: The object where the transtion was performed
def do_transition_for(brain_or_object, transition): """Performs a workflow transition for the passed in object. :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: The object where the transtion was performed ...
Tries to convert the passed in value to Zope's DateTime :param value: The value to be converted to a valid DateTime :type value: str, DateTime or datetime :return: The DateTime representation of the value passed in or default
def to_date(value, default=None): """Tries to convert the passed in value to Zope's DateTime :param value: The value to be converted to a valid DateTime :type value: str, DateTime or datetime :return: The DateTime representation of the value passed in or default """ if isinstance(value, DateTim...
Ses the logging level of the script based on command line options. Arguments: - `verbose`: - `quiet`:
def set_log_level(verbose, quiet): ''' Ses the logging level of the script based on command line options. Arguments: - `verbose`: - `quiet`: ''' if quiet: verbose = -1 if verbose < 0: verbose = logging.CRITICAL elif verbose == 0: verbose = logging.WARNING ...
Automatically detects the pattern file format, and determines whether the Aho-Corasick string matching should pay attention to word boundaries or not. Arguments: - `pattern_filename`: - `encoding`: - `on_word_boundaries`:
def detect_pattern_format(pattern_filename, encoding, on_word_boundaries): ''' Automatically detects the pattern file format, and determines whether the Aho-Corasick string matching should pay attention to word boundaries or not. Arguments: - `pattern_filename`: - `encoding`: - `on_word...
Process escaped characters in ``sval``. Arguments: - `sval`:
def sub_escapes(sval): ''' Process escaped characters in ``sval``. Arguments: - `sval`: ''' sval = sval.replace('\\a', '\a') sval = sval.replace('\\b', '\x00') sval = sval.replace('\\f', '\f') sval = sval.replace('\\n', '\n') sval = sval.replace('\\r', '\r') sval = sval.repl...
Constructs a finite state machine for performing string rewriting. Arguments: - `pattern_filename`: - `pattern_format`: - `encoding`: - `on_word_boundaries`:
def build_trie(pattern_filename, pattern_format, encoding, on_word_boundaries): ''' Constructs a finite state machine for performing string rewriting. Arguments: - `pattern_filename`: - `pattern_format`: - `encoding`: - `on_word_boundaries`: ''' boundaries = on_word_boundaries i...
Prints warning messages for every node that has both a value and a longest_prefix.
def warn_prefix_values(trie): ''' Prints warning messages for every node that has both a value and a longest_prefix. ''' for current, _parent in trie.dfs(): if current.has_value and current.longest_prefix is not None: LOGGER.warn(('pattern {} (value {}) is a superstring of patter...
Rewrites a string using the given trie object. Arguments: - `sval`: - `trie`: - `boundaries`: - `slow`:
def rewrite_str_with_trie(sval, trie, boundaries = False, slow = False): ''' Rewrites a string using the given trie object. Arguments: - `sval`: - `trie`: - `boundaries`: - `slow`: ''' if boundaries: sval = fsed.ahocorasick.boundary_transform(sval) if slow: sval ...
Search and replace on INPUT_FILE(s) (or standard input), with matching on fixed strings.
def main(pattern_filename, input_filenames, pattern_format, output_filename, encoding, words, by_line, slow, verbose, quiet): ''' Search and replace on INPUT_FILE(s) (or standard input), with matching on fixed strings. ''' set_log_level(verbose, quiet) if slow: by_line ...
Register a function with the pipeline.
def register_function(cls, fn, label): """Register a function with the pipeline.""" if label in cls.registered_functions: log.warning("Overwriting existing registered function %s", label) fn.label = label cls.registered_functions[fn.label] = fn
Loads a previously serialised pipeline.
def load(cls, serialised): """Loads a previously serialised pipeline.""" pipeline = cls() for fn_name in serialised: try: fn = cls.registered_functions[fn_name] except KeyError: raise BaseLunrException( "Cannot load unre...
Adds new functions to the end of the pipeline. Functions must accept three arguments: - Token: A lunr.Token object which will be updated - i: The index of the token in the set - tokens: A list of tokens representing the set
def add(self, *args): """Adds new functions to the end of the pipeline. Functions must accept three arguments: - Token: A lunr.Token object which will be updated - i: The index of the token in the set - tokens: A list of tokens representing the set """ for fn in ...
Adds a single function after a function that already exists in the pipeline.
def after(self, existing_fn, new_fn): """Adds a single function after a function that already exists in the pipeline.""" self.warn_if_function_not_registered(new_fn) try: index = self._stack.index(existing_fn) self._stack.insert(index + 1, new_fn) except V...
Runs the current list of functions that make up the pipeline against the passed tokens.
def run(self, tokens): """Runs the current list of functions that make up the pipeline against the passed tokens.""" for fn in self._stack: results = [] for i, token in enumerate(tokens): # JS ignores additional arguments to the functions but we ...
Convenience method for passing a string through a pipeline and getting strings out. This method takes care of wrapping the passed string in a token and mapping the resulting tokens back to strings.
def run_string(self, string, metadata=None): """Convenience method for passing a string through a pipeline and getting strings out. This method takes care of wrapping the passed string in a token and mapping the resulting tokens back to strings.""" token = Token(string, metadata) ...
Use the same MongoDB client as pmxbot if available.
def get_client(): """ Use the same MongoDB client as pmxbot if available. """ with contextlib.suppress(Exception): store = Storage.from_URI() assert isinstance(store, pmxbot.storage.MongoDBStorage) return store.db.database.client
Create a database in a shard. !create-db-in-shard {db name} {shard name}
def cdbs(client, event, channel, nick, rest): """ Create a database in a shard. !create-db-in-shard {db name} {shard name} """ db_name, shard = shlex.split(rest) return sharding.create_db_in_shard(db_name, shard, client=get_client())
In a sharded cluster, create a database in a particular shard.
def create_db_in_shard(db_name, shard, client=None): """ In a sharded cluster, create a database in a particular shard. """ client = client or pymongo.MongoClient() # flush the router config to ensure it's not stale res = client.admin.command('flushRouterConfig') if not res.get('ok'): ...
Calculates the Luhn checksum for `number` :param number: string or int :param chars: string >>> luhn_checksum(1234) 4
def luhn_checksum(number, chars=DIGITS): ''' Calculates the Luhn checksum for `number` :param number: string or int :param chars: string >>> luhn_checksum(1234) 4 ''' length = len(chars) number = [chars.index(n) for n in reversed(str(number))] return ( sum(number[::2])...
Calculate the Luhn check digit for ``number``. :param number: string :param chars: string >>> luhn_calc('42') '2'
def luhn_calc(number, chars=DIGITS): ''' Calculate the Luhn check digit for ``number``. :param number: string :param chars: string >>> luhn_calc('42') '2' ''' checksum = luhn_checksum(str(number) + chars[0], chars) return chars[-checksum]
Converts a number to a string of decimals in base 10. >>> to_decimal(123) '123' >>> to_decimal('o123') '83' >>> to_decimal('b101010') '42' >>> to_decimal('0x2a') '42'
def to_decimal(number, strip='- '): ''' Converts a number to a string of decimals in base 10. >>> to_decimal(123) '123' >>> to_decimal('o123') '83' >>> to_decimal('b101010') '42' >>> to_decimal('0x2a') '42' ''' if isinstance(number, six.integer_types): return str...
thread safe redirect of stdout and stderr :param stdout: :param stderr: :return:
def output_redirect(stdout, stderr): """ thread safe redirect of stdout and stderr :param stdout: :param stderr: :return: """ import sys import threading if not redirect: originals = (sys.stdout.write, sys.stderr.write) class Logger: def __init__(self, fun): self.buffer = "" ...
Returns a method from a given class or instance. When the method doest not exist, it returns `None`. Also works with properties and cached properties.
def get_class_method(cls_or_inst, method_name): """ Returns a method from a given class or instance. When the method doest not exist, it returns `None`. Also works with properties and cached properties. """ cls = cls_or_inst if isinstance(cls_or_inst, type) else cls_or_inst.__class__ meth = geta...
Combine HDUList objects using algorithm 'method
def combine(method, images, masks=None, dtype=None, region=None, zeros=None, scales=None, weights=None, include_variance=True, datamodel=None, method_name=""): """Combine HDUList objects using algorithm 'method'""" import numina.datamodel nimages = len(images) # processing mas...
Manage a list of FITS resources
def manage_fits(list_of_frame): """Manage a list of FITS resources""" import astropy.io.fits as fits import numina.types.dataframe as df refs = [] for frame in list_of_frame: if isinstance(frame, str): ref = fits.open(frame) refs.append(ref) elif isinstance(...
Extract metadata from serialized file
def extract_db_info(self, obj, keys): """Extract metadata from serialized file""" objl = self.convert(obj) result = super(LinesCatalog, self).extract_db_info(objl, keys) result['tags'] = {} result['type'] = 'LinesCatalog' result['uuid'] = str(uuid.uuid1()) resu...
Set debugging level based on debugplot value. Parameters ---------- debugplot : int Debugging level for messages and plots. For details see 'numina.array.display.pause_debugplot.py'.
def logging_from_debugplot(debugplot): """Set debugging level based on debugplot value. Parameters ---------- debugplot : int Debugging level for messages and plots. For details see 'numina.array.display.pause_debugplot.py'. """ if isinstance(debugplot, int): if...
Add/replace FITS key Add/replace the key keyname with value keyval of type keytype in filename. Parameters: ---------- keyname : str FITS Keyword name. keyval : str FITS keyword value. keytype: str FITS keyword type: int, float, str or bool. filaname : str F...
def add_key_val(keyname, keyval, keytype, filename, extnum): """Add/replace FITS key Add/replace the key keyname with value keyval of type keytype in filename. Parameters: ---------- keyname : str FITS Keyword name. keyval : str FITS keyword value. keytype: str FITS...
Auxiliary function to display 1d plot. Parameters ---------- ycut : 1d numpy array, float Array to be displayed. title : string Plot title. show : bool If True, the function shows the displayed image. Otherwise plt.show() is expected to be executed outside. plot_...
def ximplot(ycut, title=None, show=True, plot_bbox=(0, 0), geometry=(0, 0, 640, 480), tight_layout=True, debugplot=None): """Auxiliary function to display 1d plot. Parameters ---------- ycut : 1d numpy array, float Array to be displayed. title : string Plot t...
Parameters ---------- ob (ObservationResult): Observation result reqtags (dict): Keywords Returns ------- A dictionary
def get_tags_from_full_ob(ob, reqtags=None): """ Parameters ---------- ob (ObservationResult): Observation result reqtags (dict): Keywords Returns ------- A dictionary """ # each instrument should have one # perhaps each mode... files = ob.frames cfiles = ob.childre...
Oversample spectrum. Parameters ---------- sp : numpy array Spectrum to be oversampled. crval1 : float Abscissae of the center of the first pixel in the original spectrum 'sp'. cdelt1 : float Abscissae increment corresponding to 1 pixel in the original spectr...
def oversample1d(sp, crval1, cdelt1, oversampling=1, debugplot=0): """Oversample spectrum. Parameters ---------- sp : numpy array Spectrum to be oversampled. crval1 : float Abscissae of the center of the first pixel in the original spectrum 'sp'. cdelt1 : float A...
See http://scipy-cookbook.readthedocs.io/items/Rebinning.html Note: integer division in the computation of 'factor' has been included to avoid the following runtime message: VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future from __futu...
def rebin(a, *args): """See http://scipy-cookbook.readthedocs.io/items/Rebinning.html Note: integer division in the computation of 'factor' has been included to avoid the following runtime message: VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error i...
Resample 2D image using a shift in the x direction (flux is preserved). Parameters ---------- image2d_orig : numpy array 2D image to be resampled. xoffset : float Offset to be applied. Returns ------- image2d_resampled : numpy array Resampled 2D image.
def shiftx_image2d_flux(image2d_orig, xoffset): """Resample 2D image using a shift in the x direction (flux is preserved). Parameters ---------- image2d_orig : numpy array 2D image to be resampled. xoffset : float Offset to be applied. Returns ------- image2d_resampled ...
Resample a 1D/2D image using NAXIS1, CDELT1, CRVAL1, and CRPIX1. The same NAXIS1, CDELT1, CRVAL1, and CRPIX1 are employed for all the scans (rows) of the original 'image2d'. The wavelength calibrated output image has dimensions NAXIS1 * NSCAN, where NSCAN is the original number of scans (rows) of the o...
def resample_image2d_flux(image2d_orig, naxis1, cdelt1, crval1, crpix1, coeff): """Resample a 1D/2D image using NAXIS1, CDELT1, CRVAL1, and CRPIX1. The same NAXIS1, CDELT1, CRVAL1, and CRPIX1 are employed for all the scans (rows) of the original 'image2d'. The wavelength calib...
Compute borders of pixels for interpolation. The border of the pixel is assumed to be midway of the wls
def map_borders(wls): """Compute borders of pixels for interpolation. The border of the pixel is assumed to be midway of the wls """ midpt_wl = 0.5 * (wls[1:] + wls[:-1]) all_borders = np.zeros((wls.shape[0] + 1,)) all_borders[1:-1] = midpt_wl all_borders[0] = 2 * wls[0] - midpt_wl[0] a...
Import an object given its fully qualified name.
def import_object(path): """Import an object given its fully qualified name.""" spl = path.split('.') if len(spl) == 1: return importlib.import_module(path) # avoid last part for the moment cls = spl[-1] mods = '.'.join(spl[:-1]) mm = importlib.import_module(mods) # try to get t...
Return an argparse.ArgumentParser object with losser's arguments. Other projects can call this to get an ArgumentParser with losser's command line interface to use as a parent parser for their own parser. For example:: parent_parser = losser.cli.make_parser( add_help=False, exclude_arg...
def make_parser(add_help=True, exclude_args=None): """Return an argparse.ArgumentParser object with losser's arguments. Other projects can call this to get an ArgumentParser with losser's command line interface to use as a parent parser for their own parser. For example:: parent_parser = losse...
Parse the command line arguments, return an argparse namespace object. Other projects can call this function and pass in their own ArgumentParser object (which should have a losser ArgumentParser from make_parser() above as parent) to do the argument parsing and get the result (this does some custom po...
def parse(parser=None, args=None): """Parse the command line arguments, return an argparse namespace object. Other projects can call this function and pass in their own ArgumentParser object (which should have a losser ArgumentParser from make_parser() above as parent) to do the argument parsing and ge...
Read command-line args and stdin, return the result. Read the command line arguments and the input data from stdin, pass them to the table() function to do the filter and transform, and return the string of CSV- or JSON-formatted text that should be written to stdout. Note that although the output dat...
def do(parser=None, args=None, in_=None, table_function=None): """Read command-line args and stdin, return the result. Read the command line arguments and the input data from stdin, pass them to the table() function to do the filter and transform, and return the string of CSV- or JSON-formatted text th...
Call do() and if it raises an exception then sys.exit() appropriately. This makes sure that any usage and error messages are printed correctly, and that the exit code is right. do() itself doesn't call sys.exit() because we want it to be callable from tests that check that it raises the right exceptio...
def main(): """Call do() and if it raises an exception then sys.exit() appropriately. This makes sure that any usage and error messages are printed correctly, and that the exit code is right. do() itself doesn't call sys.exit() because we want it to be callable from tests that check that it raises...
Compute A-B-(B-A). Note that 'list_of_fileinfo' must contain 4 file names. Parameters ---------- list_of_fileinfo : list of strings List of the for files corresponding to the ABBA observation. outfile : string Base name for the output FITS file name. extnum : int Extens...
def compute_abba_result(list_of_fileinfo, outfile, extnum=0, noheader=False, save_partial=False, debugplot=0): """Compute A-B-(B-A). Note that 'list_of_fileinfo' must contain 4 file names. Parameters ---------- list_of_fileinfo : list of strings List of the for file...
Generate a normalized Gaussian profile from its FWHM
def generate_gaussian_profile(seeing_fwhm): """Generate a normalized Gaussian profile from its FWHM""" FWHM_G = 2 * math.sqrt(2 * math.log(2)) sigma = seeing_fwhm / FWHM_G amplitude = 1.0 / (2 * math.pi * sigma * sigma) seeing_model = Gaussian2D(amplitude=amplitude, x_m...
Generate a normalized Moffat profile from its FWHM and alpha
def generate_moffat_profile(seeing_fwhm, alpha): """Generate a normalized Moffat profile from its FWHM and alpha""" scale = 2 * math.sqrt(2**(1.0 / alpha) - 1) gamma = seeing_fwhm / scale amplitude = 1.0 / math.pi * (alpha - 1) / gamma**2 seeing_model = Moffat2D(amplitude=amplitude, ...
Converts a model field to a dictionary
def field_to_dict(field, instance): """ Converts a model field to a dictionary """ # avoid a circular import from django.db.models.fields.related import ManyToManyField return (many_to_many_field_to_dict(field, instance) if isinstance(field, ManyToManyField) else field.value_from_ob...
The same implementation as django model_to_dict but editable fields are allowed
def model_to_dict(instance, fields=None, exclude=None): """ The same implementation as django model_to_dict but editable fields are allowed """ return { field.name: field_to_dict(field, instance) for field in chain(instance._meta.concrete_fields, instance._meta.many_to_many) # pylint: ...
Because standard distinct used on the all fields are very slow and works only with PostgreSQL database this method provides alternative to the standard distinct method. :return: qs with unique objects
def fast_distinct(self): """ Because standard distinct used on the all fields are very slow and works only with PostgreSQL database this method provides alternative to the standard distinct method. :return: qs with unique objects """ return self.model.objects.filter(pk__i...
Changes a given `changed_fields` on each object in the queryset, saves objects and returns the changed objects in the queryset.
def change_and_save(self, update_only_changed_fields=False, **changed_fields): """ Changes a given `changed_fields` on each object in the queryset, saves objects and returns the changed objects in the queryset. """ bulk_change_and_save(self, update_only_changed_fields=update_only...
Changes a given `changed_fields` on this object, saves it and returns itself. :param update_only_changed_fields: only changed fields will be updated in the database. :param changed_fields: fields to change. :return: self
def change_and_save(self, update_only_changed_fields=False, **changed_fields): """ Changes a given `changed_fields` on this object, saves it and returns itself. :param update_only_changed_fields: only changed fields will be updated in the database. :param changed_fields: fields to change...
Replace image in filename by another image (same size) in newimage. Parameters ---------- filename : str File name where the new image will be inserted. extnum_filename : int Extension number in filename where the new image will be inserted. Note that the first extension is 1 (a...
def insert_image(filename, extnum_filename, auximage, extnum_auximage): """Replace image in filename by another image (same size) in newimage. Parameters ---------- filename : str File name where the new image will be inserted. extnum_filename : int Extension number in filename wher...
Helper for matplotlib imshow
def extent(self): """Helper for matplotlib imshow""" return ( self.intervals[1].pix1 - 0.5, self.intervals[1].pix2 - 0.5, self.intervals[0].pix1 - 0.5, self.intervals[0].pix2 - 0.5, )
Readout the detector.
def readout(self): """Readout the detector.""" elec = self.simulate_poisson_variate() elec_pre = self.saturate(elec) elec_f = self.pre_readout(elec_pre) adu_r = self.base_readout(elec_f) adu_p = self.post_readout(adu_r) self.clean_up() return adu_p
Returns a set of permission strings that this user has through his/her groups.
def get_group_permissions(self, user_obj, obj=None): """ Returns a set of permission strings that this user has through his/her groups. """ if user_obj.is_anonymous() or obj is not None: return set() if not hasattr(user_obj, '_group_perm_cache'): i...
parse limited form of arguments of function in the form a=1, b='c' as a dictionary
def parse_arg_line(fargs): """parse limited form of arguments of function in the form a=1, b='c' as a dictionary """ # Convert to literal dict fargs = fargs.strip() if fargs == '': return {} pairs = [s.strip() for s in fargs.split(',')] # find first "=" result = [] ...
Return a given `number` formatter a price for humans.
def natural_number_with_currency(number, currency, show_decimal_place=True, use_nbsp=True): """ Return a given `number` formatter a price for humans. """ humanized = '{} {}'.format( numberformat.format( number=number, decimal_sep=',', decimal_pos=2 if show_dec...
Convert
def convert(self, obj): """Convert""" # We accept None representing No Image if obj is None: return None elif isinstance(obj, six.string_types): return DataFrame(filename=obj) elif isinstance(obj, DataFrame): return obj elif isinstance(...