repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
istresearch/scrapy-cluster
utils/scutils/stats_collector.py
StatsCollector.get_hll_counter
def get_hll_counter(self, redis_conn=None, host='localhost', port=6379, key='hyperloglog_counter', cycle_time=5, start_time=None, window=SECONDS_1_HOUR, roll=True, keep_max=12): ''' Generate a new HyperLogLogCounter. Useful ...
python
def get_hll_counter(self, redis_conn=None, host='localhost', port=6379, key='hyperloglog_counter', cycle_time=5, start_time=None, window=SECONDS_1_HOUR, roll=True, keep_max=12): ''' Generate a new HyperLogLogCounter. Useful ...
[ "def", "get_hll_counter", "(", "self", ",", "redis_conn", "=", "None", ",", "host", "=", "'localhost'", ",", "port", "=", "6379", ",", "key", "=", "'hyperloglog_counter'", ",", "cycle_time", "=", "5", ",", "start_time", "=", "None", ",", "window", "=", "...
Generate a new HyperLogLogCounter. Useful for approximating extremely large counts of unique items @param redis_conn: A premade redis connection (overrides host and port) @param host: the redis host @param port: the redis port @param key: the key for your stats collection ...
[ "Generate", "a", "new", "HyperLogLogCounter", ".", "Useful", "for", "approximating", "extremely", "large", "counts", "of", "unique", "items" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/stats_collector.py#L143-L167
train
istresearch/scrapy-cluster
utils/scutils/stats_collector.py
AbstractCounter.setup
def setup(self, redis_conn=None, host='localhost', port=6379): ''' Set up the redis connection ''' if redis_conn is None: if host is not None and port is not None: self.redis_conn = redis.Redis(host=host, port=port) else: raise Exce...
python
def setup(self, redis_conn=None, host='localhost', port=6379): ''' Set up the redis connection ''' if redis_conn is None: if host is not None and port is not None: self.redis_conn = redis.Redis(host=host, port=port) else: raise Exce...
[ "def", "setup", "(", "self", ",", "redis_conn", "=", "None", ",", "host", "=", "'localhost'", ",", "port", "=", "6379", ")", ":", "if", "redis_conn", "is", "None", ":", "if", "host", "is", "not", "None", "and", "port", "is", "not", "None", ":", "se...
Set up the redis connection
[ "Set", "up", "the", "redis", "connection" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/stats_collector.py#L206-L219
train
istresearch/scrapy-cluster
utils/scutils/stats_collector.py
ThreadedCounter.setup
def setup(self, redis_conn=None, host='localhost', port=6379): ''' Set up the counting manager class @param redis_conn: A premade redis connection (overrides host and port) @param host: the redis host @param port: the redis port ''' AbstractCounter.setup(self, re...
python
def setup(self, redis_conn=None, host='localhost', port=6379): ''' Set up the counting manager class @param redis_conn: A premade redis connection (overrides host and port) @param host: the redis host @param port: the redis port ''' AbstractCounter.setup(self, re...
[ "def", "setup", "(", "self", ",", "redis_conn", "=", "None", ",", "host", "=", "'localhost'", ",", "port", "=", "6379", ")", ":", "AbstractCounter", ".", "setup", "(", "self", ",", "redis_conn", "=", "redis_conn", ",", "host", "=", "host", ",", "port",...
Set up the counting manager class @param redis_conn: A premade redis connection (overrides host and port) @param host: the redis host @param port: the redis port
[ "Set", "up", "the", "counting", "manager", "class" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/stats_collector.py#L300-L311
train
istresearch/scrapy-cluster
utils/scutils/stats_collector.py
ThreadedCounter._threaded_start
def _threaded_start(self): ''' Spawns a worker thread to do the expiration checks ''' self.active = True self.thread = Thread(target=self._main_loop) self.thread.setDaemon(True) self.thread.start()
python
def _threaded_start(self): ''' Spawns a worker thread to do the expiration checks ''' self.active = True self.thread = Thread(target=self._main_loop) self.thread.setDaemon(True) self.thread.start()
[ "def", "_threaded_start", "(", "self", ")", ":", "self", ".", "active", "=", "True", "self", ".", "thread", "=", "Thread", "(", "target", "=", "self", ".", "_main_loop", ")", "self", ".", "thread", ".", "setDaemon", "(", "True", ")", "self", ".", "th...
Spawns a worker thread to do the expiration checks
[ "Spawns", "a", "worker", "thread", "to", "do", "the", "expiration", "checks" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/stats_collector.py#L313-L320
train
istresearch/scrapy-cluster
utils/scutils/stats_collector.py
ThreadedCounter._main_loop
def _main_loop(self): ''' Main loop for the stats collector ''' while self.active: self.expire() if self.roll and self.is_expired(): self.start_time = self.start_time + self.window self._set_key() self.purge_old() ...
python
def _main_loop(self): ''' Main loop for the stats collector ''' while self.active: self.expire() if self.roll and self.is_expired(): self.start_time = self.start_time + self.window self._set_key() self.purge_old() ...
[ "def", "_main_loop", "(", "self", ")", ":", "while", "self", ".", "active", ":", "self", ".", "expire", "(", ")", "if", "self", ".", "roll", "and", "self", ".", "is_expired", "(", ")", ":", "self", ".", "start_time", "=", "self", ".", "start_time", ...
Main loop for the stats collector
[ "Main", "loop", "for", "the", "stats", "collector" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/stats_collector.py#L329-L340
train
istresearch/scrapy-cluster
utils/scutils/stats_collector.py
ThreadedCounter._set_key
def _set_key(self): ''' sets the final key to be used currently ''' if self.roll: self.date = time.strftime(self.date_format, time.gmtime(self.start_time)) self.final_key = '{}:{}'.format(self.key, self.date) else: ...
python
def _set_key(self): ''' sets the final key to be used currently ''' if self.roll: self.date = time.strftime(self.date_format, time.gmtime(self.start_time)) self.final_key = '{}:{}'.format(self.key, self.date) else: ...
[ "def", "_set_key", "(", "self", ")", ":", "if", "self", ".", "roll", ":", "self", ".", "date", "=", "time", ".", "strftime", "(", "self", ".", "date_format", ",", "time", ".", "gmtime", "(", "self", ".", "start_time", ")", ")", "self", ".", "final_...
sets the final key to be used currently
[ "sets", "the", "final", "key", "to", "be", "used", "currently" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/stats_collector.py#L348-L358
train
istresearch/scrapy-cluster
utils/scutils/stats_collector.py
ThreadedCounter.is_expired
def is_expired(self): ''' Returns true if the time is beyond the window ''' if self.window is not None: return (self._time() - self.start_time) >= self.window return False
python
def is_expired(self): ''' Returns true if the time is beyond the window ''' if self.window is not None: return (self._time() - self.start_time) >= self.window return False
[ "def", "is_expired", "(", "self", ")", ":", "if", "self", ".", "window", "is", "not", "None", ":", "return", "(", "self", ".", "_time", "(", ")", "-", "self", ".", "start_time", ")", ">=", "self", ".", "window", "return", "False" ]
Returns true if the time is beyond the window
[ "Returns", "true", "if", "the", "time", "is", "beyond", "the", "window" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/stats_collector.py#L360-L366
train
istresearch/scrapy-cluster
utils/scutils/stats_collector.py
ThreadedCounter.purge_old
def purge_old(self): ''' Removes keys that are beyond our keep_max limit ''' if self.keep_max is not None: keys = self.redis_conn.keys(self.get_key() + ':*') keys.sort(reverse=True) while len(keys) > self.keep_max: key = keys.pop() ...
python
def purge_old(self): ''' Removes keys that are beyond our keep_max limit ''' if self.keep_max is not None: keys = self.redis_conn.keys(self.get_key() + ':*') keys.sort(reverse=True) while len(keys) > self.keep_max: key = keys.pop() ...
[ "def", "purge_old", "(", "self", ")", ":", "if", "self", ".", "keep_max", "is", "not", "None", ":", "keys", "=", "self", ".", "redis_conn", ".", "keys", "(", "self", ".", "get_key", "(", ")", "+", "':*'", ")", "keys", ".", "sort", "(", "reverse", ...
Removes keys that are beyond our keep_max limit
[ "Removes", "keys", "that", "are", "beyond", "our", "keep_max", "limit" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/stats_collector.py#L368-L377
train
istresearch/scrapy-cluster
utils/scutils/redis_queue.py
Base._encode_item
def _encode_item(self, item): ''' Encode an item object @requires: The object be serializable ''' if self.encoding.__name__ == 'pickle': return self.encoding.dumps(item, protocol=-1) else: return self.encoding.dumps(item)
python
def _encode_item(self, item): ''' Encode an item object @requires: The object be serializable ''' if self.encoding.__name__ == 'pickle': return self.encoding.dumps(item, protocol=-1) else: return self.encoding.dumps(item)
[ "def", "_encode_item", "(", "self", ",", "item", ")", ":", "if", "self", ".", "encoding", ".", "__name__", "==", "'pickle'", ":", "return", "self", ".", "encoding", ".", "dumps", "(", "item", ",", "protocol", "=", "-", "1", ")", "else", ":", "return"...
Encode an item object @requires: The object be serializable
[ "Encode", "an", "item", "object" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/redis_queue.py#L35-L44
train
istresearch/scrapy-cluster
utils/scutils/zookeeper_watcher.py
ZookeeperWatcher.threaded_start
def threaded_start(self, no_init=False): ''' Spawns a worker thread to set up the zookeeper connection ''' thread = Thread(target=self.init_connections, kwargs={ 'no_init': no_init}) thread.setDaemon(True) thread.start() thread.join()
python
def threaded_start(self, no_init=False): ''' Spawns a worker thread to set up the zookeeper connection ''' thread = Thread(target=self.init_connections, kwargs={ 'no_init': no_init}) thread.setDaemon(True) thread.start() thread.join()
[ "def", "threaded_start", "(", "self", ",", "no_init", "=", "False", ")", ":", "thread", "=", "Thread", "(", "target", "=", "self", ".", "init_connections", ",", "kwargs", "=", "{", "'no_init'", ":", "no_init", "}", ")", "thread", ".", "setDaemon", "(", ...
Spawns a worker thread to set up the zookeeper connection
[ "Spawns", "a", "worker", "thread", "to", "set", "up", "the", "zookeeper", "connection" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/zookeeper_watcher.py#L77-L85
train
istresearch/scrapy-cluster
utils/scutils/zookeeper_watcher.py
ZookeeperWatcher.init_connections
def init_connections(self, no_init=False): ''' Sets up the initial Kazoo Client and watches ''' success = False self.set_valid(False) if not no_init: if self.zoo_client: self.zoo_client.remove_listener(self.state_listener) self...
python
def init_connections(self, no_init=False): ''' Sets up the initial Kazoo Client and watches ''' success = False self.set_valid(False) if not no_init: if self.zoo_client: self.zoo_client.remove_listener(self.state_listener) self...
[ "def", "init_connections", "(", "self", ",", "no_init", "=", "False", ")", ":", "success", "=", "False", "self", ".", "set_valid", "(", "False", ")", "if", "not", "no_init", ":", "if", "self", ".", "zoo_client", ":", "self", ".", "zoo_client", ".", "re...
Sets up the initial Kazoo Client and watches
[ "Sets", "up", "the", "initial", "Kazoo", "Client", "and", "watches" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/zookeeper_watcher.py#L87-L121
train
istresearch/scrapy-cluster
utils/scutils/zookeeper_watcher.py
ZookeeperWatcher.setup
def setup(self): ''' Ensures the path to the watched file exists and we have a state listener ''' self.zoo_client.add_listener(self.state_listener) if self.ensure: self.zoo_client.ensure_path(self.my_file)
python
def setup(self): ''' Ensures the path to the watched file exists and we have a state listener ''' self.zoo_client.add_listener(self.state_listener) if self.ensure: self.zoo_client.ensure_path(self.my_file)
[ "def", "setup", "(", "self", ")", ":", "self", ".", "zoo_client", ".", "add_listener", "(", "self", ".", "state_listener", ")", "if", "self", ".", "ensure", ":", "self", ".", "zoo_client", ".", "ensure_path", "(", "self", ".", "my_file", ")" ]
Ensures the path to the watched file exists and we have a state listener
[ "Ensures", "the", "path", "to", "the", "watched", "file", "exists", "and", "we", "have", "a", "state", "listener" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/zookeeper_watcher.py#L123-L131
train
istresearch/scrapy-cluster
utils/scutils/zookeeper_watcher.py
ZookeeperWatcher.state_listener
def state_listener(self, state): ''' Restarts the session if we get anything besides CONNECTED ''' if state == KazooState.SUSPENDED: self.set_valid(False) self.call_error(self.BAD_CONNECTION) elif state == KazooState.LOST and not self.do_not_restart: ...
python
def state_listener(self, state): ''' Restarts the session if we get anything besides CONNECTED ''' if state == KazooState.SUSPENDED: self.set_valid(False) self.call_error(self.BAD_CONNECTION) elif state == KazooState.LOST and not self.do_not_restart: ...
[ "def", "state_listener", "(", "self", ",", "state", ")", ":", "if", "state", "==", "KazooState", ".", "SUSPENDED", ":", "self", ".", "set_valid", "(", "False", ")", "self", ".", "call_error", "(", "self", ".", "BAD_CONNECTION", ")", "elif", "state", "=="...
Restarts the session if we get anything besides CONNECTED
[ "Restarts", "the", "session", "if", "we", "get", "anything", "besides", "CONNECTED" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/zookeeper_watcher.py#L133-L146
train
istresearch/scrapy-cluster
utils/scutils/zookeeper_watcher.py
ZookeeperWatcher.close
def close(self, kill_restart=True): ''' Use when you would like to close everything down @param kill_restart= Prevent kazoo restarting from occurring ''' self.do_not_restart = kill_restart self.zoo_client.stop() self.zoo_client.close()
python
def close(self, kill_restart=True): ''' Use when you would like to close everything down @param kill_restart= Prevent kazoo restarting from occurring ''' self.do_not_restart = kill_restart self.zoo_client.stop() self.zoo_client.close()
[ "def", "close", "(", "self", ",", "kill_restart", "=", "True", ")", ":", "self", ".", "do_not_restart", "=", "kill_restart", "self", ".", "zoo_client", ".", "stop", "(", ")", "self", ".", "zoo_client", ".", "close", "(", ")" ]
Use when you would like to close everything down @param kill_restart= Prevent kazoo restarting from occurring
[ "Use", "when", "you", "would", "like", "to", "close", "everything", "down" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/zookeeper_watcher.py#L166-L173
train
istresearch/scrapy-cluster
utils/scutils/zookeeper_watcher.py
ZookeeperWatcher.get_file_contents
def get_file_contents(self, pointer=False): ''' Gets any file contents you care about. Defaults to the main file @param pointer: The the contents of the file pointer, not the pointed at file @return: A string of the contents ''' if self.pointer: if poi...
python
def get_file_contents(self, pointer=False): ''' Gets any file contents you care about. Defaults to the main file @param pointer: The the contents of the file pointer, not the pointed at file @return: A string of the contents ''' if self.pointer: if poi...
[ "def", "get_file_contents", "(", "self", ",", "pointer", "=", "False", ")", ":", "if", "self", ".", "pointer", ":", "if", "pointer", ":", "return", "self", ".", "old_pointed", "else", ":", "return", "self", ".", "old_data", "else", ":", "return", "self",...
Gets any file contents you care about. Defaults to the main file @param pointer: The the contents of the file pointer, not the pointed at file @return: A string of the contents
[ "Gets", "any", "file", "contents", "you", "care", "about", ".", "Defaults", "to", "the", "main", "file" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/zookeeper_watcher.py#L175-L188
train
istresearch/scrapy-cluster
utils/scutils/zookeeper_watcher.py
ZookeeperWatcher.update_file
def update_file(self, path): ''' Updates the file watcher and calls the appropriate method for results @return: False if we need to keep trying the connection ''' try: # grab the file result, stat = self.zoo_client.get(path, watch=self.watch_file) ...
python
def update_file(self, path): ''' Updates the file watcher and calls the appropriate method for results @return: False if we need to keep trying the connection ''' try: # grab the file result, stat = self.zoo_client.get(path, watch=self.watch_file) ...
[ "def", "update_file", "(", "self", ",", "path", ")", ":", "try", ":", "result", ",", "stat", "=", "self", ".", "zoo_client", ".", "get", "(", "path", ",", "watch", "=", "self", ".", "watch_file", ")", "except", "ZookeeperError", ":", "self", ".", "se...
Updates the file watcher and calls the appropriate method for results @return: False if we need to keep trying the connection
[ "Updates", "the", "file", "watcher", "and", "calls", "the", "appropriate", "method", "for", "results" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/zookeeper_watcher.py#L197-L229
train
istresearch/scrapy-cluster
utils/scutils/zookeeper_watcher.py
ZookeeperWatcher.update_pointed
def update_pointed(self): ''' Grabs the latest file contents based on the pointer uri ''' # only grab file if our pointer is still good (not None) if not self.pointed_at_expired: try: conf_string, stat2 = self.zoo_client.get(self.point_path, ...
python
def update_pointed(self): ''' Grabs the latest file contents based on the pointer uri ''' # only grab file if our pointer is still good (not None) if not self.pointed_at_expired: try: conf_string, stat2 = self.zoo_client.get(self.point_path, ...
[ "def", "update_pointed", "(", "self", ")", ":", "if", "not", "self", ".", "pointed_at_expired", ":", "try", ":", "conf_string", ",", "stat2", "=", "self", ".", "zoo_client", ".", "get", "(", "self", ".", "point_path", ",", "watch", "=", "self", ".", "w...
Grabs the latest file contents based on the pointer uri
[ "Grabs", "the", "latest", "file", "contents", "based", "on", "the", "pointer", "uri" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/zookeeper_watcher.py#L237-L255
train
istresearch/scrapy-cluster
utils/scutils/zookeeper_watcher.py
ZookeeperWatcher.set_valid
def set_valid(self, boolean): ''' Sets the state and calls the change if needed @param bool: The state (true or false) ''' old_state = self.is_valid() self.valid_file = boolean if old_state != self.valid_file: self.call_valid(self.valid_file)
python
def set_valid(self, boolean): ''' Sets the state and calls the change if needed @param bool: The state (true or false) ''' old_state = self.is_valid() self.valid_file = boolean if old_state != self.valid_file: self.call_valid(self.valid_file)
[ "def", "set_valid", "(", "self", ",", "boolean", ")", ":", "old_state", "=", "self", ".", "is_valid", "(", ")", "self", ".", "valid_file", "=", "boolean", "if", "old_state", "!=", "self", ".", "valid_file", ":", "self", ".", "call_valid", "(", "self", ...
Sets the state and calls the change if needed @param bool: The state (true or false)
[ "Sets", "the", "state", "and", "calls", "the", "change", "if", "needed" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/zookeeper_watcher.py#L257-L266
train
istresearch/scrapy-cluster
kafka-monitor/plugins/zookeeper_handler.py
ZookeeperHandler.setup
def setup(self, settings): ''' Setup redis and tldextract ''' self.extract = tldextract.TLDExtract() self.redis_conn = redis.Redis(host=settings['REDIS_HOST'], port=settings['REDIS_PORT'], db=settings.get...
python
def setup(self, settings): ''' Setup redis and tldextract ''' self.extract = tldextract.TLDExtract() self.redis_conn = redis.Redis(host=settings['REDIS_HOST'], port=settings['REDIS_PORT'], db=settings.get...
[ "def", "setup", "(", "self", ",", "settings", ")", ":", "self", ".", "extract", "=", "tldextract", ".", "TLDExtract", "(", ")", "self", ".", "redis_conn", "=", "redis", ".", "Redis", "(", "host", "=", "settings", "[", "'REDIS_HOST'", "]", ",", "port", ...
Setup redis and tldextract
[ "Setup", "redis", "and", "tldextract" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/kafka-monitor/plugins/zookeeper_handler.py#L14-L29
train
istresearch/scrapy-cluster
redis-monitor/plugins/base_monitor.py
BaseMonitor.get_log_dict
def get_log_dict(self, action, appid, spiderid=None, uuid=None, crawlid=None): ''' Returns a basic dictionary for logging @param action: the action taken by the redis monitor @param spiderid: the spider id @param appid: the application id @param uuid:...
python
def get_log_dict(self, action, appid, spiderid=None, uuid=None, crawlid=None): ''' Returns a basic dictionary for logging @param action: the action taken by the redis monitor @param spiderid: the spider id @param appid: the application id @param uuid:...
[ "def", "get_log_dict", "(", "self", ",", "action", ",", "appid", ",", "spiderid", "=", "None", ",", "uuid", "=", "None", ",", "crawlid", "=", "None", ")", ":", "extras", "=", "{", "}", "extras", "[", "'action'", "]", "=", "action", "extras", "[", "...
Returns a basic dictionary for logging @param action: the action taken by the redis monitor @param spiderid: the spider id @param appid: the application id @param uuid: a unique id of the request @param crawlid: a unique crawl id of the request
[ "Returns", "a", "basic", "dictionary", "for", "logging" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/plugins/base_monitor.py#L71-L91
train
istresearch/scrapy-cluster
redis-monitor/redis_monitor.py
RedisMonitor._load_plugins
def _load_plugins(self): ''' Sets up all plugins and defaults ''' plugins = self.settings['PLUGINS'] self.plugins_dict = {} for key in plugins: # skip loading the plugin if its value is None if plugins[key] is None: continue ...
python
def _load_plugins(self): ''' Sets up all plugins and defaults ''' plugins = self.settings['PLUGINS'] self.plugins_dict = {} for key in plugins: # skip loading the plugin if its value is None if plugins[key] is None: continue ...
[ "def", "_load_plugins", "(", "self", ")", ":", "plugins", "=", "self", ".", "settings", "[", "'PLUGINS'", "]", "self", ".", "plugins_dict", "=", "{", "}", "for", "key", "in", "plugins", ":", "if", "plugins", "[", "key", "]", "is", "None", ":", "conti...
Sets up all plugins and defaults
[ "Sets", "up", "all", "plugins", "and", "defaults" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/redis_monitor.py#L87-L119
train
istresearch/scrapy-cluster
redis-monitor/redis_monitor.py
RedisMonitor._main_loop
def _main_loop(self): ''' The internal while true main loop for the redis monitor ''' self.logger.debug("Running main loop") old_time = 0 while True: for plugin_key in self.plugins_dict: obj = self.plugins_dict[plugin_key] self....
python
def _main_loop(self): ''' The internal while true main loop for the redis monitor ''' self.logger.debug("Running main loop") old_time = 0 while True: for plugin_key in self.plugins_dict: obj = self.plugins_dict[plugin_key] self....
[ "def", "_main_loop", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Running main loop\"", ")", "old_time", "=", "0", "while", "True", ":", "for", "plugin_key", "in", "self", ".", "plugins_dict", ":", "obj", "=", "self", ".", "plugins...
The internal while true main loop for the redis monitor
[ "The", "internal", "while", "true", "main", "loop", "for", "the", "redis", "monitor" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/redis_monitor.py#L127-L152
train
istresearch/scrapy-cluster
redis-monitor/redis_monitor.py
RedisMonitor._process_plugin
def _process_plugin(self, plugin): ''' Logic to handle each plugin that is active @param plugin: a plugin dict object ''' instance = plugin['instance'] regex = plugin['regex'] for key in self.redis_conn.scan_iter(match=regex): # acquire lock ...
python
def _process_plugin(self, plugin): ''' Logic to handle each plugin that is active @param plugin: a plugin dict object ''' instance = plugin['instance'] regex = plugin['regex'] for key in self.redis_conn.scan_iter(match=regex): # acquire lock ...
[ "def", "_process_plugin", "(", "self", ",", "plugin", ")", ":", "instance", "=", "plugin", "[", "'instance'", "]", "regex", "=", "plugin", "[", "'regex'", "]", "for", "key", "in", "self", ".", "redis_conn", ".", "scan_iter", "(", "match", "=", "regex", ...
Logic to handle each plugin that is active @param plugin: a plugin dict object
[ "Logic", "to", "handle", "each", "plugin", "that", "is", "active" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/redis_monitor.py#L154-L179
train
istresearch/scrapy-cluster
redis-monitor/redis_monitor.py
RedisMonitor._create_lock_object
def _create_lock_object(self, key): ''' Returns a lock object, split for testing ''' return redis_lock.Lock(self.redis_conn, key, expire=self.settings['REDIS_LOCK_EXPIRATION'], auto_renewal=True)
python
def _create_lock_object(self, key): ''' Returns a lock object, split for testing ''' return redis_lock.Lock(self.redis_conn, key, expire=self.settings['REDIS_LOCK_EXPIRATION'], auto_renewal=True)
[ "def", "_create_lock_object", "(", "self", ",", "key", ")", ":", "return", "redis_lock", ".", "Lock", "(", "self", ".", "redis_conn", ",", "key", ",", "expire", "=", "self", ".", "settings", "[", "'REDIS_LOCK_EXPIRATION'", "]", ",", "auto_renewal", "=", "T...
Returns a lock object, split for testing
[ "Returns", "a", "lock", "object", "split", "for", "testing" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/redis_monitor.py#L181-L187
train
istresearch/scrapy-cluster
redis-monitor/redis_monitor.py
RedisMonitor._process_failures
def _process_failures(self, key): ''' Handles the retrying of the failed key ''' if self.settings['RETRY_FAILURES']: self.logger.debug("going to retry failure") # get the current failure count failkey = self._get_fail_key(key) current = sel...
python
def _process_failures(self, key): ''' Handles the retrying of the failed key ''' if self.settings['RETRY_FAILURES']: self.logger.debug("going to retry failure") # get the current failure count failkey = self._get_fail_key(key) current = sel...
[ "def", "_process_failures", "(", "self", ",", "key", ")", ":", "if", "self", ".", "settings", "[", "'RETRY_FAILURES'", "]", ":", "self", ".", "logger", ".", "debug", "(", "\"going to retry failure\"", ")", "failkey", "=", "self", ".", "_get_fail_key", "(", ...
Handles the retrying of the failed key
[ "Handles", "the", "retrying", "of", "the", "failed", "key" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/redis_monitor.py#L195-L216
train
istresearch/scrapy-cluster
redis-monitor/redis_monitor.py
RedisMonitor._setup_stats
def _setup_stats(self): ''' Sets up the stats ''' # stats setup self.stats_dict = {} if self.settings['STATS_TOTAL']: self._setup_stats_total() if self.settings['STATS_PLUGINS']: self._setup_stats_plugins()
python
def _setup_stats(self): ''' Sets up the stats ''' # stats setup self.stats_dict = {} if self.settings['STATS_TOTAL']: self._setup_stats_total() if self.settings['STATS_PLUGINS']: self._setup_stats_plugins()
[ "def", "_setup_stats", "(", "self", ")", ":", "self", ".", "stats_dict", "=", "{", "}", "if", "self", ".", "settings", "[", "'STATS_TOTAL'", "]", ":", "self", ".", "_setup_stats_total", "(", ")", "if", "self", ".", "settings", "[", "'STATS_PLUGINS'", "]"...
Sets up the stats
[ "Sets", "up", "the", "stats" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/redis_monitor.py#L239-L250
train
istresearch/scrapy-cluster
redis-monitor/redis_monitor.py
RedisMonitor._setup_stats_plugins
def _setup_stats_plugins(self): ''' Sets up the plugin stats collectors ''' self.stats_dict['plugins'] = {} for key in self.plugins_dict: plugin_name = self.plugins_dict[key]['instance'].__class__.__name__ temp_key = 'stats:redis-monitor:{p}'.format(p=plug...
python
def _setup_stats_plugins(self): ''' Sets up the plugin stats collectors ''' self.stats_dict['plugins'] = {} for key in self.plugins_dict: plugin_name = self.plugins_dict[key]['instance'].__class__.__name__ temp_key = 'stats:redis-monitor:{p}'.format(p=plug...
[ "def", "_setup_stats_plugins", "(", "self", ")", ":", "self", ".", "stats_dict", "[", "'plugins'", "]", "=", "{", "}", "for", "key", "in", "self", ".", "plugins_dict", ":", "plugin_name", "=", "self", ".", "plugins_dict", "[", "key", "]", "[", "'instance...
Sets up the plugin stats collectors
[ "Sets", "up", "the", "plugin", "stats", "collectors" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/redis_monitor.py#L292-L322
train
istresearch/scrapy-cluster
redis-monitor/redis_monitor.py
RedisMonitor._dump_crawl_stats
def _dump_crawl_stats(self): ''' Dumps flattened crawling stats so the spiders do not have to ''' extras = {} spiders = {} spider_set = set() total_spider_count = 0 keys = self.redis_conn.keys('stats:crawler:*:*:*') for key in keys: #...
python
def _dump_crawl_stats(self): ''' Dumps flattened crawling stats so the spiders do not have to ''' extras = {} spiders = {} spider_set = set() total_spider_count = 0 keys = self.redis_conn.keys('stats:crawler:*:*:*') for key in keys: #...
[ "def", "_dump_crawl_stats", "(", "self", ")", ":", "extras", "=", "{", "}", "spiders", "=", "{", "}", "spider_set", "=", "set", "(", ")", "total_spider_count", "=", "0", "keys", "=", "self", ".", "redis_conn", ".", "keys", "(", "'stats:crawler:*:*:*'", "...
Dumps flattened crawling stats so the spiders do not have to
[ "Dumps", "flattened", "crawling", "stats", "so", "the", "spiders", "do", "not", "have", "to" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/redis_monitor.py#L398-L451
train
istresearch/scrapy-cluster
redis-monitor/redis_monitor.py
RedisMonitor._dump_queue_stats
def _dump_queue_stats(self): ''' Dumps basic info about the queue lengths for the spider types ''' extras = {} keys = self.redis_conn.keys('*:*:queue') total_backlog = 0 for key in keys: elements = key.split(":") spider = elements[0] ...
python
def _dump_queue_stats(self): ''' Dumps basic info about the queue lengths for the spider types ''' extras = {} keys = self.redis_conn.keys('*:*:queue') total_backlog = 0 for key in keys: elements = key.split(":") spider = elements[0] ...
[ "def", "_dump_queue_stats", "(", "self", ")", ":", "extras", "=", "{", "}", "keys", "=", "self", ".", "redis_conn", ".", "keys", "(", "'*:*:queue'", ")", "total_backlog", "=", "0", "for", "key", "in", "keys", ":", "elements", "=", "key", ".", "split", ...
Dumps basic info about the queue lengths for the spider types
[ "Dumps", "basic", "info", "about", "the", "queue", "lengths", "for", "the", "spider", "types" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/redis_monitor.py#L453-L482
train
istresearch/scrapy-cluster
redis-monitor/redis_monitor.py
RedisMonitor.close
def close(self): ''' Closes the Redis Monitor and plugins ''' for plugin_key in self.plugins_dict: obj = self.plugins_dict[plugin_key] instance = obj['instance'] instance.close()
python
def close(self): ''' Closes the Redis Monitor and plugins ''' for plugin_key in self.plugins_dict: obj = self.plugins_dict[plugin_key] instance = obj['instance'] instance.close()
[ "def", "close", "(", "self", ")", ":", "for", "plugin_key", "in", "self", ".", "plugins_dict", ":", "obj", "=", "self", ".", "plugins_dict", "[", "plugin_key", "]", "instance", "=", "obj", "[", "'instance'", "]", "instance", ".", "close", "(", ")" ]
Closes the Redis Monitor and plugins
[ "Closes", "the", "Redis", "Monitor", "and", "plugins" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/redis_monitor.py#L494-L501
train
istresearch/scrapy-cluster
redis-monitor/plugins/stats_monitor.py
StatsMonitor.get_all_stats
def get_all_stats(self): ''' Gather all stats objects ''' self.logger.debug("Gathering all stats") the_dict = {} the_dict['kafka-monitor'] = self.get_kafka_monitor_stats() the_dict['redis-monitor'] = self.get_redis_monitor_stats() the_dict['crawler'] = sel...
python
def get_all_stats(self): ''' Gather all stats objects ''' self.logger.debug("Gathering all stats") the_dict = {} the_dict['kafka-monitor'] = self.get_kafka_monitor_stats() the_dict['redis-monitor'] = self.get_redis_monitor_stats() the_dict['crawler'] = sel...
[ "def", "get_all_stats", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Gathering all stats\"", ")", "the_dict", "=", "{", "}", "the_dict", "[", "'kafka-monitor'", "]", "=", "self", ".", "get_kafka_monitor_stats", "(", ")", "the_dict", "[...
Gather all stats objects
[ "Gather", "all", "stats", "objects" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/plugins/stats_monitor.py#L69-L80
train
istresearch/scrapy-cluster
redis-monitor/plugins/stats_monitor.py
StatsMonitor._get_plugin_stats
def _get_plugin_stats(self, name): ''' Used for getting stats for Plugin based stuff, like Kafka Monitor and Redis Monitor @param name: the main class stats name @return: A formatted dict of stats ''' the_dict = {} keys = self.redis_conn.keys('stats:{n}:...
python
def _get_plugin_stats(self, name): ''' Used for getting stats for Plugin based stuff, like Kafka Monitor and Redis Monitor @param name: the main class stats name @return: A formatted dict of stats ''' the_dict = {} keys = self.redis_conn.keys('stats:{n}:...
[ "def", "_get_plugin_stats", "(", "self", ",", "name", ")", ":", "the_dict", "=", "{", "}", "keys", "=", "self", ".", "redis_conn", ".", "keys", "(", "'stats:{n}:*'", ".", "format", "(", "n", "=", "name", ")", ")", "for", "key", "in", "keys", ":", "...
Used for getting stats for Plugin based stuff, like Kafka Monitor and Redis Monitor @param name: the main class stats name @return: A formatted dict of stats
[ "Used", "for", "getting", "stats", "for", "Plugin", "based", "stuff", "like", "Kafka", "Monitor", "and", "Redis", "Monitor" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/plugins/stats_monitor.py#L109-L146
train
istresearch/scrapy-cluster
redis-monitor/plugins/stats_monitor.py
StatsMonitor._get_key_value
def _get_key_value(self, key, is_hll=False): ''' Returns the proper key value for the stats @param key: the redis key @param is_hll: the key is a HyperLogLog, else is a sorted set ''' if is_hll: # get hll value return self.redis_conn.execute_comma...
python
def _get_key_value(self, key, is_hll=False): ''' Returns the proper key value for the stats @param key: the redis key @param is_hll: the key is a HyperLogLog, else is a sorted set ''' if is_hll: # get hll value return self.redis_conn.execute_comma...
[ "def", "_get_key_value", "(", "self", ",", "key", ",", "is_hll", "=", "False", ")", ":", "if", "is_hll", ":", "return", "self", ".", "redis_conn", ".", "execute_command", "(", "\"PFCOUNT\"", ",", "key", ")", "else", ":", "return", "self", ".", "redis_con...
Returns the proper key value for the stats @param key: the redis key @param is_hll: the key is a HyperLogLog, else is a sorted set
[ "Returns", "the", "proper", "key", "value", "for", "the", "stats" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/plugins/stats_monitor.py#L148-L160
train
istresearch/scrapy-cluster
redis-monitor/plugins/stats_monitor.py
StatsMonitor.get_crawler_stats
def get_crawler_stats(self): ''' Gather crawler stats @return: A dict of stats ''' self.logger.debug("Gathering crawler stats") the_dict = {} the_dict['spiders'] = self.get_spider_stats()['spiders'] the_dict['machines'] = self.get_machine_stats()['machin...
python
def get_crawler_stats(self): ''' Gather crawler stats @return: A dict of stats ''' self.logger.debug("Gathering crawler stats") the_dict = {} the_dict['spiders'] = self.get_spider_stats()['spiders'] the_dict['machines'] = self.get_machine_stats()['machin...
[ "def", "get_crawler_stats", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Gathering crawler stats\"", ")", "the_dict", "=", "{", "}", "the_dict", "[", "'spiders'", "]", "=", "self", ".", "get_spider_stats", "(", ")", "[", "'spiders'", ...
Gather crawler stats @return: A dict of stats
[ "Gather", "crawler", "stats" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/plugins/stats_monitor.py#L246-L259
train
istresearch/scrapy-cluster
redis-monitor/plugins/stats_monitor.py
StatsMonitor.get_queue_stats
def get_queue_stats(self): ''' Gather queue stats @return: A dict of stats ''' self.logger.debug("Gathering queue based stats") the_dict = {} keys = self.redis_conn.keys('*:*:queue') total_backlog = 0 for key in keys: elements = key.s...
python
def get_queue_stats(self): ''' Gather queue stats @return: A dict of stats ''' self.logger.debug("Gathering queue based stats") the_dict = {} keys = self.redis_conn.keys('*:*:queue') total_backlog = 0 for key in keys: elements = key.s...
[ "def", "get_queue_stats", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Gathering queue based stats\"", ")", "the_dict", "=", "{", "}", "keys", "=", "self", ".", "redis_conn", ".", "keys", "(", "'*:*:queue'", ")", "total_backlog", "=", ...
Gather queue stats @return: A dict of stats
[ "Gather", "queue", "stats" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/plugins/stats_monitor.py#L261-L297
train
istresearch/scrapy-cluster
crawler/config/file_pusher.py
main
def main(): ''' A manual configuration file pusher for the crawlers. This will update Zookeeper with the contents of the file specified in the args. ''' import argparse from kazoo.client import KazooClient parser = argparse.ArgumentParser( description="Crawler config file pusher...
python
def main(): ''' A manual configuration file pusher for the crawlers. This will update Zookeeper with the contents of the file specified in the args. ''' import argparse from kazoo.client import KazooClient parser = argparse.ArgumentParser( description="Crawler config file pusher...
[ "def", "main", "(", ")", ":", "import", "argparse", "from", "kazoo", ".", "client", "import", "KazooClient", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Crawler config file pusher to Zookeeper\"", ")", "parser", ".", "add_argument",...
A manual configuration file pusher for the crawlers. This will update Zookeeper with the contents of the file specified in the args.
[ "A", "manual", "configuration", "file", "pusher", "for", "the", "crawlers", ".", "This", "will", "update", "Zookeeper", "with", "the", "contents", "of", "the", "file", "specified", "in", "the", "args", "." ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/crawler/config/file_pusher.py#L5-L54
train
istresearch/scrapy-cluster
utils/scutils/log_factory.py
LogCallbackMixin.is_subdict
def is_subdict(self, a,b): ''' Return True if a is a subdict of b ''' return all((k in b and b[k]==v) for k,v in a.iteritems())
python
def is_subdict(self, a,b): ''' Return True if a is a subdict of b ''' return all((k in b and b[k]==v) for k,v in a.iteritems())
[ "def", "is_subdict", "(", "self", ",", "a", ",", "b", ")", ":", "return", "all", "(", "(", "k", "in", "b", "and", "b", "[", "k", "]", "==", "v", ")", "for", "k", ",", "v", "in", "a", ".", "iteritems", "(", ")", ")" ]
Return True if a is a subdict of b
[ "Return", "True", "if", "a", "is", "a", "subdict", "of", "b" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/log_factory.py#L62-L66
train
istresearch/scrapy-cluster
utils/scutils/log_factory.py
LogObject._check_log_level
def _check_log_level(self, level): ''' Ensures a valid log level @param level: the asked for level ''' if level not in list(self.level_dict.keys()): self.log_level = 'DEBUG' self.logger.warn("Unknown log level '{lev}', defaulting to DEBUG" ...
python
def _check_log_level(self, level): ''' Ensures a valid log level @param level: the asked for level ''' if level not in list(self.level_dict.keys()): self.log_level = 'DEBUG' self.logger.warn("Unknown log level '{lev}', defaulting to DEBUG" ...
[ "def", "_check_log_level", "(", "self", ",", "level", ")", ":", "if", "level", "not", "in", "list", "(", "self", ".", "level_dict", ".", "keys", "(", ")", ")", ":", "self", ".", "log_level", "=", "'DEBUG'", "self", ".", "logger", ".", "warn", "(", ...
Ensures a valid log level @param level: the asked for level
[ "Ensures", "a", "valid", "log", "level" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/log_factory.py#L169-L178
train
istresearch/scrapy-cluster
utils/scutils/log_factory.py
LogObject._get_formatter
def _get_formatter(self, json): ''' Return the proper log formatter @param json: Boolean value ''' if json: return jsonlogger.JsonFormatter() else: return logging.Formatter(self.format_string)
python
def _get_formatter(self, json): ''' Return the proper log formatter @param json: Boolean value ''' if json: return jsonlogger.JsonFormatter() else: return logging.Formatter(self.format_string)
[ "def", "_get_formatter", "(", "self", ",", "json", ")", ":", "if", "json", ":", "return", "jsonlogger", ".", "JsonFormatter", "(", ")", "else", ":", "return", "logging", ".", "Formatter", "(", "self", ".", "format_string", ")" ]
Return the proper log formatter @param json: Boolean value
[ "Return", "the", "proper", "log", "formatter" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/log_factory.py#L180-L189
train
istresearch/scrapy-cluster
utils/scutils/log_factory.py
LogObject.debug
def debug(self, message, extra={}): ''' Writes an error message to the log @param message: The message to write @param extra: The extras object to pass in ''' if self.level_dict['DEBUG'] >= self.level_dict[self.log_level]: extras = self.add_extras(extra, "DEB...
python
def debug(self, message, extra={}): ''' Writes an error message to the log @param message: The message to write @param extra: The extras object to pass in ''' if self.level_dict['DEBUG'] >= self.level_dict[self.log_level]: extras = self.add_extras(extra, "DEB...
[ "def", "debug", "(", "self", ",", "message", ",", "extra", "=", "{", "}", ")", ":", "if", "self", ".", "level_dict", "[", "'DEBUG'", "]", ">=", "self", ".", "level_dict", "[", "self", ".", "log_level", "]", ":", "extras", "=", "self", ".", "add_ext...
Writes an error message to the log @param message: The message to write @param extra: The extras object to pass in
[ "Writes", "an", "error", "message", "to", "the", "log" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/log_factory.py#L191-L201
train
istresearch/scrapy-cluster
utils/scutils/log_factory.py
LogObject._write_message
def _write_message(self, message, extra): ''' Writes the log output @param message: The message to write @param extra: The potential object to write ''' if not self.json: self._write_standard(message, extra) else: self._write_json(message, ...
python
def _write_message(self, message, extra): ''' Writes the log output @param message: The message to write @param extra: The potential object to write ''' if not self.json: self._write_standard(message, extra) else: self._write_json(message, ...
[ "def", "_write_message", "(", "self", ",", "message", ",", "extra", ")", ":", "if", "not", "self", ".", "json", ":", "self", ".", "_write_standard", "(", "message", ",", "extra", ")", "else", ":", "self", ".", "_write_json", "(", "message", ",", "extra...
Writes the log output @param message: The message to write @param extra: The potential object to write
[ "Writes", "the", "log", "output" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/log_factory.py#L260-L269
train
istresearch/scrapy-cluster
utils/scutils/log_factory.py
LogObject._write_standard
def _write_standard(self, message, extra): ''' Writes a standard log statement @param message: The message to write @param extra: The object to pull defaults from ''' level = extra['level'] if self.include_extra: del extra['timestamp'] del...
python
def _write_standard(self, message, extra): ''' Writes a standard log statement @param message: The message to write @param extra: The object to pull defaults from ''' level = extra['level'] if self.include_extra: del extra['timestamp'] del...
[ "def", "_write_standard", "(", "self", ",", "message", ",", "extra", ")", ":", "level", "=", "extra", "[", "'level'", "]", "if", "self", ".", "include_extra", ":", "del", "extra", "[", "'timestamp'", "]", "del", "extra", "[", "'level'", "]", "del", "ex...
Writes a standard log statement @param message: The message to write @param extra: The object to pull defaults from
[ "Writes", "a", "standard", "log", "statement" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/log_factory.py#L271-L297
train
istresearch/scrapy-cluster
utils/scutils/log_factory.py
LogObject._write_json
def _write_json(self, message, extra): ''' The JSON logger doesn't obey log levels @param message: The message to write @param extra: The object to write ''' self.logger.info(message, extra=extra)
python
def _write_json(self, message, extra): ''' The JSON logger doesn't obey log levels @param message: The message to write @param extra: The object to write ''' self.logger.info(message, extra=extra)
[ "def", "_write_json", "(", "self", ",", "message", ",", "extra", ")", ":", "self", ".", "logger", ".", "info", "(", "message", ",", "extra", "=", "extra", ")" ]
The JSON logger doesn't obey log levels @param message: The message to write @param extra: The object to write
[ "The", "JSON", "logger", "doesn", "t", "obey", "log", "levels" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/log_factory.py#L299-L306
train
istresearch/scrapy-cluster
utils/scutils/log_factory.py
LogObject.add_extras
def add_extras(self, dict, level): ''' Adds the log level to the dict object ''' my_copy = copy.deepcopy(dict) if 'level' not in my_copy: my_copy['level'] = level if 'timestamp' not in my_copy: my_copy['timestamp'] = self._get_time() if 'lo...
python
def add_extras(self, dict, level): ''' Adds the log level to the dict object ''' my_copy = copy.deepcopy(dict) if 'level' not in my_copy: my_copy['level'] = level if 'timestamp' not in my_copy: my_copy['timestamp'] = self._get_time() if 'lo...
[ "def", "add_extras", "(", "self", ",", "dict", ",", "level", ")", ":", "my_copy", "=", "copy", ".", "deepcopy", "(", "dict", ")", "if", "'level'", "not", "in", "my_copy", ":", "my_copy", "[", "'level'", "]", "=", "level", "if", "'timestamp'", "not", ...
Adds the log level to the dict object
[ "Adds", "the", "log", "level", "to", "the", "dict", "object" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/log_factory.py#L315-L326
train
istresearch/scrapy-cluster
crawler/crawling/log_retry_middleware.py
LogRetryMiddleware._increment_504_stat
def _increment_504_stat(self, request): ''' Increments the 504 stat counters @param request: The scrapy request in the spider ''' for key in self.stats_dict: if key == 'lifetime': unique = request.url + str(time.time()) self.stats_dict...
python
def _increment_504_stat(self, request): ''' Increments the 504 stat counters @param request: The scrapy request in the spider ''' for key in self.stats_dict: if key == 'lifetime': unique = request.url + str(time.time()) self.stats_dict...
[ "def", "_increment_504_stat", "(", "self", ",", "request", ")", ":", "for", "key", "in", "self", ".", "stats_dict", ":", "if", "key", "==", "'lifetime'", ":", "unique", "=", "request", ".", "url", "+", "str", "(", "time", ".", "time", "(", ")", ")", ...
Increments the 504 stat counters @param request: The scrapy request in the spider
[ "Increments", "the", "504", "stat", "counters" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/crawler/crawling/log_retry_middleware.py#L149-L161
train
istresearch/scrapy-cluster
utils/scutils/redis_throttled_queue.py
RedisThrottledQueue.clear
def clear(self): ''' Clears all data associated with the throttled queue ''' self.redis_conn.delete(self.window_key) self.redis_conn.delete(self.moderate_key) self.queue.clear()
python
def clear(self): ''' Clears all data associated with the throttled queue ''' self.redis_conn.delete(self.window_key) self.redis_conn.delete(self.moderate_key) self.queue.clear()
[ "def", "clear", "(", "self", ")", ":", "self", ".", "redis_conn", ".", "delete", "(", "self", ".", "window_key", ")", "self", ".", "redis_conn", ".", "delete", "(", "self", ".", "moderate_key", ")", "self", ".", "queue", ".", "clear", "(", ")" ]
Clears all data associated with the throttled queue
[ "Clears", "all", "data", "associated", "with", "the", "throttled", "queue" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/redis_throttled_queue.py#L76-L82
train
istresearch/scrapy-cluster
utils/scutils/redis_throttled_queue.py
RedisThrottledQueue.pop
def pop(self, *args): ''' Non-blocking from throttled queue standpoint, tries to return a queue pop request, only will return a request if the given time window has not been exceeded @return: The item if the throttle limit has not been hit, otherwise None ''' ...
python
def pop(self, *args): ''' Non-blocking from throttled queue standpoint, tries to return a queue pop request, only will return a request if the given time window has not been exceeded @return: The item if the throttle limit has not been hit, otherwise None ''' ...
[ "def", "pop", "(", "self", ",", "*", "args", ")", ":", "if", "self", ".", "allowed", "(", ")", ":", "if", "self", ".", "elastic_kick_in", "<", "self", ".", "limit", ":", "self", ".", "elastic_kick_in", "+=", "1", "return", "self", ".", "queue", "."...
Non-blocking from throttled queue standpoint, tries to return a queue pop request, only will return a request if the given time window has not been exceeded @return: The item if the throttle limit has not been hit, otherwise None
[ "Non", "-", "blocking", "from", "throttled", "queue", "standpoint", "tries", "to", "return", "a", "queue", "pop", "request", "only", "will", "return", "a", "request", "if", "the", "given", "time", "window", "has", "not", "been", "exceeded" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/redis_throttled_queue.py#L90-L104
train
istresearch/scrapy-cluster
utils/scutils/redis_throttled_queue.py
RedisThrottledQueue.allowed
def allowed(self): ''' Check to see if the pop request is allowed @return: True means the maximum was not been reached for the current time window, thus allowing what ever operation follows ''' # Expire old keys (hits) expires = time.time() - self.window ...
python
def allowed(self): ''' Check to see if the pop request is allowed @return: True means the maximum was not been reached for the current time window, thus allowing what ever operation follows ''' # Expire old keys (hits) expires = time.time() - self.window ...
[ "def", "allowed", "(", "self", ")", ":", "expires", "=", "time", ".", "time", "(", ")", "-", "self", ".", "window", "self", ".", "redis_conn", ".", "zremrangebyscore", "(", "self", ".", "window_key", ",", "'-inf'", ",", "expires", ")", "if", "self", ...
Check to see if the pop request is allowed @return: True means the maximum was not been reached for the current time window, thus allowing what ever operation follows
[ "Check", "to", "see", "if", "the", "pop", "request", "is", "allowed" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/redis_throttled_queue.py#L112-L157
train
istresearch/scrapy-cluster
utils/scutils/redis_throttled_queue.py
RedisThrottledQueue.check_elastic
def check_elastic(self): ''' Checks if we need to break moderation in order to maintain our desired throttle limit @return: True if we need to break moderation ''' if self.elastic and self.elastic_kick_in == self.limit: value = self.redis_conn.zcard(self.wind...
python
def check_elastic(self): ''' Checks if we need to break moderation in order to maintain our desired throttle limit @return: True if we need to break moderation ''' if self.elastic and self.elastic_kick_in == self.limit: value = self.redis_conn.zcard(self.wind...
[ "def", "check_elastic", "(", "self", ")", ":", "if", "self", ".", "elastic", "and", "self", ".", "elastic_kick_in", "==", "self", ".", "limit", ":", "value", "=", "self", ".", "redis_conn", ".", "zcard", "(", "self", ".", "window_key", ")", "if", "self...
Checks if we need to break moderation in order to maintain our desired throttle limit @return: True if we need to break moderation
[ "Checks", "if", "we", "need", "to", "break", "moderation", "in", "order", "to", "maintain", "our", "desired", "throttle", "limit" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/redis_throttled_queue.py#L159-L170
train
istresearch/scrapy-cluster
utils/scutils/redis_throttled_queue.py
RedisThrottledQueue.is_moderated
def is_moderated(self, curr_time, pipe): ''' Tests to see if the moderation limit is not exceeded @return: True if the moderation limit is exceeded ''' # get key, otherwise default the moderate key expired and # we dont care value = pipe.get(self.moderate_key) ...
python
def is_moderated(self, curr_time, pipe): ''' Tests to see if the moderation limit is not exceeded @return: True if the moderation limit is exceeded ''' # get key, otherwise default the moderate key expired and # we dont care value = pipe.get(self.moderate_key) ...
[ "def", "is_moderated", "(", "self", ",", "curr_time", ",", "pipe", ")", ":", "value", "=", "pipe", ".", "get", "(", "self", ".", "moderate_key", ")", "if", "value", "is", "None", ":", "value", "=", "0.0", "else", ":", "value", "=", "float", "(", "v...
Tests to see if the moderation limit is not exceeded @return: True if the moderation limit is exceeded
[ "Tests", "to", "see", "if", "the", "moderation", "limit", "is", "not", "exceeded" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/redis_throttled_queue.py#L172-L190
train
istresearch/scrapy-cluster
redis-monitor/plugins/info_monitor.py
InfoMonitor._get_bin
def _get_bin(self, key): ''' Returns a binned dictionary based on redis zscore @return: The sorted dict ''' # keys based on score sortedDict = {} # this doesnt return them in order, need to bin first for item in self.redis_conn.zscan_iter(key): ...
python
def _get_bin(self, key): ''' Returns a binned dictionary based on redis zscore @return: The sorted dict ''' # keys based on score sortedDict = {} # this doesnt return them in order, need to bin first for item in self.redis_conn.zscan_iter(key): ...
[ "def", "_get_bin", "(", "self", ",", "key", ")", ":", "sortedDict", "=", "{", "}", "for", "item", "in", "self", ".", "redis_conn", ".", "zscan_iter", "(", "key", ")", ":", "my_item", "=", "ujson", ".", "loads", "(", "item", "[", "0", "]", ")", "m...
Returns a binned dictionary based on redis zscore @return: The sorted dict
[ "Returns", "a", "binned", "dictionary", "based", "on", "redis", "zscore" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/plugins/info_monitor.py#L60-L79
train
istresearch/scrapy-cluster
redis-monitor/plugins/info_monitor.py
InfoMonitor._build_appid_info
def _build_appid_info(self, master, dict): ''' Builds the appid info object @param master: the master dict @param dict: the dict object received @return: the appid info object ''' master['total_crawlids'] = 0 master['total_pending'] = 0 master['to...
python
def _build_appid_info(self, master, dict): ''' Builds the appid info object @param master: the master dict @param dict: the dict object received @return: the appid info object ''' master['total_crawlids'] = 0 master['total_pending'] = 0 master['to...
[ "def", "_build_appid_info", "(", "self", ",", "master", ",", "dict", ")", ":", "master", "[", "'total_crawlids'", "]", "=", "0", "master", "[", "'total_pending'", "]", "=", "0", "master", "[", "'total_domains'", "]", "=", "0", "master", "[", "'crawlids'", ...
Builds the appid info object @param master: the master dict @param dict: the dict object received @return: the appid info object
[ "Builds", "the", "appid", "info", "object" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/plugins/info_monitor.py#L81-L150
train
istresearch/scrapy-cluster
redis-monitor/plugins/info_monitor.py
InfoMonitor._build_crawlid_info
def _build_crawlid_info(self, master, dict): ''' Builds the crawlid info object @param master: the master dict @param dict: the dict object received @return: the crawlid info object ''' master['total_pending'] = 0 master['total_domains'] = 0 maste...
python
def _build_crawlid_info(self, master, dict): ''' Builds the crawlid info object @param master: the master dict @param dict: the dict object received @return: the crawlid info object ''' master['total_pending'] = 0 master['total_domains'] = 0 maste...
[ "def", "_build_crawlid_info", "(", "self", ",", "master", ",", "dict", ")", ":", "master", "[", "'total_pending'", "]", "=", "0", "master", "[", "'total_domains'", "]", "=", "0", "master", "[", "'appid'", "]", "=", "dict", "[", "'appid'", "]", "master", ...
Builds the crawlid info object @param master: the master dict @param dict: the dict object received @return: the crawlid info object
[ "Builds", "the", "crawlid", "info", "object" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/plugins/info_monitor.py#L152-L202
train
istresearch/scrapy-cluster
redis-monitor/plugins/stop_monitor.py
StopMonitor._purge_crawl
def _purge_crawl(self, spiderid, appid, crawlid): ''' Wrapper for purging the crawlid from the queues @param spiderid: the spider id @param appid: the app id @param crawlid: the crawl id @return: The number of requests purged ''' # purge three times to tr...
python
def _purge_crawl(self, spiderid, appid, crawlid): ''' Wrapper for purging the crawlid from the queues @param spiderid: the spider id @param appid: the app id @param crawlid: the crawl id @return: The number of requests purged ''' # purge three times to tr...
[ "def", "_purge_crawl", "(", "self", ",", "spiderid", ",", "appid", ",", "crawlid", ")", ":", "total", "=", "self", ".", "_mini_purge", "(", "spiderid", ",", "appid", ",", "crawlid", ")", "total", "=", "total", "+", "self", ".", "_mini_purge", "(", "spi...
Wrapper for purging the crawlid from the queues @param spiderid: the spider id @param appid: the app id @param crawlid: the crawl id @return: The number of requests purged
[ "Wrapper", "for", "purging", "the", "crawlid", "from", "the", "queues" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/plugins/stop_monitor.py#L73-L87
train
istresearch/scrapy-cluster
redis-monitor/plugins/stop_monitor.py
StopMonitor._mini_purge
def _mini_purge(self, spiderid, appid, crawlid): ''' Actually purges the crawlid from the queue @param spiderid: the spider id @param appid: the app id @param crawlid: the crawl id @return: The number of requests purged ''' total_purged = 0 match...
python
def _mini_purge(self, spiderid, appid, crawlid): ''' Actually purges the crawlid from the queue @param spiderid: the spider id @param appid: the app id @param crawlid: the crawl id @return: The number of requests purged ''' total_purged = 0 match...
[ "def", "_mini_purge", "(", "self", ",", "spiderid", ",", "appid", ",", "crawlid", ")", ":", "total_purged", "=", "0", "match_string", "=", "'{sid}:*:queue'", ".", "format", "(", "sid", "=", "spiderid", ")", "for", "key", "in", "self", ".", "redis_conn", ...
Actually purges the crawlid from the queue @param spiderid: the spider id @param appid: the app id @param crawlid: the crawl id @return: The number of requests purged
[ "Actually", "purges", "the", "crawlid", "from", "the", "queue" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/plugins/stop_monitor.py#L89-L113
train
istresearch/scrapy-cluster
rest/rest_service.py
log_call
def log_call(call_name): """Log the API call to the logger.""" def decorator(f): @wraps(f) def wrapper(*args, **kw): instance = args[0] instance.logger.info(call_name, {"content": request.get_json()}) return f(*args, **kw) return wrapper return dec...
python
def log_call(call_name): """Log the API call to the logger.""" def decorator(f): @wraps(f) def wrapper(*args, **kw): instance = args[0] instance.logger.info(call_name, {"content": request.get_json()}) return f(*args, **kw) return wrapper return dec...
[ "def", "log_call", "(", "call_name", ")", ":", "def", "decorator", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kw", ")", ":", "instance", "=", "args", "[", "0", "]", "instance", ".", "logger", ...
Log the API call to the logger.
[ "Log", "the", "API", "call", "to", "the", "logger", "." ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L38-L47
train
istresearch/scrapy-cluster
rest/rest_service.py
error_catch
def error_catch(f): """Handle unexpected errors within the rest function.""" @wraps(f) def wrapper(*args, **kw): instance = args[0] try: result = f(*args, **kw) if isinstance(result, tuple): return jsonify(result[0]), result[1] else: ...
python
def error_catch(f): """Handle unexpected errors within the rest function.""" @wraps(f) def wrapper(*args, **kw): instance = args[0] try: result = f(*args, **kw) if isinstance(result, tuple): return jsonify(result[0]), result[1] else: ...
[ "def", "error_catch", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kw", ")", ":", "instance", "=", "args", "[", "0", "]", "try", ":", "result", "=", "f", "(", "*", "args", ",", "**", "kw", ...
Handle unexpected errors within the rest function.
[ "Handle", "unexpected", "errors", "within", "the", "rest", "function", "." ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L50-L71
train
istresearch/scrapy-cluster
rest/rest_service.py
validate_json
def validate_json(f): """Validate that the call is JSON.""" @wraps(f) def wrapper(*args, **kw): instance = args[0] try: if request.get_json() is None: ret_dict = instance._create_ret_object(instance.FAILURE, N...
python
def validate_json(f): """Validate that the call is JSON.""" @wraps(f) def wrapper(*args, **kw): instance = args[0] try: if request.get_json() is None: ret_dict = instance._create_ret_object(instance.FAILURE, N...
[ "def", "validate_json", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kw", ")", ":", "instance", "=", "args", "[", "0", "]", "try", ":", "if", "request", ".", "get_json", "(", ")", "is", "None"...
Validate that the call is JSON.
[ "Validate", "that", "the", "call", "is", "JSON", "." ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L74-L94
train
istresearch/scrapy-cluster
rest/rest_service.py
validate_schema
def validate_schema(schema_name): """Validate the JSON against a required schema_name.""" def decorator(f): @wraps(f) def wrapper(*args, **kw): instance = args[0] try: instance.validator(instance.schemas[schema_name]).validate(request.get_json()) ...
python
def validate_schema(schema_name): """Validate the JSON against a required schema_name.""" def decorator(f): @wraps(f) def wrapper(*args, **kw): instance = args[0] try: instance.validator(instance.schemas[schema_name]).validate(request.get_json()) ...
[ "def", "validate_schema", "(", "schema_name", ")", ":", "def", "decorator", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kw", ")", ":", "instance", "=", "args", "[", "0", "]", "try", ":", "insta...
Validate the JSON against a required schema_name.
[ "Validate", "the", "JSON", "against", "a", "required", "schema_name", "." ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L97-L115
train
istresearch/scrapy-cluster
rest/rest_service.py
RestService._load_schemas
def _load_schemas(self): """Loads any schemas for JSON validation""" for filename in os.listdir(self.settings['SCHEMA_DIR']): if filename[-4:] == 'json': name = filename[:-5] with open(self.settings['SCHEMA_DIR'] + filename) as the_file: se...
python
def _load_schemas(self): """Loads any schemas for JSON validation""" for filename in os.listdir(self.settings['SCHEMA_DIR']): if filename[-4:] == 'json': name = filename[:-5] with open(self.settings['SCHEMA_DIR'] + filename) as the_file: se...
[ "def", "_load_schemas", "(", "self", ")", ":", "for", "filename", "in", "os", ".", "listdir", "(", "self", ".", "settings", "[", "'SCHEMA_DIR'", "]", ")", ":", "if", "filename", "[", "-", "4", ":", "]", "==", "'json'", ":", "name", "=", "filename", ...
Loads any schemas for JSON validation
[ "Loads", "any", "schemas", "for", "JSON", "validation" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L198-L205
train
istresearch/scrapy-cluster
rest/rest_service.py
RestService._spawn_redis_connection_thread
def _spawn_redis_connection_thread(self): """Spawns a redis connection thread""" self.logger.debug("Spawn redis connection thread") self.redis_connected = False self._redis_thread = Thread(target=self._setup_redis) self._redis_thread.setDaemon(True) self._redis_thread.sta...
python
def _spawn_redis_connection_thread(self): """Spawns a redis connection thread""" self.logger.debug("Spawn redis connection thread") self.redis_connected = False self._redis_thread = Thread(target=self._setup_redis) self._redis_thread.setDaemon(True) self._redis_thread.sta...
[ "def", "_spawn_redis_connection_thread", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Spawn redis connection thread\"", ")", "self", ".", "redis_connected", "=", "False", "self", ".", "_redis_thread", "=", "Thread", "(", "target", "=", "se...
Spawns a redis connection thread
[ "Spawns", "a", "redis", "connection", "thread" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L228-L234
train
istresearch/scrapy-cluster
rest/rest_service.py
RestService._spawn_kafka_connection_thread
def _spawn_kafka_connection_thread(self): """Spawns a kafka connection thread""" self.logger.debug("Spawn kafka connection thread") self.kafka_connected = False self._kafka_thread = Thread(target=self._setup_kafka) self._kafka_thread.setDaemon(True) self._kafka_thread.sta...
python
def _spawn_kafka_connection_thread(self): """Spawns a kafka connection thread""" self.logger.debug("Spawn kafka connection thread") self.kafka_connected = False self._kafka_thread = Thread(target=self._setup_kafka) self._kafka_thread.setDaemon(True) self._kafka_thread.sta...
[ "def", "_spawn_kafka_connection_thread", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Spawn kafka connection thread\"", ")", "self", ".", "kafka_connected", "=", "False", "self", ".", "_kafka_thread", "=", "Thread", "(", "target", "=", "se...
Spawns a kafka connection thread
[ "Spawns", "a", "kafka", "connection", "thread" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L236-L242
train
istresearch/scrapy-cluster
rest/rest_service.py
RestService._consumer_loop
def _consumer_loop(self): """The main consumer loop""" self.logger.debug("running main consumer thread") while not self.closed: if self.kafka_connected: self._process_messages() time.sleep(self.settings['KAFKA_CONSUMER_SLEEP_TIME'])
python
def _consumer_loop(self): """The main consumer loop""" self.logger.debug("running main consumer thread") while not self.closed: if self.kafka_connected: self._process_messages() time.sleep(self.settings['KAFKA_CONSUMER_SLEEP_TIME'])
[ "def", "_consumer_loop", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"running main consumer thread\"", ")", "while", "not", "self", ".", "closed", ":", "if", "self", ".", "kafka_connected", ":", "self", ".", "_process_messages", "(", "...
The main consumer loop
[ "The", "main", "consumer", "loop" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L251-L257
train
istresearch/scrapy-cluster
rest/rest_service.py
RestService._process_messages
def _process_messages(self): """Processes messages received from kafka""" try: for message in self.consumer: try: if message is None: self.logger.debug("no message") break loaded_dict = js...
python
def _process_messages(self): """Processes messages received from kafka""" try: for message in self.consumer: try: if message is None: self.logger.debug("no message") break loaded_dict = js...
[ "def", "_process_messages", "(", "self", ")", ":", "try", ":", "for", "message", "in", "self", ".", "consumer", ":", "try", ":", "if", "message", "is", "None", ":", "self", ".", "logger", ".", "debug", "(", "\"no message\"", ")", "break", "loaded_dict", ...
Processes messages received from kafka
[ "Processes", "messages", "received", "from", "kafka" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L259-L293
train
istresearch/scrapy-cluster
rest/rest_service.py
RestService._send_result_to_redis
def _send_result_to_redis(self, result): """Sends the result of a poll to redis to be used potentially by another process @param result: the result retrieved from kafka""" if self.redis_connected: self.logger.debug("Sending result to redis") try: ...
python
def _send_result_to_redis(self, result): """Sends the result of a poll to redis to be used potentially by another process @param result: the result retrieved from kafka""" if self.redis_connected: self.logger.debug("Sending result to redis") try: ...
[ "def", "_send_result_to_redis", "(", "self", ",", "result", ")", ":", "if", "self", ".", "redis_connected", ":", "self", ".", "logger", ".", "debug", "(", "\"Sending result to redis\"", ")", "try", ":", "key", "=", "\"rest:poll:{u}\"", ".", "format", "(", "u...
Sends the result of a poll to redis to be used potentially by another process @param result: the result retrieved from kafka
[ "Sends", "the", "result", "of", "a", "poll", "to", "redis", "to", "be", "used", "potentially", "by", "another", "process" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L295-L309
train
istresearch/scrapy-cluster
rest/rest_service.py
RestService._check_kafka_disconnect
def _check_kafka_disconnect(self): """Checks the kafka connection is still valid""" for node_id in self.consumer._client._conns: conn = self.consumer._client._conns[node_id] if conn.state == ConnectionStates.DISCONNECTED or \ conn.state == ConnectionStates.DIS...
python
def _check_kafka_disconnect(self): """Checks the kafka connection is still valid""" for node_id in self.consumer._client._conns: conn = self.consumer._client._conns[node_id] if conn.state == ConnectionStates.DISCONNECTED or \ conn.state == ConnectionStates.DIS...
[ "def", "_check_kafka_disconnect", "(", "self", ")", ":", "for", "node_id", "in", "self", ".", "consumer", ".", "_client", ".", "_conns", ":", "conn", "=", "self", ".", "consumer", ".", "_client", ".", "_conns", "[", "node_id", "]", "if", "conn", ".", "...
Checks the kafka connection is still valid
[ "Checks", "the", "kafka", "connection", "is", "still", "valid" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L311-L318
train
istresearch/scrapy-cluster
rest/rest_service.py
RestService._heartbeat_loop
def _heartbeat_loop(self): """A main run loop thread to do work""" self.logger.debug("running main heartbeat thread") while not self.closed: time.sleep(self.settings['SLEEP_TIME']) self._report_self()
python
def _heartbeat_loop(self): """A main run loop thread to do work""" self.logger.debug("running main heartbeat thread") while not self.closed: time.sleep(self.settings['SLEEP_TIME']) self._report_self()
[ "def", "_heartbeat_loop", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"running main heartbeat thread\"", ")", "while", "not", "self", ".", "closed", ":", "time", ".", "sleep", "(", "self", ".", "settings", "[", "'SLEEP_TIME'", "]", "...
A main run loop thread to do work
[ "A", "main", "run", "loop", "thread", "to", "do", "work" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L320-L325
train
istresearch/scrapy-cluster
rest/rest_service.py
RestService._setup_redis
def _setup_redis(self): """Returns a Redis Client""" if not self.closed: try: self.logger.debug("Creating redis connection to host " + str(self.settings['REDIS_HOST'])) self.redis_conn = redis.StrictRedis(host=self.settings['R...
python
def _setup_redis(self): """Returns a Redis Client""" if not self.closed: try: self.logger.debug("Creating redis connection to host " + str(self.settings['REDIS_HOST'])) self.redis_conn = redis.StrictRedis(host=self.settings['R...
[ "def", "_setup_redis", "(", "self", ")", ":", "if", "not", "self", ".", "closed", ":", "try", ":", "self", ".", "logger", ".", "debug", "(", "\"Creating redis connection to host \"", "+", "str", "(", "self", ".", "settings", "[", "'REDIS_HOST'", "]", ")", ...
Returns a Redis Client
[ "Returns", "a", "Redis", "Client" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L347-L365
train
istresearch/scrapy-cluster
rest/rest_service.py
RestService._setup_kafka
def _setup_kafka(self): """ Sets up kafka connections """ # close older connections if self.consumer is not None: self.logger.debug("Closing existing kafka consumer") self.consumer.close() self.consumer = None if self.producer is not No...
python
def _setup_kafka(self): """ Sets up kafka connections """ # close older connections if self.consumer is not None: self.logger.debug("Closing existing kafka consumer") self.consumer.close() self.consumer = None if self.producer is not No...
[ "def", "_setup_kafka", "(", "self", ")", ":", "if", "self", ".", "consumer", "is", "not", "None", ":", "self", ".", "logger", ".", "debug", "(", "\"Closing existing kafka consumer\"", ")", "self", ".", "consumer", ".", "close", "(", ")", "self", ".", "co...
Sets up kafka connections
[ "Sets", "up", "kafka", "connections" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L367-L395
train
istresearch/scrapy-cluster
rest/rest_service.py
RestService._create_consumer
def _create_consumer(self): """Tries to establing the Kafka consumer connection""" if not self.closed: try: self.logger.debug("Creating new kafka consumer using brokers: " + str(self.settings['KAFKA_HOSTS']) + ' and topic ' + ...
python
def _create_consumer(self): """Tries to establing the Kafka consumer connection""" if not self.closed: try: self.logger.debug("Creating new kafka consumer using brokers: " + str(self.settings['KAFKA_HOSTS']) + ' and topic ' + ...
[ "def", "_create_consumer", "(", "self", ")", ":", "if", "not", "self", ".", "closed", ":", "try", ":", "self", ".", "logger", ".", "debug", "(", "\"Creating new kafka consumer using brokers: \"", "+", "str", "(", "self", ".", "settings", "[", "'KAFKA_HOSTS'", ...
Tries to establing the Kafka consumer connection
[ "Tries", "to", "establing", "the", "Kafka", "consumer", "connection" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L398-L422
train
istresearch/scrapy-cluster
rest/rest_service.py
RestService.run
def run(self): """Main flask run loop""" self.logger.info("Running main flask method on port " + str(self.settings['FLASK_PORT'])) self.app.run(host='0.0.0.0', port=self.settings['FLASK_PORT'])
python
def run(self): """Main flask run loop""" self.logger.info("Running main flask method on port " + str(self.settings['FLASK_PORT'])) self.app.run(host='0.0.0.0', port=self.settings['FLASK_PORT'])
[ "def", "run", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Running main flask method on port \"", "+", "str", "(", "self", ".", "settings", "[", "'FLASK_PORT'", "]", ")", ")", "self", ".", "app", ".", "run", "(", "host", "=", "'0....
Main flask run loop
[ "Main", "flask", "run", "loop" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L445-L449
train
istresearch/scrapy-cluster
rest/rest_service.py
RestService._create_ret_object
def _create_ret_object(self, status=SUCCESS, data=None, error=False, error_message=None, error_cause=None): """ Create generic reponse objects. :param str status: The SUCCESS or FAILURE of the request :param obj data: The data to return :param bool err...
python
def _create_ret_object(self, status=SUCCESS, data=None, error=False, error_message=None, error_cause=None): """ Create generic reponse objects. :param str status: The SUCCESS or FAILURE of the request :param obj data: The data to return :param bool err...
[ "def", "_create_ret_object", "(", "self", ",", "status", "=", "SUCCESS", ",", "data", "=", "None", ",", "error", "=", "False", ",", "error_message", "=", "None", ",", "error_cause", "=", "None", ")", ":", "ret", "=", "{", "}", "if", "status", "==", "...
Create generic reponse objects. :param str status: The SUCCESS or FAILURE of the request :param obj data: The data to return :param bool error: Set to True to add Error response :param str error_message: The generic error message :param str error_cause: The cause of the error ...
[ "Create", "generic", "reponse", "objects", "." ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L451-L478
train
istresearch/scrapy-cluster
rest/rest_service.py
RestService._close_thread
def _close_thread(self, thread, thread_name): """Closes daemon threads @param thread: the thread to close @param thread_name: a human readable name of the thread """ if thread is not None and thread.isAlive(): self.logger.debug("Waiting for {} thread to close".format...
python
def _close_thread(self, thread, thread_name): """Closes daemon threads @param thread: the thread to close @param thread_name: a human readable name of the thread """ if thread is not None and thread.isAlive(): self.logger.debug("Waiting for {} thread to close".format...
[ "def", "_close_thread", "(", "self", ",", "thread", ",", "thread_name", ")", ":", "if", "thread", "is", "not", "None", "and", "thread", ".", "isAlive", "(", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Waiting for {} thread to close\"", ".", "for...
Closes daemon threads @param thread: the thread to close @param thread_name: a human readable name of the thread
[ "Closes", "daemon", "threads" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L480-L491
train
istresearch/scrapy-cluster
rest/rest_service.py
RestService.close
def close(self): """ Cleans up anything from the process """ self.logger.info("Closing Rest Service") self.closed = True # close threads self._close_thread(self._redis_thread, "Redis setup") self._close_thread(self._heartbeat_thread, "Heartbeat") ...
python
def close(self): """ Cleans up anything from the process """ self.logger.info("Closing Rest Service") self.closed = True # close threads self._close_thread(self._redis_thread, "Redis setup") self._close_thread(self._heartbeat_thread, "Heartbeat") ...
[ "def", "close", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Closing Rest Service\"", ")", "self", ".", "closed", "=", "True", "self", ".", "_close_thread", "(", "self", ".", "_redis_thread", ",", "\"Redis setup\"", ")", "self", ".", ...
Cleans up anything from the process
[ "Cleans", "up", "anything", "from", "the", "process" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L493-L512
train
istresearch/scrapy-cluster
rest/rest_service.py
RestService._calculate_health
def _calculate_health(self): """Returns a string representation of the node health @returns: GREEN if fully connected, YELLOW if partially connected, RED if not connected """ if self.redis_connected and self.kafka_connected: return "GREEN" elif self...
python
def _calculate_health(self): """Returns a string representation of the node health @returns: GREEN if fully connected, YELLOW if partially connected, RED if not connected """ if self.redis_connected and self.kafka_connected: return "GREEN" elif self...
[ "def", "_calculate_health", "(", "self", ")", ":", "if", "self", ".", "redis_connected", "and", "self", ".", "kafka_connected", ":", "return", "\"GREEN\"", "elif", "self", ".", "redis_connected", "or", "self", ".", "kafka_connected", ":", "return", "\"YELLOW\"",...
Returns a string representation of the node health @returns: GREEN if fully connected, YELLOW if partially connected, RED if not connected
[ "Returns", "a", "string", "representation", "of", "the", "node", "health" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L514-L525
train
istresearch/scrapy-cluster
rest/rest_service.py
RestService._feed_to_kafka
def _feed_to_kafka(self, json_item): """Sends a request to Kafka :param json_item: The json item to send :returns: A boolean indicating whther the data was sent successfully or not """ @MethodTimer.timeout(self.settings['KAFKA_FEED_TIMEOUT'], False) def _feed(json_item):...
python
def _feed_to_kafka(self, json_item): """Sends a request to Kafka :param json_item: The json item to send :returns: A boolean indicating whther the data was sent successfully or not """ @MethodTimer.timeout(self.settings['KAFKA_FEED_TIMEOUT'], False) def _feed(json_item):...
[ "def", "_feed_to_kafka", "(", "self", ",", "json_item", ")", ":", "@", "MethodTimer", ".", "timeout", "(", "self", ".", "settings", "[", "'KAFKA_FEED_TIMEOUT'", "]", ",", "False", ")", "def", "_feed", "(", "json_item", ")", ":", "try", ":", "self", ".", ...
Sends a request to Kafka :param json_item: The json item to send :returns: A boolean indicating whther the data was sent successfully or not
[ "Sends", "a", "request", "to", "Kafka" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L540-L565
train
istresearch/scrapy-cluster
rest/rest_service.py
RestService._decorate_routes
def _decorate_routes(self): """ Decorates the routes to use within the flask app """ self.logger.debug("Decorating routes") # self.app.add_url_rule('/', 'catch', self.catch, methods=['GET'], # defaults={'path': ''}) self.app.add_url_rule('/<...
python
def _decorate_routes(self): """ Decorates the routes to use within the flask app """ self.logger.debug("Decorating routes") # self.app.add_url_rule('/', 'catch', self.catch, methods=['GET'], # defaults={'path': ''}) self.app.add_url_rule('/<...
[ "def", "_decorate_routes", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Decorating routes\"", ")", "self", ".", "app", ".", "add_url_rule", "(", "'/<path:path>'", ",", "'catch'", ",", "self", ".", "catch", ",", "methods", "=", "[", ...
Decorates the routes to use within the flask app
[ "Decorates", "the", "routes", "to", "use", "within", "the", "flask", "app" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L569-L583
train
istresearch/scrapy-cluster
rest/rest_service.py
RestService.poll
def poll(self): """Retrieves older requests that may not make it back quick enough""" if self.redis_connected: json_item = request.get_json() result = None try: key = "rest:poll:{u}".format(u=json_item['poll_id']) result = self....
python
def poll(self): """Retrieves older requests that may not make it back quick enough""" if self.redis_connected: json_item = request.get_json() result = None try: key = "rest:poll:{u}".format(u=json_item['poll_id']) result = self....
[ "def", "poll", "(", "self", ")", ":", "if", "self", ".", "redis_connected", ":", "json_item", "=", "request", ".", "get_json", "(", ")", "result", "=", "None", "try", ":", "key", "=", "\"rest:poll:{u}\"", ".", "format", "(", "u", "=", "json_item", "[",...
Retrieves older requests that may not make it back quick enough
[ "Retrieves", "older", "requests", "that", "may", "not", "make", "it", "back", "quick", "enough" ]
13aaed2349af5d792d6bcbfcadc5563158aeb599
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/rest/rest_service.py#L661-L695
train
vimalloc/flask-jwt-extended
flask_jwt_extended/utils.py
create_refresh_token
def create_refresh_token(identity, expires_delta=None, user_claims=None): """ Creates a new refresh token. :param identity: The identity of this token, which can be any data that is json serializable. It can also be a python object, in which case you can use the ...
python
def create_refresh_token(identity, expires_delta=None, user_claims=None): """ Creates a new refresh token. :param identity: The identity of this token, which can be any data that is json serializable. It can also be a python object, in which case you can use the ...
[ "def", "create_refresh_token", "(", "identity", ",", "expires_delta", "=", "None", ",", "user_claims", "=", "None", ")", ":", "jwt_manager", "=", "_get_jwt_manager", "(", ")", "return", "jwt_manager", ".", "_create_refresh_token", "(", "identity", ",", "expires_de...
Creates a new refresh token. :param identity: The identity of this token, which can be any data that is json serializable. It can also be a python object, in which case you can use the :meth:`~flask_jwt_extended.JWTManager.user_identity_loader` ...
[ "Creates", "a", "new", "refresh", "token", "." ]
569d3b89eb5d2586d0cff4581a346229c623cefc
https://github.com/vimalloc/flask-jwt-extended/blob/569d3b89eb5d2586d0cff4581a346229c623cefc/flask_jwt_extended/utils.py#L160-L179
train
vimalloc/flask-jwt-extended
examples/database_blacklist/blacklist_helpers.py
is_token_revoked
def is_token_revoked(decoded_token): """ Checks if the given token is revoked or not. Because we are adding all the tokens that we create into this database, if the token is not present in the database we are going to consider it revoked, as we don't know where it was created. """ jti = deco...
python
def is_token_revoked(decoded_token): """ Checks if the given token is revoked or not. Because we are adding all the tokens that we create into this database, if the token is not present in the database we are going to consider it revoked, as we don't know where it was created. """ jti = deco...
[ "def", "is_token_revoked", "(", "decoded_token", ")", ":", "jti", "=", "decoded_token", "[", "'jti'", "]", "try", ":", "token", "=", "TokenBlacklist", ".", "query", ".", "filter_by", "(", "jti", "=", "jti", ")", ".", "one", "(", ")", "return", "token", ...
Checks if the given token is revoked or not. Because we are adding all the tokens that we create into this database, if the token is not present in the database we are going to consider it revoked, as we don't know where it was created.
[ "Checks", "if", "the", "given", "token", "is", "revoked", "or", "not", ".", "Because", "we", "are", "adding", "all", "the", "tokens", "that", "we", "create", "into", "this", "database", "if", "the", "token", "is", "not", "present", "in", "the", "database...
569d3b89eb5d2586d0cff4581a346229c623cefc
https://github.com/vimalloc/flask-jwt-extended/blob/569d3b89eb5d2586d0cff4581a346229c623cefc/examples/database_blacklist/blacklist_helpers.py#L42-L54
train
vimalloc/flask-jwt-extended
examples/database_blacklist/blacklist_helpers.py
revoke_token
def revoke_token(token_id, user): """ Revokes the given token. Raises a TokenNotFound error if the token does not exist in the database """ try: token = TokenBlacklist.query.filter_by(id=token_id, user_identity=user).one() token.revoked = True db.session.commit() except N...
python
def revoke_token(token_id, user): """ Revokes the given token. Raises a TokenNotFound error if the token does not exist in the database """ try: token = TokenBlacklist.query.filter_by(id=token_id, user_identity=user).one() token.revoked = True db.session.commit() except N...
[ "def", "revoke_token", "(", "token_id", ",", "user", ")", ":", "try", ":", "token", "=", "TokenBlacklist", ".", "query", ".", "filter_by", "(", "id", "=", "token_id", ",", "user_identity", "=", "user", ")", ".", "one", "(", ")", "token", ".", "revoked"...
Revokes the given token. Raises a TokenNotFound error if the token does not exist in the database
[ "Revokes", "the", "given", "token", ".", "Raises", "a", "TokenNotFound", "error", "if", "the", "token", "does", "not", "exist", "in", "the", "database" ]
569d3b89eb5d2586d0cff4581a346229c623cefc
https://github.com/vimalloc/flask-jwt-extended/blob/569d3b89eb5d2586d0cff4581a346229c623cefc/examples/database_blacklist/blacklist_helpers.py#L65-L75
train
vimalloc/flask-jwt-extended
examples/database_blacklist/blacklist_helpers.py
prune_database
def prune_database(): """ Delete tokens that have expired from the database. How (and if) you call this is entirely up you. You could expose it to an endpoint that only administrators could call, you could run it as a cron, set it up with flask cli, etc. """ now = datetime.now() expired...
python
def prune_database(): """ Delete tokens that have expired from the database. How (and if) you call this is entirely up you. You could expose it to an endpoint that only administrators could call, you could run it as a cron, set it up with flask cli, etc. """ now = datetime.now() expired...
[ "def", "prune_database", "(", ")", ":", "now", "=", "datetime", ".", "now", "(", ")", "expired", "=", "TokenBlacklist", ".", "query", ".", "filter", "(", "TokenBlacklist", ".", "expires", "<", "now", ")", ".", "all", "(", ")", "for", "token", "in", "...
Delete tokens that have expired from the database. How (and if) you call this is entirely up you. You could expose it to an endpoint that only administrators could call, you could run it as a cron, set it up with flask cli, etc.
[ "Delete", "tokens", "that", "have", "expired", "from", "the", "database", "." ]
569d3b89eb5d2586d0cff4581a346229c623cefc
https://github.com/vimalloc/flask-jwt-extended/blob/569d3b89eb5d2586d0cff4581a346229c623cefc/examples/database_blacklist/blacklist_helpers.py#L91-L103
train
vimalloc/flask-jwt-extended
flask_jwt_extended/view_decorators.py
verify_jwt_in_request
def verify_jwt_in_request(): """ Ensure that the requester has a valid access token. This does not check the freshness of the access token. Raises an appropiate exception there is no token or if the token is invalid. """ if request.method not in config.exempt_methods: jwt_data = _decode_...
python
def verify_jwt_in_request(): """ Ensure that the requester has a valid access token. This does not check the freshness of the access token. Raises an appropiate exception there is no token or if the token is invalid. """ if request.method not in config.exempt_methods: jwt_data = _decode_...
[ "def", "verify_jwt_in_request", "(", ")", ":", "if", "request", ".", "method", "not", "in", "config", ".", "exempt_methods", ":", "jwt_data", "=", "_decode_jwt_from_request", "(", "request_type", "=", "'access'", ")", "ctx_stack", ".", "top", ".", "jwt", "=", ...
Ensure that the requester has a valid access token. This does not check the freshness of the access token. Raises an appropiate exception there is no token or if the token is invalid.
[ "Ensure", "that", "the", "requester", "has", "a", "valid", "access", "token", ".", "This", "does", "not", "check", "the", "freshness", "of", "the", "access", "token", ".", "Raises", "an", "appropiate", "exception", "there", "is", "no", "token", "or", "if",...
569d3b89eb5d2586d0cff4581a346229c623cefc
https://github.com/vimalloc/flask-jwt-extended/blob/569d3b89eb5d2586d0cff4581a346229c623cefc/flask_jwt_extended/view_decorators.py#L24-L34
train
vimalloc/flask-jwt-extended
flask_jwt_extended/view_decorators.py
verify_fresh_jwt_in_request
def verify_fresh_jwt_in_request(): """ Ensure that the requester has a valid and fresh access token. Raises an appropiate exception if there is no token, the token is invalid, or the token is not marked as fresh. """ if request.method not in config.exempt_methods: jwt_data = _decode_jwt_...
python
def verify_fresh_jwt_in_request(): """ Ensure that the requester has a valid and fresh access token. Raises an appropiate exception if there is no token, the token is invalid, or the token is not marked as fresh. """ if request.method not in config.exempt_methods: jwt_data = _decode_jwt_...
[ "def", "verify_fresh_jwt_in_request", "(", ")", ":", "if", "request", ".", "method", "not", "in", "config", ".", "exempt_methods", ":", "jwt_data", "=", "_decode_jwt_from_request", "(", "request_type", "=", "'access'", ")", "ctx_stack", ".", "top", ".", "jwt", ...
Ensure that the requester has a valid and fresh access token. Raises an appropiate exception if there is no token, the token is invalid, or the token is not marked as fresh.
[ "Ensure", "that", "the", "requester", "has", "a", "valid", "and", "fresh", "access", "token", ".", "Raises", "an", "appropiate", "exception", "if", "there", "is", "no", "token", "the", "token", "is", "invalid", "or", "the", "token", "is", "not", "marked", ...
569d3b89eb5d2586d0cff4581a346229c623cefc
https://github.com/vimalloc/flask-jwt-extended/blob/569d3b89eb5d2586d0cff4581a346229c623cefc/flask_jwt_extended/view_decorators.py#L58-L76
train
vimalloc/flask-jwt-extended
flask_jwt_extended/view_decorators.py
jwt_optional
def jwt_optional(fn): """ A decorator to optionally protect a Flask endpoint If an access token in present in the request, this will call the endpoint with :func:`~flask_jwt_extended.get_jwt_identity` having the identity of the access token. If no access token is present in the request, this en...
python
def jwt_optional(fn): """ A decorator to optionally protect a Flask endpoint If an access token in present in the request, this will call the endpoint with :func:`~flask_jwt_extended.get_jwt_identity` having the identity of the access token. If no access token is present in the request, this en...
[ "def", "jwt_optional", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "verify_jwt_in_request_optional", "(", ")", "return", "fn", "(", "*", "args", ",", "**", "kwargs", ")", "retu...
A decorator to optionally protect a Flask endpoint If an access token in present in the request, this will call the endpoint with :func:`~flask_jwt_extended.get_jwt_identity` having the identity of the access token. If no access token is present in the request, this endpoint will still be called, but ...
[ "A", "decorator", "to", "optionally", "protect", "a", "Flask", "endpoint" ]
569d3b89eb5d2586d0cff4581a346229c623cefc
https://github.com/vimalloc/flask-jwt-extended/blob/569d3b89eb5d2586d0cff4581a346229c623cefc/flask_jwt_extended/view_decorators.py#L107-L125
train
MycroftAI/mycroft-precise
precise/model.py
load_precise_model
def load_precise_model(model_name: str) -> Any: """Loads a Keras model from file, handling custom loss function""" if not model_name.endswith('.net'): print('Warning: Unknown model type, ', model_name) inject_params(model_name) return load_keras().models.load_model(model_name)
python
def load_precise_model(model_name: str) -> Any: """Loads a Keras model from file, handling custom loss function""" if not model_name.endswith('.net'): print('Warning: Unknown model type, ', model_name) inject_params(model_name) return load_keras().models.load_model(model_name)
[ "def", "load_precise_model", "(", "model_name", ":", "str", ")", "->", "Any", ":", "if", "not", "model_name", ".", "endswith", "(", "'.net'", ")", ":", "print", "(", "'Warning: Unknown model type, '", ",", "model_name", ")", "inject_params", "(", "model_name", ...
Loads a Keras model from file, handling custom loss function
[ "Loads", "a", "Keras", "model", "from", "file", "handling", "custom", "loss", "function" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/model.py#L42-L48
train
MycroftAI/mycroft-precise
precise/model.py
create_model
def create_model(model_name: Optional[str], params: ModelParams) -> 'Sequential': """ Load or create a precise model Args: model_name: Name of model params: Parameters used to create the model Returns: model: Loaded Keras model """ if model_name and isfile(model_name): ...
python
def create_model(model_name: Optional[str], params: ModelParams) -> 'Sequential': """ Load or create a precise model Args: model_name: Name of model params: Parameters used to create the model Returns: model: Loaded Keras model """ if model_name and isfile(model_name): ...
[ "def", "create_model", "(", "model_name", ":", "Optional", "[", "str", "]", ",", "params", ":", "ModelParams", ")", "->", "'Sequential'", ":", "if", "model_name", "and", "isfile", "(", "model_name", ")", ":", "print", "(", "'Loading from '", "+", "model_name...
Load or create a precise model Args: model_name: Name of model params: Parameters used to create the model Returns: model: Loaded Keras model
[ "Load", "or", "create", "a", "precise", "model" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/model.py#L51-L83
train
MycroftAI/mycroft-precise
precise/scripts/train_generated.py
GeneratedTrainer.layer_with
def layer_with(self, sample: np.ndarray, value: int) -> np.ndarray: """Create an identical 2d array where the second row is filled with value""" b = np.full((2, len(sample)), value, dtype=float) b[0] = sample return b
python
def layer_with(self, sample: np.ndarray, value: int) -> np.ndarray: """Create an identical 2d array where the second row is filled with value""" b = np.full((2, len(sample)), value, dtype=float) b[0] = sample return b
[ "def", "layer_with", "(", "self", ",", "sample", ":", "np", ".", "ndarray", ",", "value", ":", "int", ")", "->", "np", ".", "ndarray", ":", "b", "=", "np", ".", "full", "(", "(", "2", ",", "len", "(", "sample", ")", ")", ",", "value", ",", "d...
Create an identical 2d array where the second row is filled with value
[ "Create", "an", "identical", "2d", "array", "where", "the", "second", "row", "is", "filled", "with", "value" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/scripts/train_generated.py#L116-L120
train
MycroftAI/mycroft-precise
precise/scripts/train_generated.py
GeneratedTrainer.generate_wakeword_pieces
def generate_wakeword_pieces(self, volume): """Generates chunks of audio that represent the wakeword stream""" while True: target = 1 if random() > 0.5 else 0 it = self.pos_files_it if target else self.neg_files_it sample_file = next(it) yield self.layer_w...
python
def generate_wakeword_pieces(self, volume): """Generates chunks of audio that represent the wakeword stream""" while True: target = 1 if random() > 0.5 else 0 it = self.pos_files_it if target else self.neg_files_it sample_file = next(it) yield self.layer_w...
[ "def", "generate_wakeword_pieces", "(", "self", ",", "volume", ")", ":", "while", "True", ":", "target", "=", "1", "if", "random", "(", ")", ">", "0.5", "else", "0", "it", "=", "self", ".", "pos_files_it", "if", "target", "else", "self", ".", "neg_file...
Generates chunks of audio that represent the wakeword stream
[ "Generates", "chunks", "of", "audio", "that", "represent", "the", "wakeword", "stream" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/scripts/train_generated.py#L122-L129
train
MycroftAI/mycroft-precise
precise/scripts/train_generated.py
GeneratedTrainer.chunk_audio_pieces
def chunk_audio_pieces(self, pieces, chunk_size): """Convert chunks of audio into a series of equally sized pieces""" left_over = np.array([]) for piece in pieces: if left_over.size == 0: combined = piece else: combined = np.concatenate([le...
python
def chunk_audio_pieces(self, pieces, chunk_size): """Convert chunks of audio into a series of equally sized pieces""" left_over = np.array([]) for piece in pieces: if left_over.size == 0: combined = piece else: combined = np.concatenate([le...
[ "def", "chunk_audio_pieces", "(", "self", ",", "pieces", ",", "chunk_size", ")", ":", "left_over", "=", "np", ".", "array", "(", "[", "]", ")", "for", "piece", "in", "pieces", ":", "if", "left_over", ".", "size", "==", "0", ":", "combined", "=", "pie...
Convert chunks of audio into a series of equally sized pieces
[ "Convert", "chunks", "of", "audio", "into", "a", "series", "of", "equally", "sized", "pieces" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/scripts/train_generated.py#L131-L141
train
MycroftAI/mycroft-precise
precise/scripts/train_generated.py
GeneratedTrainer.calc_volume
def calc_volume(self, sample: np.ndarray): """Find the RMS of the audio""" return sqrt(np.mean(np.square(sample)))
python
def calc_volume(self, sample: np.ndarray): """Find the RMS of the audio""" return sqrt(np.mean(np.square(sample)))
[ "def", "calc_volume", "(", "self", ",", "sample", ":", "np", ".", "ndarray", ")", ":", "return", "sqrt", "(", "np", ".", "mean", "(", "np", ".", "square", "(", "sample", ")", ")", ")" ]
Find the RMS of the audio
[ "Find", "the", "RMS", "of", "the", "audio" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/scripts/train_generated.py#L143-L145
train
MycroftAI/mycroft-precise
precise/scripts/train_generated.py
GeneratedTrainer.max_run_length
def max_run_length(x: np.ndarray, val: int): """Finds the maximum continuous length of the given value in the sequence""" if x.size == 0: return 0 else: y = np.array(x[1:] != x[:-1]) i = np.append(np.where(y), len(x) - 1) run_lengths = np.diff(np.a...
python
def max_run_length(x: np.ndarray, val: int): """Finds the maximum continuous length of the given value in the sequence""" if x.size == 0: return 0 else: y = np.array(x[1:] != x[:-1]) i = np.append(np.where(y), len(x) - 1) run_lengths = np.diff(np.a...
[ "def", "max_run_length", "(", "x", ":", "np", ".", "ndarray", ",", "val", ":", "int", ")", ":", "if", "x", ".", "size", "==", "0", ":", "return", "0", "else", ":", "y", "=", "np", ".", "array", "(", "x", "[", "1", ":", "]", "!=", "x", "[", ...
Finds the maximum continuous length of the given value in the sequence
[ "Finds", "the", "maximum", "continuous", "length", "of", "the", "given", "value", "in", "the", "sequence" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/scripts/train_generated.py#L156-L165
train
MycroftAI/mycroft-precise
precise/scripts/train_generated.py
GeneratedTrainer.samples_to_batches
def samples_to_batches(samples: Iterable, batch_size: int): """Chunk a series of network inputs and outputs into larger batches""" it = iter(samples) while True: with suppress(StopIteration): batch_in, batch_out = [], [] for i in range(batch_size): ...
python
def samples_to_batches(samples: Iterable, batch_size: int): """Chunk a series of network inputs and outputs into larger batches""" it = iter(samples) while True: with suppress(StopIteration): batch_in, batch_out = [], [] for i in range(batch_size): ...
[ "def", "samples_to_batches", "(", "samples", ":", "Iterable", ",", "batch_size", ":", "int", ")", ":", "it", "=", "iter", "(", "samples", ")", "while", "True", ":", "with", "suppress", "(", "StopIteration", ")", ":", "batch_in", ",", "batch_out", "=", "[...
Chunk a series of network inputs and outputs into larger batches
[ "Chunk", "a", "series", "of", "network", "inputs", "and", "outputs", "into", "larger", "batches" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/scripts/train_generated.py#L203-L215
train
MycroftAI/mycroft-precise
precise/scripts/train_generated.py
GeneratedTrainer.run
def run(self): """Train the model on randomly generated batches""" _, test_data = self.data.load(train=False, test=True) try: self.model.fit_generator( self.samples_to_batches(self.generate_samples(), self.args.batch_size), steps_per_epoch=self.args.steps_per_epoch, ...
python
def run(self): """Train the model on randomly generated batches""" _, test_data = self.data.load(train=False, test=True) try: self.model.fit_generator( self.samples_to_batches(self.generate_samples(), self.args.batch_size), steps_per_epoch=self.args.steps_per_epoch, ...
[ "def", "run", "(", "self", ")", ":", "_", ",", "test_data", "=", "self", ".", "data", ".", "load", "(", "train", "=", "False", ",", "test", "=", "True", ")", "try", ":", "self", ".", "model", ".", "fit_generator", "(", "self", ".", "samples_to_batc...
Train the model on randomly generated batches
[ "Train", "the", "model", "on", "randomly", "generated", "batches" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/scripts/train_generated.py#L226-L237
train
MycroftAI/mycroft-precise
precise/train_data.py
TrainData.from_both
def from_both(cls, tags_file: str, tags_folder: str, folder: str) -> 'TrainData': """Load data from both a database and a structured folder""" return cls.from_tags(tags_file, tags_folder) + cls.from_folder(folder)
python
def from_both(cls, tags_file: str, tags_folder: str, folder: str) -> 'TrainData': """Load data from both a database and a structured folder""" return cls.from_tags(tags_file, tags_folder) + cls.from_folder(folder)
[ "def", "from_both", "(", "cls", ",", "tags_file", ":", "str", ",", "tags_folder", ":", "str", ",", "folder", ":", "str", ")", "->", "'TrainData'", ":", "return", "cls", ".", "from_tags", "(", "tags_file", ",", "tags_folder", ")", "+", "cls", ".", "from...
Load data from both a database and a structured folder
[ "Load", "data", "from", "both", "a", "database", "and", "a", "structured", "folder" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/train_data.py#L113-L115
train
MycroftAI/mycroft-precise
precise/train_data.py
TrainData.load_inhibit
def load_inhibit(self, train=True, test=True) -> tuple: """Generate data with inhibitory inputs created from wake word samples""" def loader(kws: list, nkws: list): from precise.params import pr inputs = np.empty((0, pr.n_features, pr.feature_size)) outputs = np.zero...
python
def load_inhibit(self, train=True, test=True) -> tuple: """Generate data with inhibitory inputs created from wake word samples""" def loader(kws: list, nkws: list): from precise.params import pr inputs = np.empty((0, pr.n_features, pr.feature_size)) outputs = np.zero...
[ "def", "load_inhibit", "(", "self", ",", "train", "=", "True", ",", "test", "=", "True", ")", "->", "tuple", ":", "def", "loader", "(", "kws", ":", "list", ",", "nkws", ":", "list", ")", ":", "from", "precise", ".", "params", "import", "pr", "input...
Generate data with inhibitory inputs created from wake word samples
[ "Generate", "data", "with", "inhibitory", "inputs", "created", "from", "wake", "word", "samples" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/train_data.py#L126-L141
train
MycroftAI/mycroft-precise
precise/train_data.py
TrainData.parse_args
def parse_args(parser: ArgumentParser) -> Any: """Return parsed args from parser, adding options for train data inputs""" extra_usage = ''' :folder str Folder to load wav files from :-tf --tags-folder str {folder} Specify a different f...
python
def parse_args(parser: ArgumentParser) -> Any: """Return parsed args from parser, adding options for train data inputs""" extra_usage = ''' :folder str Folder to load wav files from :-tf --tags-folder str {folder} Specify a different f...
[ "def", "parse_args", "(", "parser", ":", "ArgumentParser", ")", "->", "Any", ":", "extra_usage", "=", "add_to_parser", "(", "parser", ",", "extra_usage", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "args", ".", "tags_folder", "=", "args", ".",...
Return parsed args from parser, adding options for train data inputs
[ "Return", "parsed", "args", "from", "parser", "adding", "options", "for", "train", "data", "inputs" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/train_data.py#L148-L167
train
MycroftAI/mycroft-precise
precise/vectorization.py
vectorize_raw
def vectorize_raw(audio: np.ndarray) -> np.ndarray: """Turns audio into feature vectors, without clipping for length""" if len(audio) == 0: raise InvalidAudio('Cannot vectorize empty audio!') return vectorizers[pr.vectorizer](audio)
python
def vectorize_raw(audio: np.ndarray) -> np.ndarray: """Turns audio into feature vectors, without clipping for length""" if len(audio) == 0: raise InvalidAudio('Cannot vectorize empty audio!') return vectorizers[pr.vectorizer](audio)
[ "def", "vectorize_raw", "(", "audio", ":", "np", ".", "ndarray", ")", "->", "np", ".", "ndarray", ":", "if", "len", "(", "audio", ")", "==", "0", ":", "raise", "InvalidAudio", "(", "'Cannot vectorize empty audio!'", ")", "return", "vectorizers", "[", "pr",...
Turns audio into feature vectors, without clipping for length
[ "Turns", "audio", "into", "feature", "vectors", "without", "clipping", "for", "length" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/vectorization.py#L42-L46
train
MycroftAI/mycroft-precise
precise/vectorization.py
vectorize_inhibit
def vectorize_inhibit(audio: np.ndarray) -> np.ndarray: """ Returns an array of inputs generated from the wake word audio that shouldn't cause an activation """ def samp(x): return int(pr.sample_rate * x) inputs = [] for offset in range(samp(inhibit_t), samp(inhibit_dist_t), samp(i...
python
def vectorize_inhibit(audio: np.ndarray) -> np.ndarray: """ Returns an array of inputs generated from the wake word audio that shouldn't cause an activation """ def samp(x): return int(pr.sample_rate * x) inputs = [] for offset in range(samp(inhibit_t), samp(inhibit_dist_t), samp(i...
[ "def", "vectorize_inhibit", "(", "audio", ":", "np", ".", "ndarray", ")", "->", "np", ".", "ndarray", ":", "def", "samp", "(", "x", ")", ":", "return", "int", "(", "pr", ".", "sample_rate", "*", "x", ")", "inputs", "=", "[", "]", "for", "offset", ...
Returns an array of inputs generated from the wake word audio that shouldn't cause an activation
[ "Returns", "an", "array", "of", "inputs", "generated", "from", "the", "wake", "word", "audio", "that", "shouldn", "t", "cause", "an", "activation" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/vectorization.py#L83-L97
train
MycroftAI/mycroft-precise
runner/precise_runner/runner.py
TriggerDetector.update
def update(self, prob): # type: (float) -> bool """Returns whether the new prediction caused an activation""" chunk_activated = prob > 1.0 - self.sensitivity if chunk_activated or self.activation < 0: self.activation += 1 has_activated = self.activation > self.tr...
python
def update(self, prob): # type: (float) -> bool """Returns whether the new prediction caused an activation""" chunk_activated = prob > 1.0 - self.sensitivity if chunk_activated or self.activation < 0: self.activation += 1 has_activated = self.activation > self.tr...
[ "def", "update", "(", "self", ",", "prob", ")", ":", "chunk_activated", "=", "prob", ">", "1.0", "-", "self", ".", "sensitivity", "if", "chunk_activated", "or", "self", ".", "activation", "<", "0", ":", "self", ".", "activation", "+=", "1", "has_activate...
Returns whether the new prediction caused an activation
[ "Returns", "whether", "the", "new", "prediction", "caused", "an", "activation" ]
e17cebdd171906dbd8a16e282d8a7966fba2eeba
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/runner/precise_runner/runner.py#L107-L122
train