repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
nyergler/hieroglyph
src/hieroglyph/themes/slides2/static/scripts/md/render.py
postprocess_html
def postprocess_html(html, metadata): """Returns processed HTML to fit into the slide template format.""" if metadata.get('build_lists') and metadata['build_lists'] == 'true': html = html.replace('<ul>', '<ul class="build">') html = html.replace('<ol>', '<ol class="build">') return html
python
def postprocess_html(html, metadata): """Returns processed HTML to fit into the slide template format.""" if metadata.get('build_lists') and metadata['build_lists'] == 'true': html = html.replace('<ul>', '<ul class="build">') html = html.replace('<ol>', '<ol class="build">') return html
Returns processed HTML to fit into the slide template format.
https://github.com/nyergler/hieroglyph/blob/1ef062fad5060006566f8d6bd3b5a231ac7e0488/src/hieroglyph/themes/slides2/static/scripts/md/render.py#L49-L54
PyCQA/pylint-plugin-utils
pylint_plugin_utils/__init__.py
augment_visit
def augment_visit(linter, checker_method, augmentation): """ Augmenting a visit enables additional errors to be raised (although that case is better served using a new checker) or to suppress all warnings in certain circumstances. Augmenting functions should accept a 'chain' function, which runs the ch...
python
def augment_visit(linter, checker_method, augmentation): """ Augmenting a visit enables additional errors to be raised (although that case is better served using a new checker) or to suppress all warnings in certain circumstances. Augmenting functions should accept a 'chain' function, which runs the ch...
Augmenting a visit enables additional errors to be raised (although that case is better served using a new checker) or to suppress all warnings in certain circumstances. Augmenting functions should accept a 'chain' function, which runs the checker method and possibly any other augmentations, and secondly a...
https://github.com/PyCQA/pylint-plugin-utils/blob/43fde2104fb4e7d6aa3a6a71725bca31d44eb936/pylint_plugin_utils/__init__.py#L33-L59
PyCQA/pylint-plugin-utils
pylint_plugin_utils/__init__.py
suppress_message
def suppress_message(linter, checker_method, message_id_or_symbol, test_func): """ This wrapper allows the suppression of a message if the supplied test function returns True. It is useful to prevent one particular message from being raised in one particular case, while leaving the rest of the messages ...
python
def suppress_message(linter, checker_method, message_id_or_symbol, test_func): """ This wrapper allows the suppression of a message if the supplied test function returns True. It is useful to prevent one particular message from being raised in one particular case, while leaving the rest of the messages ...
This wrapper allows the suppression of a message if the supplied test function returns True. It is useful to prevent one particular message from being raised in one particular case, while leaving the rest of the messages intact.
https://github.com/PyCQA/pylint-plugin-utils/blob/43fde2104fb4e7d6aa3a6a71725bca31d44eb936/pylint_plugin_utils/__init__.py#L103-L149
afilipovich/gglsbl
gglsbl/storage.py
SqliteStorage.lookup_full_hashes
def lookup_full_hashes(self, hash_values): """Query DB to see if hash is blacklisted""" q = '''SELECT threat_type,platform_type,threat_entry_type, expires_at < current_timestamp AS has_expired FROM full_hash WHERE value IN ({}) ''' output = [] with self.get_cursor...
python
def lookup_full_hashes(self, hash_values): """Query DB to see if hash is blacklisted""" q = '''SELECT threat_type,platform_type,threat_entry_type, expires_at < current_timestamp AS has_expired FROM full_hash WHERE value IN ({}) ''' output = [] with self.get_cursor...
Query DB to see if hash is blacklisted
https://github.com/afilipovich/gglsbl/blob/89c4665bd6487a3689ccb6b1f3e53ff85e056103/gglsbl/storage.py#L172-L185
afilipovich/gglsbl
gglsbl/storage.py
SqliteStorage.lookup_hash_prefix
def lookup_hash_prefix(self, cues): """Lookup hash prefixes by cue (first 4 bytes of hash) Returns a tuple of (value, negative_cache_expired). """ q = '''SELECT value, MAX(negative_expires_at < current_timestamp) AS negative_cache_expired FROM hash_prefix WHERE cue IN ({...
python
def lookup_hash_prefix(self, cues): """Lookup hash prefixes by cue (first 4 bytes of hash) Returns a tuple of (value, negative_cache_expired). """ q = '''SELECT value, MAX(negative_expires_at < current_timestamp) AS negative_cache_expired FROM hash_prefix WHERE cue IN ({...
Lookup hash prefixes by cue (first 4 bytes of hash) Returns a tuple of (value, negative_cache_expired).
https://github.com/afilipovich/gglsbl/blob/89c4665bd6487a3689ccb6b1f3e53ff85e056103/gglsbl/storage.py#L187-L201
afilipovich/gglsbl
gglsbl/storage.py
SqliteStorage.store_full_hash
def store_full_hash(self, threat_list, hash_value, cache_duration, malware_threat_type): """Store full hash found for the given hash prefix""" log.info('Storing full hash %s to list %s with cache duration %s', to_hex(hash_value), str(threat_list), cache_duration) qi = '''INSERT ...
python
def store_full_hash(self, threat_list, hash_value, cache_duration, malware_threat_type): """Store full hash found for the given hash prefix""" log.info('Storing full hash %s to list %s with cache duration %s', to_hex(hash_value), str(threat_list), cache_duration) qi = '''INSERT ...
Store full hash found for the given hash prefix
https://github.com/afilipovich/gglsbl/blob/89c4665bd6487a3689ccb6b1f3e53ff85e056103/gglsbl/storage.py#L203-L222
afilipovich/gglsbl
gglsbl/storage.py
SqliteStorage.cleanup_full_hashes
def cleanup_full_hashes(self, keep_expired_for=(60 * 60 * 12)): """Remove long expired full_hash entries.""" q = '''DELETE FROM full_hash WHERE expires_at < datetime(current_timestamp, '-{} SECONDS') ''' log.info('Cleaning up full_hash entries expired more than {} seconds ago.'.format(ke...
python
def cleanup_full_hashes(self, keep_expired_for=(60 * 60 * 12)): """Remove long expired full_hash entries.""" q = '''DELETE FROM full_hash WHERE expires_at < datetime(current_timestamp, '-{} SECONDS') ''' log.info('Cleaning up full_hash entries expired more than {} seconds ago.'.format(ke...
Remove long expired full_hash entries.
https://github.com/afilipovich/gglsbl/blob/89c4665bd6487a3689ccb6b1f3e53ff85e056103/gglsbl/storage.py#L232-L238
afilipovich/gglsbl
gglsbl/storage.py
SqliteStorage.get_threat_lists
def get_threat_lists(self): """Get a list of known threat lists.""" q = '''SELECT threat_type,platform_type,threat_entry_type FROM threat_list''' output = [] with self.get_cursor() as dbc: dbc.execute(q) for h in dbc.fetchall(): threat_type, platfo...
python
def get_threat_lists(self): """Get a list of known threat lists.""" q = '''SELECT threat_type,platform_type,threat_entry_type FROM threat_list''' output = [] with self.get_cursor() as dbc: dbc.execute(q) for h in dbc.fetchall(): threat_type, platfo...
Get a list of known threat lists.
https://github.com/afilipovich/gglsbl/blob/89c4665bd6487a3689ccb6b1f3e53ff85e056103/gglsbl/storage.py#L247-L257
afilipovich/gglsbl
gglsbl/storage.py
SqliteStorage.get_client_state
def get_client_state(self): """Get a dict of known threat lists including clientState values.""" q = '''SELECT threat_type,platform_type,threat_entry_type,client_state FROM threat_list''' output = {} with self.get_cursor() as dbc: dbc.execute(q) for h in dbc.fetch...
python
def get_client_state(self): """Get a dict of known threat lists including clientState values.""" q = '''SELECT threat_type,platform_type,threat_entry_type,client_state FROM threat_list''' output = {} with self.get_cursor() as dbc: dbc.execute(q) for h in dbc.fetch...
Get a dict of known threat lists including clientState values.
https://github.com/afilipovich/gglsbl/blob/89c4665bd6487a3689ccb6b1f3e53ff85e056103/gglsbl/storage.py#L259-L269
afilipovich/gglsbl
gglsbl/storage.py
SqliteStorage.add_threat_list
def add_threat_list(self, threat_list): """Add threat list entry if it does not exist.""" q = '''INSERT OR IGNORE INTO threat_list (threat_type, platform_type, threat_entry_type, timestamp) VALUES (?, ?, ?, current_timestamp) ''' pa...
python
def add_threat_list(self, threat_list): """Add threat list entry if it does not exist.""" q = '''INSERT OR IGNORE INTO threat_list (threat_type, platform_type, threat_entry_type, timestamp) VALUES (?, ?, ?, current_timestamp) ''' pa...
Add threat list entry if it does not exist.
https://github.com/afilipovich/gglsbl/blob/89c4665bd6487a3689ccb6b1f3e53ff85e056103/gglsbl/storage.py#L271-L280
afilipovich/gglsbl
gglsbl/storage.py
SqliteStorage.delete_threat_list
def delete_threat_list(self, threat_list): """Delete threat list entry.""" log.info('Deleting cached threat list "{}"'.format(repr(threat_list))) q = '''DELETE FROM threat_list WHERE threat_type=? AND platform_type=? AND threat_entry_type=? ''' params = [threa...
python
def delete_threat_list(self, threat_list): """Delete threat list entry.""" log.info('Deleting cached threat list "{}"'.format(repr(threat_list))) q = '''DELETE FROM threat_list WHERE threat_type=? AND platform_type=? AND threat_entry_type=? ''' params = [threa...
Delete threat list entry.
https://github.com/afilipovich/gglsbl/blob/89c4665bd6487a3689ccb6b1f3e53ff85e056103/gglsbl/storage.py#L282-L290
afilipovich/gglsbl
gglsbl/storage.py
SqliteStorage.hash_prefix_list_checksum
def hash_prefix_list_checksum(self, threat_list): """Returns SHA256 checksum for alphabetically-sorted concatenated list of hash prefixes""" q = '''SELECT value FROM hash_prefix WHERE threat_type=? AND platform_type=? AND threat_entry_type=? ORDER BY value ''' ...
python
def hash_prefix_list_checksum(self, threat_list): """Returns SHA256 checksum for alphabetically-sorted concatenated list of hash prefixes""" q = '''SELECT value FROM hash_prefix WHERE threat_type=? AND platform_type=? AND threat_entry_type=? ORDER BY value ''' ...
Returns SHA256 checksum for alphabetically-sorted concatenated list of hash prefixes
https://github.com/afilipovich/gglsbl/blob/89c4665bd6487a3689ccb6b1f3e53ff85e056103/gglsbl/storage.py#L300-L311
afilipovich/gglsbl
gglsbl/storage.py
SqliteStorage.remove_hash_prefix_indices
def remove_hash_prefix_indices(self, threat_list, indices): """Remove records matching idices from a lexicographically-sorted local threat list.""" batch_size = 40 q = '''DELETE FROM hash_prefix WHERE threat_type=? AND platform_type=? AND threat_entry_type=? AND value IN ({}) ...
python
def remove_hash_prefix_indices(self, threat_list, indices): """Remove records matching idices from a lexicographically-sorted local threat list.""" batch_size = 40 q = '''DELETE FROM hash_prefix WHERE threat_type=? AND platform_type=? AND threat_entry_type=? AND value IN ({}) ...
Remove records matching idices from a lexicographically-sorted local threat list.
https://github.com/afilipovich/gglsbl/blob/89c4665bd6487a3689ccb6b1f3e53ff85e056103/gglsbl/storage.py#L344-L359
afilipovich/gglsbl
gglsbl/storage.py
SqliteStorage.dump_hash_prefix_values
def dump_hash_prefix_values(self): """Export all hash prefix values. Returns a list of known hash prefix values """ q = '''SELECT distinct value from hash_prefix''' output = [] with self.get_cursor() as dbc: dbc.execute(q) output = [bytes(r[0]) fo...
python
def dump_hash_prefix_values(self): """Export all hash prefix values. Returns a list of known hash prefix values """ q = '''SELECT distinct value from hash_prefix''' output = [] with self.get_cursor() as dbc: dbc.execute(q) output = [bytes(r[0]) fo...
Export all hash prefix values. Returns a list of known hash prefix values
https://github.com/afilipovich/gglsbl/blob/89c4665bd6487a3689ccb6b1f3e53ff85e056103/gglsbl/storage.py#L361-L371
RedFantom/mtTkinter
mttkinter/mtTkinter.py
_check_events
def _check_events(tk): """Checks events in the queue on a given Tk instance""" used = False try: # Process all enqueued events, then exit. while True: try: # Get an event request from the queue. method, args, kwargs, response_queue = tk.tk._event_...
python
def _check_events(tk): """Checks events in the queue on a given Tk instance""" used = False try: # Process all enqueued events, then exit. while True: try: # Get an event request from the queue. method, args, kwargs, response_queue = tk.tk._event_...
Checks events in the queue on a given Tk instance
https://github.com/RedFantom/mtTkinter/blob/0102da6eeb0da22df7d82660363a0b355b1618c6/mttkinter/mtTkinter.py#L178-L214
afilipovich/gglsbl
gglsbl/client.py
SafeBrowsingList.update_hash_prefix_cache
def update_hash_prefix_cache(self): """Update locally cached threat lists.""" try: self.storage.cleanup_full_hashes() self.storage.commit() self._sync_threat_lists() self.storage.commit() self._sync_hash_prefix_cache() except Exception:...
python
def update_hash_prefix_cache(self): """Update locally cached threat lists.""" try: self.storage.cleanup_full_hashes() self.storage.commit() self._sync_threat_lists() self.storage.commit() self._sync_hash_prefix_cache() except Exception:...
Update locally cached threat lists.
https://github.com/afilipovich/gglsbl/blob/89c4665bd6487a3689ccb6b1f3e53ff85e056103/gglsbl/client.py#L42-L52
afilipovich/gglsbl
gglsbl/client.py
SafeBrowsingList._sync_full_hashes
def _sync_full_hashes(self, hash_prefixes): """Download full hashes matching hash_prefixes. Also update cache expiration timestamps. """ client_state = self.storage.get_client_state() self.api_client.fair_use_delay() fh_response = self.api_client.get_full_hashes(hash_pre...
python
def _sync_full_hashes(self, hash_prefixes): """Download full hashes matching hash_prefixes. Also update cache expiration timestamps. """ client_state = self.storage.get_client_state() self.api_client.fair_use_delay() fh_response = self.api_client.get_full_hashes(hash_pre...
Download full hashes matching hash_prefixes. Also update cache expiration timestamps.
https://github.com/afilipovich/gglsbl/blob/89c4665bd6487a3689ccb6b1f3e53ff85e056103/gglsbl/client.py#L96-L121
afilipovich/gglsbl
gglsbl/client.py
SafeBrowsingList.lookup_url
def lookup_url(self, url): """Look up specified URL in Safe Browsing threat lists.""" if type(url) is not str: url = url.encode('utf8') if not url.strip(): raise ValueError("Empty input string.") url_hashes = URL(url).hashes try: list_names = s...
python
def lookup_url(self, url): """Look up specified URL in Safe Browsing threat lists.""" if type(url) is not str: url = url.encode('utf8') if not url.strip(): raise ValueError("Empty input string.") url_hashes = URL(url).hashes try: list_names = s...
Look up specified URL in Safe Browsing threat lists.
https://github.com/afilipovich/gglsbl/blob/89c4665bd6487a3689ccb6b1f3e53ff85e056103/gglsbl/client.py#L123-L138
afilipovich/gglsbl
gglsbl/client.py
SafeBrowsingList._lookup_hashes
def _lookup_hashes(self, full_hashes): """Lookup URL hash in blacklists Returns names of lists it was found in. """ full_hashes = list(full_hashes) cues = [fh[0:4] for fh in full_hashes] result = [] matching_prefixes = {} matching_full_hashes = set() ...
python
def _lookup_hashes(self, full_hashes): """Lookup URL hash in blacklists Returns names of lists it was found in. """ full_hashes = list(full_hashes) cues = [fh[0:4] for fh in full_hashes] result = [] matching_prefixes = {} matching_full_hashes = set() ...
Lookup URL hash in blacklists Returns names of lists it was found in.
https://github.com/afilipovich/gglsbl/blob/89c4665bd6487a3689ccb6b1f3e53ff85e056103/gglsbl/client.py#L140-L185
afilipovich/gglsbl
gglsbl/protocol.py
SafeBrowsingApiClient.get_threats_lists
def get_threats_lists(self): """Retrieve all available threat lists""" response = self.service.threatLists().list().execute() self.set_wait_duration(response.get('minimumWaitDuration')) return response['threatLists']
python
def get_threats_lists(self): """Retrieve all available threat lists""" response = self.service.threatLists().list().execute() self.set_wait_duration(response.get('minimumWaitDuration')) return response['threatLists']
Retrieve all available threat lists
https://github.com/afilipovich/gglsbl/blob/89c4665bd6487a3689ccb6b1f3e53ff85e056103/gglsbl/protocol.py#L99-L103
afilipovich/gglsbl
gglsbl/protocol.py
SafeBrowsingApiClient.get_threats_update
def get_threats_update(self, client_state): """Fetch hash prefixes update for given threat list. client_state is a dict which looks like {(threatType, platformType, threatEntryType): clientState} """ request_body = { "client": { "clientId": self.client_id, ...
python
def get_threats_update(self, client_state): """Fetch hash prefixes update for given threat list. client_state is a dict which looks like {(threatType, platformType, threatEntryType): clientState} """ request_body = { "client": { "clientId": self.client_id, ...
Fetch hash prefixes update for given threat list. client_state is a dict which looks like {(threatType, platformType, threatEntryType): clientState}
https://github.com/afilipovich/gglsbl/blob/89c4665bd6487a3689ccb6b1f3e53ff85e056103/gglsbl/protocol.py#L106-L132
afilipovich/gglsbl
gglsbl/protocol.py
SafeBrowsingApiClient.get_full_hashes
def get_full_hashes(self, prefixes, client_state): """Find full hashes matching hash prefixes. client_state is a dict which looks like {(threatType, platformType, threatEntryType): clientState} """ request_body = { "client": { "clientId": self.client_id, ...
python
def get_full_hashes(self, prefixes, client_state): """Find full hashes matching hash prefixes. client_state is a dict which looks like {(threatType, platformType, threatEntryType): clientState} """ request_body = { "client": { "clientId": self.client_id, ...
Find full hashes matching hash prefixes. client_state is a dict which looks like {(threatType, platformType, threatEntryType): clientState}
https://github.com/afilipovich/gglsbl/blob/89c4665bd6487a3689ccb6b1f3e53ff85e056103/gglsbl/protocol.py#L135-L165
afilipovich/gglsbl
gglsbl/protocol.py
URL.hashes
def hashes(self): """Hashes of all possible permutations of the URL in canonical form""" for url_variant in self.url_permutations(self.canonical): url_hash = self.digest(url_variant) yield url_hash
python
def hashes(self): """Hashes of all possible permutations of the URL in canonical form""" for url_variant in self.url_permutations(self.canonical): url_hash = self.digest(url_variant) yield url_hash
Hashes of all possible permutations of the URL in canonical form
https://github.com/afilipovich/gglsbl/blob/89c4665bd6487a3689ccb6b1f3e53ff85e056103/gglsbl/protocol.py#L187-L191
afilipovich/gglsbl
gglsbl/protocol.py
URL.canonical
def canonical(self): """Convert URL to its canonical form.""" def full_unescape(u): uu = urllib.unquote(u) if uu == u: return uu else: return full_unescape(uu) def full_unescape_to_bytes(u): uu = urlparse.unquote_to...
python
def canonical(self): """Convert URL to its canonical form.""" def full_unescape(u): uu = urllib.unquote(u) if uu == u: return uu else: return full_unescape(uu) def full_unescape_to_bytes(u): uu = urlparse.unquote_to...
Convert URL to its canonical form.
https://github.com/afilipovich/gglsbl/blob/89c4665bd6487a3689ccb6b1f3e53ff85e056103/gglsbl/protocol.py#L194-L267
afilipovich/gglsbl
gglsbl/protocol.py
URL.url_permutations
def url_permutations(url): """Try all permutations of hostname and path which can be applied to blacklisted URLs """ def url_host_permutations(host): if re.match(r'\d+\.\d+\.\d+\.\d+', host): yield host return parts = host.split('....
python
def url_permutations(url): """Try all permutations of hostname and path which can be applied to blacklisted URLs """ def url_host_permutations(host): if re.match(r'\d+\.\d+\.\d+\.\d+', host): yield host return parts = host.split('....
Try all permutations of hostname and path which can be applied to blacklisted URLs
https://github.com/afilipovich/gglsbl/blob/89c4665bd6487a3689ccb6b1f3e53ff85e056103/gglsbl/protocol.py#L270-L310
matze/pkgconfig
pkgconfig/pkgconfig.py
_compare_versions
def _compare_versions(v1, v2): """ Compare two version strings and return -1, 0 or 1 depending on the equality of the subset of matching version numbers. The implementation is inspired by the top answer at http://stackoverflow.com/a/1714190/997768. """ def normalize(v): # strip trai...
python
def _compare_versions(v1, v2): """ Compare two version strings and return -1, 0 or 1 depending on the equality of the subset of matching version numbers. The implementation is inspired by the top answer at http://stackoverflow.com/a/1714190/997768. """ def normalize(v): # strip trai...
Compare two version strings and return -1, 0 or 1 depending on the equality of the subset of matching version numbers. The implementation is inspired by the top answer at http://stackoverflow.com/a/1714190/997768.
https://github.com/matze/pkgconfig/blob/a7108a65625a529dc1cf1b4779d23e5701f202dc/pkgconfig/pkgconfig.py#L42-L78
matze/pkgconfig
pkgconfig/pkgconfig.py
_split_version_specifier
def _split_version_specifier(spec): """Splits version specifiers in the form ">= 0.1.2" into ('0.1.2', '>=')""" m = re.search(r'([<>=]?=?)?\s*([0-9.a-zA-Z]+)', spec) return m.group(2), m.group(1)
python
def _split_version_specifier(spec): """Splits version specifiers in the form ">= 0.1.2" into ('0.1.2', '>=')""" m = re.search(r'([<>=]?=?)?\s*([0-9.a-zA-Z]+)', spec) return m.group(2), m.group(1)
Splits version specifiers in the form ">= 0.1.2" into ('0.1.2', '>=')
https://github.com/matze/pkgconfig/blob/a7108a65625a529dc1cf1b4779d23e5701f202dc/pkgconfig/pkgconfig.py#L81-L84
matze/pkgconfig
pkgconfig/pkgconfig.py
exists
def exists(package): """ Return True if package information is available. If ``pkg-config`` not on path, raises ``EnvironmentError``. """ pkg_config_exe = os.environ.get('PKG_CONFIG', None) or 'pkg-config' cmd = '{0} --exists {1}'.format(pkg_config_exe, package).split() return call(cmd) == ...
python
def exists(package): """ Return True if package information is available. If ``pkg-config`` not on path, raises ``EnvironmentError``. """ pkg_config_exe = os.environ.get('PKG_CONFIG', None) or 'pkg-config' cmd = '{0} --exists {1}'.format(pkg_config_exe, package).split() return call(cmd) == ...
Return True if package information is available. If ``pkg-config`` not on path, raises ``EnvironmentError``.
https://github.com/matze/pkgconfig/blob/a7108a65625a529dc1cf1b4779d23e5701f202dc/pkgconfig/pkgconfig.py#L117-L125
matze/pkgconfig
pkgconfig/pkgconfig.py
libs
def libs(package, static=False): """ Return the LDFLAGS string returned by pkg-config. The static specifier will also include libraries for static linking (i.e., includes any private libraries). """ _raise_if_not_exists(package) return _query(package, *_build_options('--libs', static=static...
python
def libs(package, static=False): """ Return the LDFLAGS string returned by pkg-config. The static specifier will also include libraries for static linking (i.e., includes any private libraries). """ _raise_if_not_exists(package) return _query(package, *_build_options('--libs', static=static...
Return the LDFLAGS string returned by pkg-config. The static specifier will also include libraries for static linking (i.e., includes any private libraries).
https://github.com/matze/pkgconfig/blob/a7108a65625a529dc1cf1b4779d23e5701f202dc/pkgconfig/pkgconfig.py#L158-L166
matze/pkgconfig
pkgconfig/pkgconfig.py
variables
def variables(package): """ Return a dictionary of all the variables defined in the .pc pkg-config file of 'package'. """ _raise_if_not_exists(package) result = _query(package, '--print-variables') names = (x.strip() for x in result.split('\n') if x != '') return dict(((x, _query(package...
python
def variables(package): """ Return a dictionary of all the variables defined in the .pc pkg-config file of 'package'. """ _raise_if_not_exists(package) result = _query(package, '--print-variables') names = (x.strip() for x in result.split('\n') if x != '') return dict(((x, _query(package...
Return a dictionary of all the variables defined in the .pc pkg-config file of 'package'.
https://github.com/matze/pkgconfig/blob/a7108a65625a529dc1cf1b4779d23e5701f202dc/pkgconfig/pkgconfig.py#L169-L177
matze/pkgconfig
pkgconfig/pkgconfig.py
installed
def installed(package, version): """ Check if the package meets the required version. The version specifier consists of an optional comparator (one of =, ==, >, <, >=, <=) and an arbitrarily long version number separated by dots. The should be as you would expect, e.g. for an installed version '0.1...
python
def installed(package, version): """ Check if the package meets the required version. The version specifier consists of an optional comparator (one of =, ==, >, <, >=, <=) and an arbitrarily long version number separated by dots. The should be as you would expect, e.g. for an installed version '0.1...
Check if the package meets the required version. The version specifier consists of an optional comparator (one of =, ==, >, <, >=, <=) and an arbitrarily long version number separated by dots. The should be as you would expect, e.g. for an installed version '0.1.2' of package 'foo': >>> installed(...
https://github.com/matze/pkgconfig/blob/a7108a65625a529dc1cf1b4779d23e5701f202dc/pkgconfig/pkgconfig.py#L180-L223
matze/pkgconfig
pkgconfig/pkgconfig.py
parse
def parse(packages, static=False): """ Parse the output from pkg-config about the passed package or packages. Builds a dictionary containing the 'libraries', the 'library_dirs', the 'include_dirs', and the 'define_macros' that are presented by pkg-config. *package* is a string with space-delimited ...
python
def parse(packages, static=False): """ Parse the output from pkg-config about the passed package or packages. Builds a dictionary containing the 'libraries', the 'library_dirs', the 'include_dirs', and the 'define_macros' that are presented by pkg-config. *package* is a string with space-delimited ...
Parse the output from pkg-config about the passed package or packages. Builds a dictionary containing the 'libraries', the 'library_dirs', the 'include_dirs', and the 'define_macros' that are presented by pkg-config. *package* is a string with space-delimited package names. The static specifier will a...
https://github.com/matze/pkgconfig/blob/a7108a65625a529dc1cf1b4779d23e5701f202dc/pkgconfig/pkgconfig.py#L234-L267
WoLpH/python-statsd
statsd/connection.py
Connection.send
def send(self, data, sample_rate=None): '''Send the data over UDP while taking the sample_rate in account The sample rate should be a number between `0` and `1` which indicates the probability that a message will be sent. The sample_rate is also communicated to `statsd` so it knows what...
python
def send(self, data, sample_rate=None): '''Send the data over UDP while taking the sample_rate in account The sample rate should be a number between `0` and `1` which indicates the probability that a message will be sent. The sample_rate is also communicated to `statsd` so it knows what...
Send the data over UDP while taking the sample_rate in account The sample rate should be a number between `0` and `1` which indicates the probability that a message will be sent. The sample_rate is also communicated to `statsd` so it knows what multiplier to use. :keyword data: The dat...
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/connection.py#L47-L81
WoLpH/python-statsd
statsd/timer.py
Timer.start
def start(self): '''Start the timer and store the start time, this can only be executed once per instance It returns the timer instance so it can be chained when instantiating the timer instance like this: ``timer = Timer('application_name').start()``''' assert self._sta...
python
def start(self): '''Start the timer and store the start time, this can only be executed once per instance It returns the timer instance so it can be chained when instantiating the timer instance like this: ``timer = Timer('application_name').start()``''' assert self._sta...
Start the timer and store the start time, this can only be executed once per instance It returns the timer instance so it can be chained when instantiating the timer instance like this: ``timer = Timer('application_name').start()``
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/timer.py#L38-L48
WoLpH/python-statsd
statsd/timer.py
Timer.send
def send(self, subname, delta): '''Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword delta: The time delta (time.time() - time.time()) to report :type delta: float...
python
def send(self, subname, delta): '''Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword delta: The time delta (time.time() - time.time()) to report :type delta: float...
Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword delta: The time delta (time.time() - time.time()) to report :type delta: float
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/timer.py#L50-L65
WoLpH/python-statsd
statsd/timer.py
Timer.intermediate
def intermediate(self, subname): '''Send the time that has passed since our last measurement :keyword subname: The subname to report the data to (appended to the client name) :type subname: str ''' t = time.time() response = self.send(subname, t - self._last)...
python
def intermediate(self, subname): '''Send the time that has passed since our last measurement :keyword subname: The subname to report the data to (appended to the client name) :type subname: str ''' t = time.time() response = self.send(subname, t - self._last)...
Send the time that has passed since our last measurement :keyword subname: The subname to report the data to (appended to the client name) :type subname: str
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/timer.py#L67-L77
WoLpH/python-statsd
statsd/timer.py
Timer.stop
def stop(self, subname='total'): '''Stop the timer and send the total since `start()` was run :keyword subname: The subname to report the data to (appended to the client name) :type subname: str ''' assert self._stop is None, ( 'Unable to stop, the timer ...
python
def stop(self, subname='total'): '''Stop the timer and send the total since `start()` was run :keyword subname: The subname to report the data to (appended to the client name) :type subname: str ''' assert self._stop is None, ( 'Unable to stop, the timer ...
Stop the timer and send the total since `start()` was run :keyword subname: The subname to report the data to (appended to the client name) :type subname: str
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/timer.py#L79-L89
WoLpH/python-statsd
statsd/timer.py
Timer.decorate
def decorate(self, function_or_name): '''Decorate a function to time the execution The method can be called with or without a name. If no name is given the function defaults to the name of the function. :keyword function_or_name: The name to post to or the function to wrap >>>...
python
def decorate(self, function_or_name): '''Decorate a function to time the execution The method can be called with or without a name. If no name is given the function defaults to the name of the function. :keyword function_or_name: The name to post to or the function to wrap >>>...
Decorate a function to time the execution The method can be called with or without a name. If no name is given the function defaults to the name of the function. :keyword function_or_name: The name to post to or the function to wrap >>> from statsd import Timer >>> timer = Tim...
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/timer.py#L127-L152
WoLpH/python-statsd
statsd/timer.py
Timer.time
def time(self, subname=None, class_=None): '''Returns a context manager to time execution of a block of code. :keyword subname: The subname to report data to :type subname: str :keyword class_: The :class:`~statsd.client.Client` subclass to use (e.g. :class:`~statsd.timer.Ti...
python
def time(self, subname=None, class_=None): '''Returns a context manager to time execution of a block of code. :keyword subname: The subname to report data to :type subname: str :keyword class_: The :class:`~statsd.client.Client` subclass to use (e.g. :class:`~statsd.timer.Ti...
Returns a context manager to time execution of a block of code. :keyword subname: The subname to report data to :type subname: str :keyword class_: The :class:`~statsd.client.Client` subclass to use (e.g. :class:`~statsd.timer.Timer` or :class:`~statsd.counter.Counter`) ...
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/timer.py#L155-L183
WoLpH/python-statsd
statsd/raw.py
Raw.send
def send(self, subname, value, timestamp=None): '''Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword value: The raw value to send ''' if timestamp is None:...
python
def send(self, subname, value, timestamp=None): '''Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword value: The raw value to send ''' if timestamp is None:...
Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword value: The raw value to send
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/raw.py#L24-L38
WoLpH/python-statsd
statsd/gauge.py
Gauge._send
def _send(self, subname, value): '''Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword value: The gauge value to send ''' name = self._get_name(self.name, s...
python
def _send(self, subname, value): '''Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword value: The gauge value to send ''' name = self._get_name(self.name, s...
Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword value: The gauge value to send
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/gauge.py#L10-L20
WoLpH/python-statsd
statsd/gauge.py
Gauge.send
def send(self, subname, value): '''Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword value: The gauge value to send ''' assert isinstance(value, compat.NUM...
python
def send(self, subname, value): '''Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword value: The gauge value to send ''' assert isinstance(value, compat.NUM...
Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword value: The gauge value to send
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/gauge.py#L22-L31
WoLpH/python-statsd
statsd/gauge.py
Gauge.increment
def increment(self, subname=None, delta=1): '''Increment the gauge with `delta` :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword delta: The delta to add to the gauge :type delta: int >>> gauge = Ga...
python
def increment(self, subname=None, delta=1): '''Increment the gauge with `delta` :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword delta: The delta to add to the gauge :type delta: int >>> gauge = Ga...
Increment the gauge with `delta` :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword delta: The delta to add to the gauge :type delta: int >>> gauge = Gauge('application_name') >>> gauge.increment('ga...
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/gauge.py#L33-L52
WoLpH/python-statsd
statsd/gauge.py
Gauge.decrement
def decrement(self, subname=None, delta=1): '''Decrement the gauge with `delta` :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword delta: The delta to remove from the gauge :type delta: int >>> gauge...
python
def decrement(self, subname=None, delta=1): '''Decrement the gauge with `delta` :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword delta: The delta to remove from the gauge :type delta: int >>> gauge...
Decrement the gauge with `delta` :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword delta: The delta to remove from the gauge :type delta: int >>> gauge = Gauge('application_name') >>> gauge.decremen...
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/gauge.py#L54-L73
WoLpH/python-statsd
statsd/gauge.py
Gauge.set
def set(self, subname, value): ''' Set the data ignoring the sign, ie set("test", -1) will set "test" exactly to -1 (not decrement it by 1) See https://github.com/etsy/statsd/blob/master/docs/metric_types.md "Adding a sign to the gauge value will change the value, rather ...
python
def set(self, subname, value): ''' Set the data ignoring the sign, ie set("test", -1) will set "test" exactly to -1 (not decrement it by 1) See https://github.com/etsy/statsd/blob/master/docs/metric_types.md "Adding a sign to the gauge value will change the value, rather ...
Set the data ignoring the sign, ie set("test", -1) will set "test" exactly to -1 (not decrement it by 1) See https://github.com/etsy/statsd/blob/master/docs/metric_types.md "Adding a sign to the gauge value will change the value, rather than setting it. gaugor:-10|g ...
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/gauge.py#L99-L126
WoLpH/python-statsd
statsd/client.py
Client.get_client
def get_client(self, name=None, class_=None): '''Get a (sub-)client with a separate namespace This way you can create a global/app based client with subclients per class/function :keyword name: The name to use, if the name for this client was `spam` and the `name` argument i...
python
def get_client(self, name=None, class_=None): '''Get a (sub-)client with a separate namespace This way you can create a global/app based client with subclients per class/function :keyword name: The name to use, if the name for this client was `spam` and the `name` argument i...
Get a (sub-)client with a separate namespace This way you can create a global/app based client with subclients per class/function :keyword name: The name to use, if the name for this client was `spam` and the `name` argument is `eggs` than the resulting name will be `spa...
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/client.py#L45-L70
WoLpH/python-statsd
statsd/client.py
Client.get_average
def get_average(self, name=None): '''Shortcut for getting an :class:`~statsd.average.Average` instance :keyword name: See :func:`~statsd.client.Client.get_client` :type name: str ''' return self.get_client(name=name, class_=statsd.Average)
python
def get_average(self, name=None): '''Shortcut for getting an :class:`~statsd.average.Average` instance :keyword name: See :func:`~statsd.client.Client.get_client` :type name: str ''' return self.get_client(name=name, class_=statsd.Average)
Shortcut for getting an :class:`~statsd.average.Average` instance :keyword name: See :func:`~statsd.client.Client.get_client` :type name: str
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/client.py#L72-L78
WoLpH/python-statsd
statsd/client.py
Client.get_counter
def get_counter(self, name=None): '''Shortcut for getting a :class:`~statsd.counter.Counter` instance :keyword name: See :func:`~statsd.client.Client.get_client` :type name: str ''' return self.get_client(name=name, class_=statsd.Counter)
python
def get_counter(self, name=None): '''Shortcut for getting a :class:`~statsd.counter.Counter` instance :keyword name: See :func:`~statsd.client.Client.get_client` :type name: str ''' return self.get_client(name=name, class_=statsd.Counter)
Shortcut for getting a :class:`~statsd.counter.Counter` instance :keyword name: See :func:`~statsd.client.Client.get_client` :type name: str
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/client.py#L80-L86
WoLpH/python-statsd
statsd/client.py
Client.get_gauge
def get_gauge(self, name=None): '''Shortcut for getting a :class:`~statsd.gauge.Gauge` instance :keyword name: See :func:`~statsd.client.Client.get_client` :type name: str ''' return self.get_client(name=name, class_=statsd.Gauge)
python
def get_gauge(self, name=None): '''Shortcut for getting a :class:`~statsd.gauge.Gauge` instance :keyword name: See :func:`~statsd.client.Client.get_client` :type name: str ''' return self.get_client(name=name, class_=statsd.Gauge)
Shortcut for getting a :class:`~statsd.gauge.Gauge` instance :keyword name: See :func:`~statsd.client.Client.get_client` :type name: str
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/client.py#L88-L94
WoLpH/python-statsd
statsd/client.py
Client.get_raw
def get_raw(self, name=None): '''Shortcut for getting a :class:`~statsd.raw.Raw` instance :keyword name: See :func:`~statsd.client.Client.get_client` :type name: str ''' return self.get_client(name=name, class_=statsd.Raw)
python
def get_raw(self, name=None): '''Shortcut for getting a :class:`~statsd.raw.Raw` instance :keyword name: See :func:`~statsd.client.Client.get_client` :type name: str ''' return self.get_client(name=name, class_=statsd.Raw)
Shortcut for getting a :class:`~statsd.raw.Raw` instance :keyword name: See :func:`~statsd.client.Client.get_client` :type name: str
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/client.py#L96-L102
WoLpH/python-statsd
statsd/client.py
Client.get_timer
def get_timer(self, name=None): '''Shortcut for getting a :class:`~statsd.timer.Timer` instance :keyword name: See :func:`~statsd.client.Client.get_client` :type name: str ''' return self.get_client(name=name, class_=statsd.Timer)
python
def get_timer(self, name=None): '''Shortcut for getting a :class:`~statsd.timer.Timer` instance :keyword name: See :func:`~statsd.client.Client.get_client` :type name: str ''' return self.get_client(name=name, class_=statsd.Timer)
Shortcut for getting a :class:`~statsd.timer.Timer` instance :keyword name: See :func:`~statsd.client.Client.get_client` :type name: str
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/client.py#L104-L110
acsone/git-aggregator
git_aggregator/repo.py
Repo.init_git_version
def init_git_version(cls, v_str): r"""Parse git version string and store the resulting tuple on self. :returns: the parsed version tuple Only the first 3 digits are kept. This is good enough for the few version dependent cases we need, and coarse enough to avoid more complicated ...
python
def init_git_version(cls, v_str): r"""Parse git version string and store the resulting tuple on self. :returns: the parsed version tuple Only the first 3 digits are kept. This is good enough for the few version dependent cases we need, and coarse enough to avoid more complicated ...
r"""Parse git version string and store the resulting tuple on self. :returns: the parsed version tuple Only the first 3 digits are kept. This is good enough for the few version dependent cases we need, and coarse enough to avoid more complicated parsing. Some real-life examples::...
https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/repo.py#L85-L132
acsone/git-aggregator
git_aggregator/repo.py
Repo.query_remote_ref
def query_remote_ref(self, remote, ref): """Query remote repo about given ref. :return: ``('tag', sha)`` if ref is a tag in remote ``('branch', sha)`` if ref is branch (aka "head") in remote ``(None, ref)`` if ref does not exist in remote. This happens ...
python
def query_remote_ref(self, remote, ref): """Query remote repo about given ref. :return: ``('tag', sha)`` if ref is a tag in remote ``('branch', sha)`` if ref is branch (aka "head") in remote ``(None, ref)`` if ref does not exist in remote. This happens ...
Query remote repo about given ref. :return: ``('tag', sha)`` if ref is a tag in remote ``('branch', sha)`` if ref is branch (aka "head") in remote ``(None, ref)`` if ref does not exist in remote. This happens notably if ref if a commit sha (they can't be querie...
https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/repo.py#L134-L151
acsone/git-aggregator
git_aggregator/repo.py
Repo.log_call
def log_call(self, cmd, callwith=subprocess.check_call, log_level=logging.DEBUG, **kw): """Wrap a subprocess call with logging :param meth: the calling method to use. """ logger.log(log_level, "%s> call %r", self.cwd, cmd) ret = callwith(cmd, **kw) if cal...
python
def log_call(self, cmd, callwith=subprocess.check_call, log_level=logging.DEBUG, **kw): """Wrap a subprocess call with logging :param meth: the calling method to use. """ logger.log(log_level, "%s> call %r", self.cwd, cmd) ret = callwith(cmd, **kw) if cal...
Wrap a subprocess call with logging :param meth: the calling method to use.
https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/repo.py#L153-L162
acsone/git-aggregator
git_aggregator/repo.py
Repo.aggregate
def aggregate(self): """ Aggregate all merges into the target branch If the target_dir doesn't exist, create an empty git repo otherwise clean it, add all remotes , and merge all merges. """ logger.info('Start aggregation of %s', self.cwd) target_dir = self.cwd i...
python
def aggregate(self): """ Aggregate all merges into the target branch If the target_dir doesn't exist, create an empty git repo otherwise clean it, add all remotes , and merge all merges. """ logger.info('Start aggregation of %s', self.cwd) target_dir = self.cwd i...
Aggregate all merges into the target branch If the target_dir doesn't exist, create an empty git repo otherwise clean it, add all remotes , and merge all merges.
https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/repo.py#L164-L189
acsone/git-aggregator
git_aggregator/repo.py
Repo._check_status
def _check_status(self): """Check repo status and except if dirty.""" logger.info('Checking repo status') status = self.log_call( ['git', 'status', '--porcelain'], callwith=subprocess.check_output, cwd=self.cwd, ) if status: raise D...
python
def _check_status(self): """Check repo status and except if dirty.""" logger.info('Checking repo status') status = self.log_call( ['git', 'status', '--porcelain'], callwith=subprocess.check_output, cwd=self.cwd, ) if status: raise D...
Check repo status and except if dirty.
https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/repo.py#L210-L219
acsone/git-aggregator
git_aggregator/repo.py
Repo._fetch_options
def _fetch_options(self, merge): """Get the fetch options from the given merge dict.""" cmd = tuple() for option in FETCH_DEFAULTS: value = merge.get(option, self.defaults.get(option)) if value: cmd += ("--%s" % option, str(value)) return cmd
python
def _fetch_options(self, merge): """Get the fetch options from the given merge dict.""" cmd = tuple() for option in FETCH_DEFAULTS: value = merge.get(option, self.defaults.get(option)) if value: cmd += ("--%s" % option, str(value)) return cmd
Get the fetch options from the given merge dict.
https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/repo.py#L221-L228
acsone/git-aggregator
git_aggregator/repo.py
Repo._set_remote
def _set_remote(self, name, url): """Add remote to the repository. It's equivalent to the command git remote add <name> <url> If the remote already exists with an other url, it's removed and added aggain """ remotes = self._get_remotes() exising_url = remotes.get...
python
def _set_remote(self, name, url): """Add remote to the repository. It's equivalent to the command git remote add <name> <url> If the remote already exists with an other url, it's removed and added aggain """ remotes = self._get_remotes() exising_url = remotes.get...
Add remote to the repository. It's equivalent to the command git remote add <name> <url> If the remote already exists with an other url, it's removed and added aggain
https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/repo.py#L285-L304
acsone/git-aggregator
git_aggregator/repo.py
Repo.collect_prs_info
def collect_prs_info(self): """Collect all pending merge PRs info. :returns: mapping of PRs by state """ REPO_RE = re.compile( '^(https://github.com/|git@github.com:)' '(?P<owner>.*?)/(?P<repo>.*?)(.git)?$') PULL_RE = re.compile( '^(refs/)?pul...
python
def collect_prs_info(self): """Collect all pending merge PRs info. :returns: mapping of PRs by state """ REPO_RE = re.compile( '^(https://github.com/|git@github.com:)' '(?P<owner>.*?)/(?P<repo>.*?)(.git)?$') PULL_RE = re.compile( '^(refs/)?pul...
Collect all pending merge PRs info. :returns: mapping of PRs by state
https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/repo.py#L313-L357
acsone/git-aggregator
git_aggregator/repo.py
Repo.show_closed_prs
def show_closed_prs(self): """Log only closed PRs.""" all_prs = self.collect_prs_info() for pr_info in all_prs.get('closed', []): logger.info( '{url} in state {state} ({merged})'.format(**pr_info) )
python
def show_closed_prs(self): """Log only closed PRs.""" all_prs = self.collect_prs_info() for pr_info in all_prs.get('closed', []): logger.info( '{url} in state {state} ({merged})'.format(**pr_info) )
Log only closed PRs.
https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/repo.py#L359-L365
acsone/git-aggregator
git_aggregator/repo.py
Repo.show_all_prs
def show_all_prs(self): """Log all PRs grouped by state.""" for __, prs in self.collect_prs_info().items(): for pr_info in prs: logger.info( '{url} in state {state} ({merged})'.format(**pr_info) )
python
def show_all_prs(self): """Log all PRs grouped by state.""" for __, prs in self.collect_prs_info().items(): for pr_info in prs: logger.info( '{url} in state {state} ({merged})'.format(**pr_info) )
Log all PRs grouped by state.
https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/repo.py#L367-L373
acsone/git-aggregator
git_aggregator/config.py
get_repos
def get_repos(config, force=False): """Return a :py:obj:`list` list of repos from config file. :param config: the repos config in :py:class:`dict` format. :param bool force: Force aggregate dirty repos or not. :type config: dict :rtype: list """ repo_list = [] for directory, repo_data in...
python
def get_repos(config, force=False): """Return a :py:obj:`list` list of repos from config file. :param config: the repos config in :py:class:`dict` format. :param bool force: Force aggregate dirty repos or not. :type config: dict :rtype: list """ repo_list = [] for directory, repo_data in...
Return a :py:obj:`list` list of repos from config file. :param config: the repos config in :py:class:`dict` format. :param bool force: Force aggregate dirty repos or not. :type config: dict :rtype: list
https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/config.py#L17-L123
acsone/git-aggregator
git_aggregator/config.py
load_config
def load_config(config, expand_env=False, force=False): """Return repos from a directory and fnmatch. Not recursive. :param config: paths to config file :type config: str :param expand_env: True to expand environment varialbes in the config. :type expand_env: bool :param bool force: True to agg...
python
def load_config(config, expand_env=False, force=False): """Return repos from a directory and fnmatch. Not recursive. :param config: paths to config file :type config: str :param expand_env: True to expand environment varialbes in the config. :type expand_env: bool :param bool force: True to agg...
Return repos from a directory and fnmatch. Not recursive. :param config: paths to config file :type config: str :param expand_env: True to expand environment varialbes in the config. :type expand_env: bool :param bool force: True to aggregate even if repo is dirty. :returns: expanded config dic...
https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/config.py#L126-L149
acsone/git-aggregator
git_aggregator/main.py
setup_logger
def setup_logger(log=None, level=logging.INFO): """Setup logging for CLI use. :param log: instance of logger :type log: :py:class:`Logger` """ if not log: log = logging.getLogger() if not log.handlers: channel = logging.StreamHandler() if level == logging.DEBUG: ...
python
def setup_logger(log=None, level=logging.INFO): """Setup logging for CLI use. :param log: instance of logger :type log: :py:class:`Logger` """ if not log: log = logging.getLogger() if not log.handlers: channel = logging.StreamHandler() if level == logging.DEBUG: ...
Setup logging for CLI use. :param log: instance of logger :type log: :py:class:`Logger`
https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/main.py#L45-L60
acsone/git-aggregator
git_aggregator/main.py
get_parser
def get_parser(): """Return :py:class:`argparse.ArgumentParser` instance for CLI.""" main_parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter) main_parser.add_argument( '-c', '--config', dest='config', type=str, nargs='?', help='P...
python
def get_parser(): """Return :py:class:`argparse.ArgumentParser` instance for CLI.""" main_parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter) main_parser.add_argument( '-c', '--config', dest='config', type=str, nargs='?', help='P...
Return :py:class:`argparse.ArgumentParser` instance for CLI.
https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/main.py#L63-L139
acsone/git-aggregator
git_aggregator/main.py
main
def main(): """Main CLI application.""" parser = get_parser() argcomplete.autocomplete(parser, always_complete_options=False) args = parser.parse_args() setup_logger( level=args.log_level ) try: if args.config and \ args.command in \ ('agg...
python
def main(): """Main CLI application.""" parser = get_parser() argcomplete.autocomplete(parser, always_complete_options=False) args = parser.parse_args() setup_logger( level=args.log_level ) try: if args.config and \ args.command in \ ('agg...
Main CLI application.
https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/main.py#L142-L163
acsone/git-aggregator
git_aggregator/main.py
load_aggregate
def load_aggregate(args): """Load YAML and JSON configs and begin creating / updating , aggregating and pushing the repos (deprecated in favor or run())""" repos = load_config(args.config, args.expand_env) dirmatch = args.dirmatch for repo_dict in repos: r = Repo(**repo_dict) logger....
python
def load_aggregate(args): """Load YAML and JSON configs and begin creating / updating , aggregating and pushing the repos (deprecated in favor or run())""" repos = load_config(args.config, args.expand_env) dirmatch = args.dirmatch for repo_dict in repos: r = Repo(**repo_dict) logger....
Load YAML and JSON configs and begin creating / updating , aggregating and pushing the repos (deprecated in favor or run())
https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/main.py#L174-L187
acsone/git-aggregator
git_aggregator/main.py
aggregate_repo
def aggregate_repo(repo, args, sem, err_queue): """Aggregate one repo according to the args. Args: repo (Repo): The repository to aggregate. args (argparse.Namespace): CLI arguments. """ try: logger.debug('%s' % repo) dirmatch = args.dirmatch if not match_dir(r...
python
def aggregate_repo(repo, args, sem, err_queue): """Aggregate one repo according to the args. Args: repo (Repo): The repository to aggregate. args (argparse.Namespace): CLI arguments. """ try: logger.debug('%s' % repo) dirmatch = args.dirmatch if not match_dir(r...
Aggregate one repo according to the args. Args: repo (Repo): The repository to aggregate. args (argparse.Namespace): CLI arguments.
https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/main.py#L190-L214
acsone/git-aggregator
git_aggregator/main.py
run
def run(args): """Load YAML and JSON configs and run the command specified in args.command""" repos = load_config(args.config, args.expand_env, args.force) jobs = max(args.jobs, 1) threads = [] sem = threading.Semaphore(jobs) err_queue = Queue() for repo_dict in repos: if not ...
python
def run(args): """Load YAML and JSON configs and run the command specified in args.command""" repos = load_config(args.config, args.expand_env, args.force) jobs = max(args.jobs, 1) threads = [] sem = threading.Semaphore(jobs) err_queue = Queue() for repo_dict in repos: if not ...
Load YAML and JSON configs and run the command specified in args.command
https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/main.py#L217-L258
datacamp/sqlwhat
sqlwhat/checks/check_funcs.py
has_no_error
def has_no_error( state, incorrect_msg="Your code generated an error. Fix it and try again!" ): """Check whether the submission did not generate a runtime error. Simply use ``Ex().has_no_error()`` in your SCT whenever you want to check for errors. By default, after the entire SCT finished executing, ``...
python
def has_no_error( state, incorrect_msg="Your code generated an error. Fix it and try again!" ): """Check whether the submission did not generate a runtime error. Simply use ``Ex().has_no_error()`` in your SCT whenever you want to check for errors. By default, after the entire SCT finished executing, ``...
Check whether the submission did not generate a runtime error. Simply use ``Ex().has_no_error()`` in your SCT whenever you want to check for errors. By default, after the entire SCT finished executing, ``sqlwhat`` will check for errors before marking the exercise as correct. You can disable this behavior ...
https://github.com/datacamp/sqlwhat/blob/9ae798c63124f994607a0e2c120b24ebbb2bdbe9/sqlwhat/checks/check_funcs.py#L11-L29
datacamp/sqlwhat
sqlwhat/checks/check_funcs.py
has_result
def has_result(state, incorrect_msg="Your query did not return a result."): """Checks if the student's query returned a result. Args: incorrect_msg: If specified, this overrides the automatically generated feedback message in case the student's query did not return a result. ...
python
def has_result(state, incorrect_msg="Your query did not return a result."): """Checks if the student's query returned a result. Args: incorrect_msg: If specified, this overrides the automatically generated feedback message in case the student's query did not return a result. ...
Checks if the student's query returned a result. Args: incorrect_msg: If specified, this overrides the automatically generated feedback message in case the student's query did not return a result.
https://github.com/datacamp/sqlwhat/blob/9ae798c63124f994607a0e2c120b24ebbb2bdbe9/sqlwhat/checks/check_funcs.py#L32-L51
datacamp/sqlwhat
sqlwhat/checks/check_funcs.py
has_nrows
def has_nrows( state, incorrect_msg="Your query returned a table with {{n_stu}} row{{'s' if n_stu > 1 else ''}} while it should return a table with {{n_sol}} row{{'s' if n_sol > 1 else ''}}.", ): """Test whether the student and solution query results have equal numbers of rows. Args: incorr...
python
def has_nrows( state, incorrect_msg="Your query returned a table with {{n_stu}} row{{'s' if n_stu > 1 else ''}} while it should return a table with {{n_sol}} row{{'s' if n_sol > 1 else ''}}.", ): """Test whether the student and solution query results have equal numbers of rows. Args: incorr...
Test whether the student and solution query results have equal numbers of rows. Args: incorrect_msg: If specified, this overrides the automatically generated feedback message in case the number of rows in the student and solution query don't match.
https://github.com/datacamp/sqlwhat/blob/9ae798c63124f994607a0e2c120b24ebbb2bdbe9/sqlwhat/checks/check_funcs.py#L54-L78
datacamp/sqlwhat
sqlwhat/checks/check_funcs.py
has_ncols
def has_ncols( state, incorrect_msg="Your query returned a table with {{n_stu}} column{{'s' if n_stu > 1 else ''}} while it should return a table with {{n_sol}} column{{'s' if n_sol > 1 else ''}}.", ): """Test whether the student and solution query results have equal numbers of columns. Args: i...
python
def has_ncols( state, incorrect_msg="Your query returned a table with {{n_stu}} column{{'s' if n_stu > 1 else ''}} while it should return a table with {{n_sol}} column{{'s' if n_sol > 1 else ''}}.", ): """Test whether the student and solution query results have equal numbers of columns. Args: i...
Test whether the student and solution query results have equal numbers of columns. Args: incorrect_msg: If specified, this overrides the automatically generated feedback message in case the number of columns in the student and solution query don't match. :Example: Consi...
https://github.com/datacamp/sqlwhat/blob/9ae798c63124f994607a0e2c120b24ebbb2bdbe9/sqlwhat/checks/check_funcs.py#L81-L124
datacamp/sqlwhat
sqlwhat/checks/check_funcs.py
check_row
def check_row(state, index, missing_msg=None, expand_msg=None): """Zoom in on a particular row in the query result, by index. After zooming in on a row, which is represented as a single-row query result, you can use ``has_equal_value()`` to verify whether all columns in the zoomed in solution query res...
python
def check_row(state, index, missing_msg=None, expand_msg=None): """Zoom in on a particular row in the query result, by index. After zooming in on a row, which is represented as a single-row query result, you can use ``has_equal_value()`` to verify whether all columns in the zoomed in solution query res...
Zoom in on a particular row in the query result, by index. After zooming in on a row, which is represented as a single-row query result, you can use ``has_equal_value()`` to verify whether all columns in the zoomed in solution query result have a match in the student query result. Args: index:...
https://github.com/datacamp/sqlwhat/blob/9ae798c63124f994607a0e2c120b24ebbb2bdbe9/sqlwhat/checks/check_funcs.py#L127-L189
datacamp/sqlwhat
sqlwhat/checks/check_funcs.py
check_column
def check_column(state, name, missing_msg=None, expand_msg=None): """Zoom in on a particular column in the query result, by name. After zooming in on a column, which is represented as a single-column query result, you can use ``has_equal_value()`` to verify whether the column in the solution query result ...
python
def check_column(state, name, missing_msg=None, expand_msg=None): """Zoom in on a particular column in the query result, by name. After zooming in on a column, which is represented as a single-column query result, you can use ``has_equal_value()`` to verify whether the column in the solution query result ...
Zoom in on a particular column in the query result, by name. After zooming in on a column, which is represented as a single-column query result, you can use ``has_equal_value()`` to verify whether the column in the solution query result matches the column in student query result. Args: name: n...
https://github.com/datacamp/sqlwhat/blob/9ae798c63124f994607a0e2c120b24ebbb2bdbe9/sqlwhat/checks/check_funcs.py#L192-L247
datacamp/sqlwhat
sqlwhat/checks/check_funcs.py
check_all_columns
def check_all_columns(state, allow_extra=True, too_many_cols_msg=None, expand_msg=None): """Zoom in on the columns that are specified by the solution Behind the scenes, this is using ``check_column()`` for every column that is in the solution query result. Afterwards, it's selecting only these columns ...
python
def check_all_columns(state, allow_extra=True, too_many_cols_msg=None, expand_msg=None): """Zoom in on the columns that are specified by the solution Behind the scenes, this is using ``check_column()`` for every column that is in the solution query result. Afterwards, it's selecting only these columns ...
Zoom in on the columns that are specified by the solution Behind the scenes, this is using ``check_column()`` for every column that is in the solution query result. Afterwards, it's selecting only these columns from the student query result and stores them in a child state that is returned, so you can ...
https://github.com/datacamp/sqlwhat/blob/9ae798c63124f994607a0e2c120b24ebbb2bdbe9/sqlwhat/checks/check_funcs.py#L250-L319
datacamp/sqlwhat
sqlwhat/checks/check_funcs.py
has_equal_value
def has_equal_value(state, ordered=False, ndigits=None, incorrect_msg=None): """Verify if a student and solution query result match up. This function must always be used after 'zooming' in on certain columns or records (check_column, check_row or check_result). ``has_equal_value`` then goes over all column...
python
def has_equal_value(state, ordered=False, ndigits=None, incorrect_msg=None): """Verify if a student and solution query result match up. This function must always be used after 'zooming' in on certain columns or records (check_column, check_row or check_result). ``has_equal_value`` then goes over all column...
Verify if a student and solution query result match up. This function must always be used after 'zooming' in on certain columns or records (check_column, check_row or check_result). ``has_equal_value`` then goes over all columns that are still left in the solution query result, and compares each column with th...
https://github.com/datacamp/sqlwhat/blob/9ae798c63124f994607a0e2c120b24ebbb2bdbe9/sqlwhat/checks/check_funcs.py#L325-L395
datacamp/sqlwhat
sqlwhat/checks/check_funcs.py
lowercase
def lowercase(state): """Convert all column names to their lower case versions to improve robustness :Example: Suppose we are testing the following SELECT statements * solution: ``SELECT artist_id as id FROM artists`` * student : ``SELECT artist_id as ID FROM artists`` We...
python
def lowercase(state): """Convert all column names to their lower case versions to improve robustness :Example: Suppose we are testing the following SELECT statements * solution: ``SELECT artist_id as id FROM artists`` * student : ``SELECT artist_id as ID FROM artists`` We...
Convert all column names to their lower case versions to improve robustness :Example: Suppose we are testing the following SELECT statements * solution: ``SELECT artist_id as id FROM artists`` * student : ``SELECT artist_id as ID FROM artists`` We can write the following SCTs...
https://github.com/datacamp/sqlwhat/blob/9ae798c63124f994607a0e2c120b24ebbb2bdbe9/sqlwhat/checks/check_funcs.py#L430-L452
datacamp/sqlwhat
sqlwhat/checks/check_funcs.py
check_result
def check_result(state): """High level function which wraps other SCTs for checking results. ``check_result()`` * uses ``lowercase()``, then * runs ``check_all_columns()`` on the state produced by ``lowercase()``, then * runs ``has_equal_value`` on the state produced by ``check_all_columns()``...
python
def check_result(state): """High level function which wraps other SCTs for checking results. ``check_result()`` * uses ``lowercase()``, then * runs ``check_all_columns()`` on the state produced by ``lowercase()``, then * runs ``has_equal_value`` on the state produced by ``check_all_columns()``...
High level function which wraps other SCTs for checking results. ``check_result()`` * uses ``lowercase()``, then * runs ``check_all_columns()`` on the state produced by ``lowercase()``, then * runs ``has_equal_value`` on the state produced by ``check_all_columns()``.
https://github.com/datacamp/sqlwhat/blob/9ae798c63124f994607a0e2c120b24ebbb2bdbe9/sqlwhat/checks/check_funcs.py#L455-L468
datacamp/sqlwhat
sqlwhat/checks/check_funcs.py
check_query
def check_query(state, query, error_msg=None, expand_msg=None): """Run arbitrary queries against to the DB connection to verify the database state. For queries that do not return any output (INSERTs, UPDATEs, ...), you cannot use functions like ``check_col()`` and ``is_equal()`` to verify the query result....
python
def check_query(state, query, error_msg=None, expand_msg=None): """Run arbitrary queries against to the DB connection to verify the database state. For queries that do not return any output (INSERTs, UPDATEs, ...), you cannot use functions like ``check_col()`` and ``is_equal()`` to verify the query result....
Run arbitrary queries against to the DB connection to verify the database state. For queries that do not return any output (INSERTs, UPDATEs, ...), you cannot use functions like ``check_col()`` and ``is_equal()`` to verify the query result. ``check_query()`` will rerun the solution query in the transactio...
https://github.com/datacamp/sqlwhat/blob/9ae798c63124f994607a0e2c120b24ebbb2bdbe9/sqlwhat/checks/check_funcs.py#L471-L540
datacamp/sqlwhat
sqlwhat/State.py
lower_case
def lower_case(f): """Decorator specifically for turning mssql AST into lowercase""" # if it has already been wrapped, we return original if hasattr(f, "lower_cased"): return f @wraps(f) def wrapper(*args, **kwargs): f.lower_cased = True return f(*args, **kwargs).lower() ...
python
def lower_case(f): """Decorator specifically for turning mssql AST into lowercase""" # if it has already been wrapped, we return original if hasattr(f, "lower_cased"): return f @wraps(f) def wrapper(*args, **kwargs): f.lower_cased = True return f(*args, **kwargs).lower() ...
Decorator specifically for turning mssql AST into lowercase
https://github.com/datacamp/sqlwhat/blob/9ae798c63124f994607a0e2c120b24ebbb2bdbe9/sqlwhat/State.py#L16-L27
welbornprod/colr
examples/walk_dir.py
main
def main(argd): """ Main entry point, expects doctopt arg dict as argd. """ startdir = argd['DIR'] or '/' if not os.path.isdir(startdir): raise InvalidArg('not a valid start directory: {}'.format(startdir)) if argd['--progress']: return walk_dir_progress(startdir) return walk_dir_an...
python
def main(argd): """ Main entry point, expects doctopt arg dict as argd. """ startdir = argd['DIR'] or '/' if not os.path.isdir(startdir): raise InvalidArg('not a valid start directory: {}'.format(startdir)) if argd['--progress']: return walk_dir_progress(startdir) return walk_dir_an...
Main entry point, expects doctopt arg dict as argd.
https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/examples/walk_dir.py#L73-L81
welbornprod/colr
examples/walk_dir.py
print_err
def print_err(*args, **kwargs): """ A wrapper for print() that uses stderr by default. """ if kwargs.get('file', None) is None: kwargs['file'] = sys.stderr print(*args, **kwargs)
python
def print_err(*args, **kwargs): """ A wrapper for print() that uses stderr by default. """ if kwargs.get('file', None) is None: kwargs['file'] = sys.stderr print(*args, **kwargs)
A wrapper for print() that uses stderr by default.
https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/examples/walk_dir.py#L84-L88
welbornprod/colr
examples/walk_dir.py
walk_dir_animated
def walk_dir_animated(path, maxdircnt=1000): """ Walk a directory, printing status updates along the way. """ p = AnimatedProgress( 'Walking {}...'.format(path), frames=Frames.dots_orbit.as_rainbow(), show_time=True, ) rootcnt = 0 print('\nStarting animated progress.') wi...
python
def walk_dir_animated(path, maxdircnt=1000): """ Walk a directory, printing status updates along the way. """ p = AnimatedProgress( 'Walking {}...'.format(path), frames=Frames.dots_orbit.as_rainbow(), show_time=True, ) rootcnt = 0 print('\nStarting animated progress.') wi...
Walk a directory, printing status updates along the way.
https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/examples/walk_dir.py#L91-L121
welbornprod/colr
examples/walk_dir.py
walk_dir_progress
def walk_dir_progress(path, maxdircnt=5000, file=sys.stdout): """ Walk a directory, printing status updates along the way. """ p = ProgressBar( 'Walking {}'.format(C(path, 'cyan')), bars=Bars.numbers_blue.with_wrapper(('(', ')')), show_time=True, file=file, ) rootcnt = 0 ...
python
def walk_dir_progress(path, maxdircnt=5000, file=sys.stdout): """ Walk a directory, printing status updates along the way. """ p = ProgressBar( 'Walking {}'.format(C(path, 'cyan')), bars=Bars.numbers_blue.with_wrapper(('(', ')')), show_time=True, file=file, ) rootcnt = 0 ...
Walk a directory, printing status updates along the way.
https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/examples/walk_dir.py#L124-L167
welbornprod/colr
colr/colr_docopt.py
_coloredhelp
def _coloredhelp(s): """ Colorize the usage string for docopt (ColorDocoptExit, docoptextras) """ newlines = [] bigindent = (' ' * 16) in_opts = False for line in s.split('\n'): linestripped = line.strip('\n').strip().strip(':') if linestripped == 'Usage': # l...
python
def _coloredhelp(s): """ Colorize the usage string for docopt (ColorDocoptExit, docoptextras) """ newlines = [] bigindent = (' ' * 16) in_opts = False for line in s.split('\n'): linestripped = line.strip('\n').strip().strip(':') if linestripped == 'Usage': # l...
Colorize the usage string for docopt (ColorDocoptExit, docoptextras)
https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/colr_docopt.py#L57-L104
welbornprod/colr
colr/colr_docopt.py
docopt
def docopt( doc, argv=None, help=True, version=None, options_first=False, script=None, colors=None): """ This is a wrapper for docopt.docopt that also sets SCRIPT to `script`. When SCRIPT is set, it can be colorized for the usage string. A dict of Colr options can be passed with `colors` to ...
python
def docopt( doc, argv=None, help=True, version=None, options_first=False, script=None, colors=None): """ This is a wrapper for docopt.docopt that also sets SCRIPT to `script`. When SCRIPT is set, it can be colorized for the usage string. A dict of Colr options can be passed with `colors` to ...
This is a wrapper for docopt.docopt that also sets SCRIPT to `script`. When SCRIPT is set, it can be colorized for the usage string. A dict of Colr options can be passed with `colors` to alter the styles. Available color options keys: desc : Colr args for the description of options. ...
https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/colr_docopt.py#L128-L181
welbornprod/colr
colr/control_codes.py
EraseCodes.display
def display(method=EraseMethod.ALL_MOVE): """ Clear the screen or part of the screen, and possibly moves the cursor to the "home" position (1, 1). See `method` argument below. Esc[<method>J Arguments: method: One of these possible values: ...
python
def display(method=EraseMethod.ALL_MOVE): """ Clear the screen or part of the screen, and possibly moves the cursor to the "home" position (1, 1). See `method` argument below. Esc[<method>J Arguments: method: One of these possible values: ...
Clear the screen or part of the screen, and possibly moves the cursor to the "home" position (1, 1). See `method` argument below. Esc[<method>J Arguments: method: One of these possible values: EraseMethod.END or 0: ...
https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/control_codes.py#L85-L119
welbornprod/colr
colr/control_codes.py
EraseCodes.line
def line(method=EraseMethod.ALL): """ Erase a line, or part of a line. See `method` argument below. Cursor position does not change. Esc[<method>K Arguments: method : One of these possible values: EraseMethod.END or 0: ...
python
def line(method=EraseMethod.ALL): """ Erase a line, or part of a line. See `method` argument below. Cursor position does not change. Esc[<method>K Arguments: method : One of these possible values: EraseMethod.END or 0: ...
Erase a line, or part of a line. See `method` argument below. Cursor position does not change. Esc[<method>K Arguments: method : One of these possible values: EraseMethod.END or 0: Clear from cursor to the ...
https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/control_codes.py#L122-L144
welbornprod/colr
colr/progress.py
try_unbuffered_file
def try_unbuffered_file(file, _alreadyopen={}): """ Try re-opening a file in an unbuffered mode and return it. If that fails, just return the original file. This function remembers the file descriptors it opens, so it never opens the same one twice. This is meant for files like sys....
python
def try_unbuffered_file(file, _alreadyopen={}): """ Try re-opening a file in an unbuffered mode and return it. If that fails, just return the original file. This function remembers the file descriptors it opens, so it never opens the same one twice. This is meant for files like sys....
Try re-opening a file in an unbuffered mode and return it. If that fails, just return the original file. This function remembers the file descriptors it opens, so it never opens the same one twice. This is meant for files like sys.stdout or sys.stderr.
https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress.py#L89-L112
welbornprod/colr
colr/progress.py
WriterProcessBase._loop
def _loop(self): """ This is the loop that runs in the subproces. It is called from `run` and is responsible for all printing, text updates, and time management. """ self.stop_flag.value = False self.time_started.value = time() self.time_elapsed.value = 0 ...
python
def _loop(self): """ This is the loop that runs in the subproces. It is called from `run` and is responsible for all printing, text updates, and time management. """ self.stop_flag.value = False self.time_started.value = time() self.time_elapsed.value = 0 ...
This is the loop that runs in the subproces. It is called from `run` and is responsible for all printing, text updates, and time management.
https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress.py#L161-L185
welbornprod/colr
colr/progress.py
WriterProcessBase.run
def run(self): """ Runs the printer loop in a subprocess. This is called by multiprocessing. """ try: self._loop() except Exception: # Send the exception through the exc_queue, so the parent # process can check it. typ, val, tb ...
python
def run(self): """ Runs the printer loop in a subprocess. This is called by multiprocessing. """ try: self._loop() except Exception: # Send the exception through the exc_queue, so the parent # process can check it. typ, val, tb ...
Runs the printer loop in a subprocess. This is called by multiprocessing.
https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress.py#L187-L198
welbornprod/colr
colr/progress.py
WriterProcessBase.stop
def stop(self): """ Stop this WriterProcessBase, and reset the cursor. """ self.stop_flag.value = True with self.lock: ( Control().text(C(' ', style='reset_all')) .pos_restore().move_column(1).erase_line() .write(self.file) ...
python
def stop(self): """ Stop this WriterProcessBase, and reset the cursor. """ self.stop_flag.value = True with self.lock: ( Control().text(C(' ', style='reset_all')) .pos_restore().move_column(1).erase_line() .write(self.file) ...
Stop this WriterProcessBase, and reset the cursor.
https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress.py#L204-L212
welbornprod/colr
colr/progress.py
WriterProcessBase.update_text
def update_text(self): """ Write the current text, and check for any new text changes. This also updates the elapsed time. """ self.write() try: newtext = self.text_queue.get_nowait() self._text = newtext except Empty: pass
python
def update_text(self): """ Write the current text, and check for any new text changes. This also updates the elapsed time. """ self.write() try: newtext = self.text_queue.get_nowait() self._text = newtext except Empty: pass
Write the current text, and check for any new text changes. This also updates the elapsed time.
https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress.py#L218-L227
welbornprod/colr
colr/progress.py
WriterProcessBase.write
def write(self): """ Write the current text to self.file, and flush it. This can be overridden to handle custom writes. """ if self._text is not None: with self.lock: self.file.write(str(self._text).encode()) self.file.flush() sleep...
python
def write(self): """ Write the current text to self.file, and flush it. This can be overridden to handle custom writes. """ if self._text is not None: with self.lock: self.file.write(str(self._text).encode()) self.file.flush() sleep...
Write the current text to self.file, and flush it. This can be overridden to handle custom writes.
https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress.py#L229-L237
welbornprod/colr
colr/progress.py
WriterProcess.exception
def exception(self): """ Try retrieving the last subprocess exception. If set, the exception is returned. Otherwise None is returned. """ if self._exception is not None: return self._exception try: exc, tblines = self.exc_queue.get_nowait() exc...
python
def exception(self): """ Try retrieving the last subprocess exception. If set, the exception is returned. Otherwise None is returned. """ if self._exception is not None: return self._exception try: exc, tblines = self.exc_queue.get_nowait() exc...
Try retrieving the last subprocess exception. If set, the exception is returned. Otherwise None is returned.
https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress.py#L283-L296
welbornprod/colr
colr/progress.py
StaticProgress.fmt
def fmt(self, value): """ Sets self.fmt, with some extra help for plain format strings. """ if isinstance(value, str): value = value.split(self.join_str) if not (value and isinstance(value, (list, tuple))): raise TypeError( ' '.join(( '...
python
def fmt(self, value): """ Sets self.fmt, with some extra help for plain format strings. """ if isinstance(value, str): value = value.split(self.join_str) if not (value and isinstance(value, (list, tuple))): raise TypeError( ' '.join(( '...
Sets self.fmt, with some extra help for plain format strings.
https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress.py#L397-L411
welbornprod/colr
colr/progress.py
StaticProgress.run
def run(self): """ Overrides WriterProcess.run, to handle KeyboardInterrupts better. This should not be called by any user. `multiprocessing` calls this in a subprocess. Use `self.start` to start this instance. """ try: Control().cursor_hide().writ...
python
def run(self): """ Overrides WriterProcess.run, to handle KeyboardInterrupts better. This should not be called by any user. `multiprocessing` calls this in a subprocess. Use `self.start` to start this instance. """ try: Control().cursor_hide().writ...
Overrides WriterProcess.run, to handle KeyboardInterrupts better. This should not be called by any user. `multiprocessing` calls this in a subprocess. Use `self.start` to start this instance.
https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress.py#L413-L425
welbornprod/colr
colr/progress.py
StaticProgress.stop
def stop(self): """ Stop this animated progress, and block until it is finished. """ super().stop() while not self.stopped: # stop() should block, so printing afterwards isn't interrupted. sleep(0.001) # Retrieve the latest exception, if any. exc = self.ex...
python
def stop(self): """ Stop this animated progress, and block until it is finished. """ super().stop() while not self.stopped: # stop() should block, so printing afterwards isn't interrupted. sleep(0.001) # Retrieve the latest exception, if any. exc = self.ex...
Stop this animated progress, and block until it is finished.
https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress.py#L427-L436
welbornprod/colr
colr/progress.py
StaticProgress.write
def write(self): """ Writes a single frame of the progress spinner to the terminal. This function updates the current frame before returning. """ if self.text is None: # Text has not been sent through the pipe yet. # Do not write anything until it is set to no...
python
def write(self): """ Writes a single frame of the progress spinner to the terminal. This function updates the current frame before returning. """ if self.text is None: # Text has not been sent through the pipe yet. # Do not write anything until it is set to no...
Writes a single frame of the progress spinner to the terminal. This function updates the current frame before returning.
https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress.py#L438-L458