code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
cmd = [b'INFO'] if section: cmd.append(section) return self._execute(cmd, format_callback=common.format_info_response)
def info(self, section=None)
The INFO command returns information and statistics about the server in a format that is simple to parse by computers and easy to read by humans. The optional parameter can be used to select a specific section of information: - server: General information about the Redis se...
6.757408
7.605115
0.888535
if self._clustering: raise exceptions.InvalidClusterCommand future = self._execute( [b'SELECT', ascii(index).encode('ascii')], b'OK') def on_selected(f): self._connection.database = index self.io_loop.add_future(future, on_selected) ...
def select(self, index=0)
Select the DB with having the specified zero-based numeric index. New connections always use DB ``0``. :param int index: The database to select :rtype: bool :raises: :exc:`~tredis.exceptions.RedisError` :raises: :exc:`~tredis.exceptions.InvalidClusterCommand`
11.217892
6.397498
1.753481
def format_response(value): seconds, micros = value return float(seconds) + (float(micros) / 1000000.0) return self._execute([b'TIME'], format_callback=format_response)
def time(self)
Retrieve the current time from the redis server. :rtype: float :raises: :exc:`~tredis.exceptions.RedisError`
7.091642
5.343321
1.327197
div = self.soup.find('div', attrs={'data-hover': True}) data = json.loads(div['data-hover']) show_name = data.get('title') return show_name
def get_show_name(self)
Get video show name from the website. It's located in the div with 'data-hover' attribute under the 'title' key. Returns: str: Video show name.
4.578104
3.379029
1.354858
req_url = self.base_url + url req_kwargs = kwargs req_kwargs['ca_certs'] = req_kwargs.get('ca_certs', self.certs) # have to do this because tornado's HTTP client doesn't # play nice with elasticsearch req_kwargs['allow_nonstandard_methods'] = req_kwargs.get( ...
def mk_req(self, url, **kwargs)
Helper function to create a tornado HTTPRequest object, kwargs get passed in to create the HTTPRequest object. See: http://tornado.readthedocs.org/en/latest/httpclient.html#request-objects
3.747761
3.488382
1.074355
params = urlencode(kwargs) url = '/' + '/'.join([x for x in args if x]) if params: url += '?' + params return url
def mk_url(self, *args, **kwargs)
Args get parameterized into base url: *(foo, bar, baz) -> /foo/bar/baz Kwargs get encoded and appended to base url: **{'hello':'world'} -> /foo/bar/baz?hello=world
3.742604
4.036644
0.927157
self.client.fetch( self.mk_req('', method='HEAD', **kwargs), callback = callback )
def ping(self, callback=None, **kwargs)
Ping request to check status of elasticsearch host
11.464684
14.040826
0.816525
self.client.fetch( self.mk_req('', method='GET', **kwargs), callback = callback )
def info(self, callback=None, **kwargs)
Get the basic info from the current cluster.
10.692335
10.284003
1.039706
method = 'PUT' if doc_id else 'POST' query_params = ('consistency', 'op_type', 'parent', 'refresh', 'replication', 'routing', 'timeout', 'timestamp', 'ttl', 'version', 'version_type', ) params = self._filter_params(query_params, params) url = ...
def create_doc(self, index, doc_type, body, doc_id = None, params = {}, callback = None, **kwargs )
Adds a typed JSON document in a specific index, making it searchable. Behind the scenes this method calls index(..., op_type='create') `<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-index_.html>`_ :arg index: The name of the index :arg doc_type: The type of ...
2.8779
3.326076
0.865254
query_params = ('scroll',) params = self._filter_params(query_params, params) url = self.mk_url(*['/_search/scroll'], **params) self.client.fetch( self.mk_req(url, method='GET', body=scroll_id, **kwargs), callback = callback )
def scroll(self, scroll_id, params={}, callback=None, **kwargs)
Scroll a search request created by specifying the scroll parameter. `<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-scroll.html>`_ :arg scroll_id: The scroll ID :arg scroll: Specify how long a consistent view of the index should be maintained fo...
4.848848
6.696106
0.724129
url = self.mk_url(*['_search', 'scroll', scroll_id]) self.client.fetch( self.mk_req(url, method='DELETE', body=body, **kwargs), callback = callback )
def clear_scroll(self, scroll_id = None, body = '', params = {}, callback = None, **kwargs )
Clear the scroll request created by specifying the scroll parameter to search. `<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-scroll.html>`_ :arg scroll_id: The scroll ID or a list of scroll IDs :arg body: A comma-separated list of scroll IDs to cl...
4.159431
7.107802
0.585192
url = self.mk_url(*['_bench', 'abort', name]) self.client.fetch( self.mk_req(url, method='POST', body=body, **kwargs), callback = callback )
def abort_benchmark(self, name=None, params={}, body='', callback=None, **kwargs)
Aborts a running benchmark. `<http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-benchmark.html>`_ :arg name: A benchmark name
5.115169
9.315955
0.549076
url = self.mk_url(*[index, doc_type, '_bench'], **params) self.client.fetch( self.mk_req(url, method='GET', **kwargs), callback = callback )
def list_benchmarks(self, index = None, doc_type = None, params = {}, cb = None, **kwargs )
View the progress of long-running benchmarks. `<http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-benchmark.html>`_ :arg index: A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices :arg doc_type: The name ...
4.185657
8.453567
0.495135
query_params = ('op_type', 'version', 'version_type',) params = self._filter_params(query_params, params) url = self.mk_url(*['_scripts', lang, script_id], **params) self.client.fetch( self.mk_req(url, method='PUT', body=body, **kwargs), callback = cal...
def put_script(self, lang, script_id, body, params={}, callback=None, **kwargs)
Create a script in given language with specified ID. `<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/modules-scripting.html>`_ :arg lang: Script language :arg script_id: Script ID :arg body: The document :arg op_type: Explicit operation type, default u'ind...
4.543485
5.621499
0.808234
url = self.mk_url(*['_search', 'template', temp_id]) self.client.fetch( self.mk_req(url, method='PUT', body=body, **kwargs), callback = callback )
def put_template(self, temp_id, body, params={}, callback=None, **kwargs)
Create a search template. `<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-template.html>`_ :arg temp_id: Template ID :arg body: The document
5.102282
7.339846
0.695148
url = self.mk_url(*['_search', 'template', temp_id]) self.client.fetch( self.mk_req(url, method='DELETE', **kwargs), callback = callback )
def delete_template(self, temp_id=None, params={}, callback=None, **kwargs)
Delete a search template. `<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-template.html>`_ :arg temp_id: Template ID
5.965765
8.40929
0.709425
exc_type, exc_value, tb = exec_info or sys.exc_info() reporter = ExceptionReporter(exc_type, exc_value, tb) html = reporter.get_traceback_html(**kwargs) mail_admins(title, 'html only', html_message=html)
def report(title='Unhandled Exception', exec_info=(), **kwargs)
Create a technical server error response. The last three arguments are the values returned from sys.exc_info() and friends. :param title: Title of error email :type title: str :param exec_info: exc_info from traceback
4.005532
3.981137
1.006128
default_template_engine = None if default_template_engine is None: template_loaders = [] frames = self.get_traceback_frames() for i, frame in enumerate(frames): if 'vars' in frame: frame_vars = [] for k, v in frame['vars'...
def get_traceback_data(self)
Return a dictionary containing traceback information.
3.209872
3.170302
1.012481
"Return HTML version of debug 500 HTTP error page." t = Template(TECHNICAL_500_TEMPLATE) c = self.get_traceback_data() c['kwargs'] = kwargs return t.render(Context(c))
def get_traceback_html(self, **kwargs)
Return HTML version of debug 500 HTTP error page.
8.380227
4.332736
1.934165
source = None if loader is not None and hasattr(loader, "get_source"): try: source = loader.get_source(module_name) except ImportError: pass if source is not None: source = source.splitlines() if source ...
def _get_lines_from_file(self, filename, lineno, context_lines, loader=None, module_name=None)
Returns context_lines before and after lineno from file. Returns (pre_context_lineno, pre_context, context_line, post_context).
2.415223
2.235894
1.080204
frames = [] tb = self.tb while tb is not None: # Support for __traceback_hide__ which is used by a few libraries # to hide internal frames. if tb.tb_frame.f_locals.get('__traceback_hide__'): tb = tb.tb_next continue ...
def get_traceback_frames(self)
Returns the traceback frames as a list
2.283003
2.29157
0.996261
import traceback frames = self.get_traceback_frames() tb = [(f['filename'], f['lineno'], f['function'], f['context_line']) for f in frames] list = ['Traceback (most recent call last):\n'] list += traceback.format_list(tb) list += traceback.format_exception_only(s...
def format_exception(self)
Return the same data as from traceback.format_exception.
2.69257
2.471887
1.089277
return self._execute([b'DEL'] + list(keys), len(keys))
def delete(self, *keys)
Removes the specified keys. A key is ignored if it does not exist. Returns :data:`True` if all keys are removed. .. note:: **Time complexity**: ``O(N)`` where ``N`` is the number of keys that will be removed. When a key to remove holds a value other than a string, the ...
10.605548
11.064139
0.958552
return self._execute( [b'EXPIRE', key, ascii(timeout).encode('ascii')], 1)
def expire(self, key, timeout)
Set a timeout on key. After the timeout has expired, the key will automatically be deleted. A key with an associated timeout is often said to be volatile in Redis terminology. The timeout is cleared only when the key is removed using the :meth:`~tredis.RedisClient.delete` method or over...
10.838802
11.589517
0.935225
return self._execute( [b'EXPIREAT', key, ascii(timestamp).encode('ascii')], 1)
def expireat(self, key, timestamp)
:meth:`~tredis.RedisClient.expireat` has the same effect and semantic as :meth:`~tredis.RedisClient.expire`, but instead of specifying the number of seconds representing the TTL (time to live), it takes an absolute Unix timestamp (seconds since January 1, 1970). Please for the specific ...
9.37288
11.412205
0.821303
command = [ b'MIGRATE', host, ascii(port).encode('ascii'), key, ascii(destination_db).encode('ascii'), ascii(timeout).encode('ascii') ] if copy is True: command.append(b'COPY') if replace is True: command.ap...
def migrate(self, host, port, key, destination_db, timeout, copy=False, replace=False)
Atomically transfer a key from a source Redis instance to a destination Redis instance. On success the key is deleted from the original instance and is guaranteed to exist in the target instance. The command is atomic and blocks the two instances for the time required to transfer the ke...
2.64002
2.90085
0.910085
return self._execute([b'MOVE', key, ascii(db).encode('ascii')], 1)
def move(self, key, db)
Move key from the currently selected database (see :meth:`~tredis.RedisClient.select`) to the specified destination database. When key already exists in the destination database, or it does not exist in the source database, it does nothing. It is possible to use :meth:`~tredis.RedisClien...
14.570382
16.218538
0.898378
return self._execute( [b'PEXPIRE', key, ascii(timeout).encode('ascii')], 1)
def pexpire(self, key, timeout)
This command works exactly like :meth:`~tredis.RedisClient.pexpire` but the time to live of the key is specified in milliseconds instead of seconds. .. note:: **Time complexity**: ``O(1)`` :param key: The key to set an expiration for :type key: :class:`str`, :class:...
8.365699
9.585336
0.87276
return self._execute( [b'PEXPIREAT', key, ascii(timestamp).encode('ascii')], 1)
def pexpireat(self, key, timestamp)
:meth:`~tredis.RedisClient.pexpireat` has the same effect and semantic as :meth:`~tredis.RedisClient.expireat`, but the Unix time at which the key will expire is specified in milliseconds instead of seconds. .. note:: **Time complexity**: ``O(1)`` :param key: The ke...
8.348555
10.576237
0.789369
return self._execute([b'RENAME', key, new_key], b'OK')
def rename(self, key, new_key)
Renames ``key`` to ``new_key``. It returns an error when the source and destination names are the same, or when ``key`` does not exist. If ``new_key`` already exists it is overwritten, when this happens :meth:`~tredis.RedisClient.rename` executes an implicit :meth:`~tredis.RedisClient.de...
8.39639
7.18464
1.168658
command = [b'RESTORE', key, ascii(ttl).encode('ascii'), value] if replace: command.append(b'REPLACE') return self._execute(command, b'OK')
def restore(self, key, ttl, value, replace=False)
Create a key associated with a value that is obtained by deserializing the provided serialized value (obtained via :meth:`~tredis.RedisClient.dump`). If ``ttl`` is ``0`` the key is created without any expire, otherwise the specified expire time (in milliseconds) is set. :meth:`...
4.244396
6.752908
0.628529
def format_response(value): return int(value[0]), value[1] command = [b'SCAN', ascii(cursor).encode('ascii')] if pattern: command += [b'MATCH', pattern] if count: command += [b'COUNT', ascii(count).encode('ascii')] retur...
def scan(self, cursor=0, pattern=None, count=None)
The :meth:`~tredis.RedisClient.scan` command and the closely related commands :meth:`~tredis.RedisClient.sscan`, :meth:`~tredis.RedisClient.hscan` and :meth:`~tredis.RedisClient.zscan` are used in order to incrementally iterate over a collection of elements. - :meth:`~tredis.Red...
4.254084
4.0567
1.048656
if order and order not in [b'ASC', b'DESC', 'ASC', 'DESC']: raise ValueError('invalid sort order "{}"'.format(order)) command = [b'SORT', key] if by: command += [b'BY', by] if external and isinstance(external, list): for entry in external: ...
def sort(self, key, by=None, external=None, offset=0, limit=None, order=None, alpha=False, store_as=None)
Returns or stores the elements contained in the list, set or sorted set at key. By default, sorting is numeric and elements are compared by their value interpreted as double precision floating point number. The ``external`` parameter is used to specify the `GET <http://redis.io/commands...
2.248456
2.277588
0.987209
command = [ b'WAIT', ascii(num_slaves).encode('ascii'), ascii(timeout).encode('ascii') ] return self._execute(command)
def wait(self, num_slaves, timeout=0)
his command blocks the current client until all the previous write commands are successfully transferred and acknowledged by at least the specified number of slaves. If the timeout, specified in milliseconds, is reached, the command returns even if the specified number of slaves were not...
4.787822
7.662745
0.624818
global profiled_thread_enabled, Thread, Process if os.path.isdir(profile_dir): _Profiler.profile_dir = profile_dir else: raise OSError('%s does not exist' % profile_dir) _Profiler.exception_callback = exception_callback Thread = threading.Thread = ProfiledThread Process = mu...
def enable_thread_profiling(profile_dir, exception_callback=None)
Monkey-patch the threading.Thread class with our own ProfiledThread. Any subsequent imports of threading.Thread will reference ProfiledThread instead.
3.623396
3.213048
1.127713
global logged_thread_enabled, Thread LoggedThread.exception_callback = exception_callback Thread = threading.Thread = LoggedThread logged_thread_enabled = True
def enable_thread_logging(exception_callback=None)
Monkey-patch the threading.Thread class with our own LoggedThread. Any subsequent imports of threading.Thread will reference LoggedThread instead.
9.038044
5.961925
1.515961
obj = Image.objects.get(pk=obj_id) if request.method == 'POST': return post(request, obj) elif request.method == 'PUT': getPutData(request) return put(request, obj) elif request.method == 'DELETE': getPutData(request) return delete(request, obj)
def image(request, obj_id)
Handles a request based on method and calls the appropriate function
2.387646
2.19325
1.088634
obj = Video.objects.get(pk=obj_id) if request.method == 'POST': return post(request, obj) elif request.method == 'PUT': getPutData(request) return put(request, obj) elif request.method == 'DELETE': getPutData(request) return delete(request, obj)
def video(request, obj_id)
Handles a request based on method and calls the appropriate function
2.370412
2.14985
1.102594
from aiida.common.exceptions import InvalidOperation from aiida.common import aiidalogger from aiida.backends.djsite.utils import get_dblogger_extra import ase, ase.io parserlogger = aiidalogger.getChild('aseparser') logger_extra = get_dblogger_extra(self._calc...
def parse_from_calc(self)
Parses the datafolder, stores results. This parser for this simple code does simply store in the DB a node representing the file of forces in real space
2.96757
3.000564
0.989004
return self._execute([b'HSET', key, field, value])
def hset(self, key, field, value)
Sets `field` in the hash stored at `key` to `value`. If `key` does not exist, a new key holding a hash is created. If `field` already exists in the hash, it is overwritten. .. note:: **Time complexity**: always ``O(1)`` :param key: The key of the hash :type key: :c...
6.160972
9.225142
0.667846
def format_response(value): return dict(zip(value[::2], value[1::2])) return self._execute( [b'HGETALL', key], format_callback=format_response)
def hgetall(self, key)
Returns all fields and values of the has stored at `key`. The underlying redis `HGETALL`_ command returns an array of pairs. This method converts that to a Python :class:`dict`. It will return an empty :class:`dict` when the key is not found. .. note:: **Time compl...
5.283552
4.877906
1.08316
if not value_dict: future = concurrent.TracebackFuture() future.set_result(False) else: command = [b'HMSET', key] command.extend(sum(value_dict.items(), ())) future = self._execute(command) return future
def hmset(self, key, value_dict)
Sets fields to values as in `value_dict` in the hash stored at `key`. Sets the specified fields to their respective values in the hash stored at `key`. This command overwrites any specified fields already existing in the hash. If `key` does not exist, a new key holding a hash is crea...
4.522087
6.331388
0.714233
def format_response(val_array): return dict(zip(fields, val_array)) command = [b'HMGET', key] command.extend(fields) return self._execute(command, format_callback=format_response)
def hmget(self, key, *fields)
Returns the values associated with the specified `fields` in a hash. For every ``field`` that does not exist in the hash, :data:`None` is returned. Because a non-existing keys are treated as empty hashes, calling :meth:`hmget` against a non-existing key will return a list of :data:`Non...
5.284399
4.977549
1.061647
if not fields: future = concurrent.TracebackFuture() future.set_result(0) else: future = self._execute([b'HDEL', key] + list(fields)) return future
def hdel(self, key, *fields)
Remove the specified fields from the hash stored at `key`. Specified fields that do not exist within this hash are ignored. If `key` does not exist, it is treated as an empty hash and this command returns zero. :param key: The key of the hash :type key: :class:`str`, :class:`by...
5.332295
6.011333
0.88704
return self._execute( [b'HINCRBY', key, field, increment], format_callback=int)
def hincrby(self, key, field, increment)
Increments the number stored at `field` in the hash stored at `key`. If `key` does not exist, a new key holding a hash is created. If `field` does not exist the value is set to ``0`` before the operation is performed. The range of values supported is limited to 64-bit signed integers....
8.982853
11.247029
0.798687
return self._execute( [b'HINCRBYFLOAT', key, field, increment], format_callback=float)
def hincrbyfloat(self, key, field, increment)
Increments the number stored at `field` in the hash stored at `key`. If the increment value is negative, the result is to have the hash field **decremented** instead of incremented. If the field does not exist, it is set to ``0`` before performing the operation. An error is returned i...
8.466564
11.450582
0.7394
return self._execute([b'HSETNX', key, field, value])
def hsetnx(self, key, field, value)
Sets `field` in the hash stored at `key` only if it does not exist. Sets `field` in the hash stored at `key` only if `field` does not yet exist. If `key` does not exist, a new key holding a hash is created. If `field` already exists, this operation has no effect. .. note:: ...
5.157293
8.233255
0.626398
query_params = ('master_timeout', 'wait_for_completion',) params = self._filter_params(query_params, params) url = self.mk_url(*['_snapshot', repository, snapshot], **params) self.client.fetch( self.mk_req(url, body=body, method='PUT', **kwargs), call...
def create_snapshot(self, repository, snapshot, body, params={}, callback=None, **kwargs)
Create a snapshot in repository `<http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/modules-snapshots.html>`_ :arg repository: A repository name :arg snapshot: A snapshot name :arg body: The snapshot definition :arg master_timeout: Explicit operation timeout f...
5.194761
5.906933
0.879434
query_params = ('master_timeout', 'timeout',) params = self._filter_params(query_params, params) url = self.mk_url(*['_snapshot', repository, '_verify'], **params) self.client.fetch( self.mk_req(url, body=body, method='POST', **kwargs), callback = cal...
def verify_repository(self, repository, master_timeout = 10, timeout = 10, body = '', params = {}, callback = None, **kwargs )
Returns a list of nodes where repository was successfully verified or an error message if verification process failed. `<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/modules-snapshots.html>`_ :arg repository: A repository name :arg master_timeout: Explicit opera...
4.295407
5.793148
0.741463
self.log('raising %s, traceback %s\n' % (error, traceback.format_exc())) raise error(message)
def raise_and_log_error(self, error, message)
Raise error, including message and original traceback. error: the error to raise message: the user-facing error message
7.422631
6.333169
1.172025
if self.client_ip: return self.client_ip try: client = os.environ.get('SSH_CONNECTION', os.environ.get('SSH_CLIENT')) self.client_ip = client.split()[0] self.logdebug('client_ip: %s\n' % self.client_ip) ...
def get_client_ip(self)
Return the client IP from the environment.
3.928571
3.535316
1.111236
keynames = rule.get('keynames') if not keynames: self.logdebug('no keynames requirement.\n') return True if not isinstance(keynames, list): keynames = [keynames] if self.keyname in keynames: self.logdebug('keyname "%s" matches ru...
def check_keyname(self, rule)
If a key name is specified, verify it is permitted.
2.493942
2.445703
1.019724
if not rule.get('from'): self.logdebug('no "from" requirement.\n') return True allow_from = rule.get('from') if not isinstance(allow_from, list): allow_from = [allow_from] client_ip = self.get_client_ip() if client_ip in allow_from:...
def check_client_ip(self, rule)
If a client IP is specified, verify it is permitted.
2.272764
2.266101
1.00294
if self.yamldocs: return loadfiles = [] if self.configfile: loadfiles.append(self.configfile) if self.configdir: # Gets list of all non-dotfile files from configdir. loadfiles.extend( [f for f in ...
def get_merged_config(self)
Get merged config file. Returns an open StringIO containing the merged config file.
3.05308
2.907691
1.050001
try: merged_configfile = self.get_merged_config() self.yamldocs = yaml.load(merged_configfile, Loader=Loader) # Strip out the top level 'None's we get from concatenation. # Functionally not required, but makes dumps cleaner. self.yamldocs = [...
def load(self)
Load our config, log and raise on error.
6.426164
5.71449
1.124538
yaml_content = self.get_merged_config() print('YAML Configuration\n%s\n' % yaml_content.read()) try: self.load() print('Python Configuration\n%s\n' % pretty(self.yamldocs)) except ConfigError: sys.stderr.write( 'config parse er...
def dump_config(self)
Pretty print the configuration dict to stdout.
7.86591
7.403892
1.062402
target.seek(0) contents = target.read() ssh_opts = 'no-port-forwarding' if keydata in contents: raise InstallError('key data already in file - refusing ' 'to double-install.\n') command = '%s --run' % self.authprogs_binary ...
def install_key_data(self, keydata, target)
Install the key data into the open file.
5.074862
5.041785
1.006561
# Make the directory containing the authorized_keys # file, if it doesn't exist. (Typically ~/.ssh). # Ignore errors; we'll fail shortly if we can't # create the authkeys file. try: os.makedirs(os.path.dirname(authorized_keys), 0o700) except OSError:...
def install_key(self, keyfile, authorized_keys)
Install a key into the authorized_keys file.
3.653895
3.845124
0.950267
self.logdebug('skipping scp processing - binary "%s" ' 'not in approved list.\n' % binary) return filepath = orig_list.pop() arguments = orig_list if '-f' in arguments: if not rule.get('allow_download'): self.logdebu...
def find_match_scp(self, rule): # pylint: disable-msg=R0911,R0912 orig_list = [] orig_list.extend(self.original_command_list) binary = orig_list.pop(0) allowed_binaries = ['scp', '/usr/bin/scp'] if binary not in allowed_binaries
Handle scp commands.
3.656192
3.535045
1.03427
command_string = rule['command'] command_list = command_string.split() self.logdebug('comparing "%s" to "%s"\n' % (command_list, self.original_command_list)) if rule.get('allow_trailing_args'): self.logdebug('allow_trailing_args is true - comp...
def find_match_command(self, rule)
Return a matching (possibly munged) command, if found in rule.
3.231039
3.14719
1.026642
self.load() for yamldoc in self.yamldocs: self.logdebug('\nchecking rule \n' % yamldoc) if not yamldoc: continue if not self.check_client_ip(yamldoc): # Rejected - Client IP does not match continue ...
def find_match(self)
Load the config and find a matching rule. returns the results of find_match_command, a dict of the command and (in the future) other metadata.
4.710373
4.410098
1.068088
if not self.original_command_string: raise SSHEnvironmentError('no SSH command found; ' 'interactive shell disallowed.') command_info = {'from': self.get_client_ip(), 'keyname': self.keyname, 'ssh...
def exec_command(self)
Glean the command to run and exec. On problems, sys.exit. This method should *never* return.
4.900278
4.843254
1.011774
crc = 0 for byte in value: crc = ((crc << 8) & 0xffff) ^ \ _CRC16_LOOKUP[((crc >> 8) ^ ord(byte)) & 0xff] return crc
def _py2_crc16(value)
Calculate the CRC for the value in Python 2 :param str value: The value to return for the CRC Checksum :rtype: int
2.559004
3.230232
0.792204
crc = 0 for byte in value: crc = ((crc << 8) & 0xffff) ^ _CRC16_LOOKUP[((crc >> 8) ^ byte) & 0xff] return crc
def _py3_crc16(value)
Calculate the CRC for the value in Python 3 :param bytes value: The value to return for the CRC Checksum :rtype: int
2.114916
2.672641
0.791321
match = re.match(cls._VALID_URL, url) return match
def validate_url(cls, url: str) -> Optional[Match[str]]
Check if the Extractor can handle the given url.
6.059884
5.332901
1.13632
with suppress_stdout(): with youtube_dl.YoutubeDL() as ydl: info_dict = ydl.extract_info(self.url, download=False) return info_dict
def get_info(self) -> dict
Get information about the videos from YoutubeDL package.
3.648248
2.423756
1.505204
# TODO: Is mutating the list okay, making copies is such a pain in the ass for entry in entries: entry.update(data)
def update_entries(entries: Entries, data: dict) -> None
Update each entry in the list with some data.
18.417429
12.692019
1.451103
'Returns extra data useful to the templates.' # XXX: clean this up from obsolete stuff ctx['site'] = site ctx['feeds'] = feeds = site.active_feeds.order_by('name') def get_mod_chk(k): mod, chk = ( (max(vals) if vals else None) for vals in ( filter(None, it.imap(op.attrgetter(k), feeds)) for k in ['la...
def get_extra_context(site, ctx)
Returns extra data useful to the templates.
5.311438
4.903645
1.083161
'''Adds a qtags property in every post object in a page. Use "qtags" instead of "tags" in templates to avoid unnecesary DB hits.''' tagd = dict() user_obj = None tag_obj = None tags = models.Tag.objects.extra( select=dict(post_id='{0}.{1}'.format( *it.imap( connection.ops.quote_name, ('feedjack_post_ta...
def get_posts_tags(subscribers, object_list, feed, tag_name)
Adds a qtags property in every post object in a page. Use "qtags" instead of "tags" in templates to avoid unnecesary DB hits.
2.773633
2.247397
1.234153
'Returns a paginator object and a requested page from it.' global _since_formats_vary if 'since' in criterias: since = criterias['since'] if since in _since_offsets: since = datetime.today() - timedelta(_since_offsets[since]) else: if _since_formats_vary: for fmt, substs in it.product( list(_since_f...
def get_page(site, page=1, **criterias)
Returns a paginator object and a requested page from it.
3.81158
3.567974
1.068276
'Returns the context dictionary for a page view.' try: page = int(request.GET.get('page', 1)) except ValueError: page = 1 feed, tag = criterias.get('feed'), criterias.get('tag') if feed: try: feed = models.Feed.objects.get(pk=feed) except ObjectDoesNotExist: raise Http404 page = get_page(site, page=page, **...
def page_context(request, site, **criterias)
Returns the context dictionary for a page view.
4.673291
4.626123
1.010196
command = [b'BITCOUNT', key] if start is not None and end is None: raise ValueError('Can not specify start without an end') elif start is None and end is not None: raise ValueError('Can not specify start without an end') elif start is not None and end is ...
def bitcount(self, key, start=None, end=None)
Count the number of set bits (population counting) in a string. By default all the bytes contained in the string are examined. It is possible to specify the counting operation only in an interval passing the additional arguments start and end. Like for the :meth:`~tredis.RedisClient.ge...
2.735326
3.317321
0.824559
if (operation not in _BITOPTS.keys() and operation not in _BITOPTS.values()): raise ValueError('Invalid operation value: {}'.format(operation)) elif operation in [b'~', b'NOT'] and len(keys) > 1: raise ValueError('NOT can only be used with 1 key') ...
def bitop(self, operation, dest_key, *keys)
Perform a bitwise operation between multiple keys (containing string values) and store the result in the destination key. The values for operation can be one of: - ``b'AND'`` - ``b'OR'`` - ``b'XOR'`` - ``b'NOT'`` - :data:`tredis.BITOP_AND` or...
3.333114
3.209139
1.038632
if 0 < bit > 1: raise ValueError('bit must be 1 or 0, not {}'.format(bit)) command = [b'BITPOS', key, ascii(bit)] if start is not None and end is None: raise ValueError('Can not specify start without an end') elif start is None and end is not None: ...
def bitpos(self, key, bit, start=None, end=None)
Return the position of the first bit set to ``1`` or ``0`` in a string. The position is returned, thinking of the string as an array of bits from left to right, where the first byte's most significant bit is at position 0, the second byte's most significant bit is at position ``...
2.588176
2.8512
0.90775
return self._execute([b'DECRBY', key, ascii(decrement)])
def decrby(self, key, decrement)
Decrements the number stored at key by decrement. If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. This operation is limited to 64 bit...
10.991037
15.466838
0.71062
return self._execute([b'GETBIT', key, ascii(offset)])
def getbit(self, key, offset)
Returns the bit value at offset in the string value stored at key. When offset is beyond the string length, the string is assumed to be a contiguous space with 0 bits. When key does not exist it is assumed to be an empty string, so offset is always out of range and the value is also ass...
14.846508
16.070694
0.923825
return self._execute([b'GETRANGE', key, ascii(start), ascii(end)])
def getrange(self, key, start, end)
Returns the bit value at offset in the string value stored at key. When offset is beyond the string length, the string is assumed to be a contiguous space with 0 bits. When key does not exist it is assumed to be an empty string, so offset is always out of range and the value is also ass...
9.519532
8.809539
1.080594
return self._execute([b'INCRBY', key, ascii(increment)])
def incrby(self, key, increment)
Increments the number stored at key by increment. If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. This operation is limited to 64 bit...
10.215824
14.589721
0.700207
return self._execute([b'INCRBYFLOAT', key, ascii(increment)])
def incrbyfloat(self, key, increment)
Increment the string representing a floating point number stored at key by the specified increment. If the key does not exist, it is set to 0 before performing the operation. An error is returned if one of the following conditions occur: - The key contains a value of the wrong type (n...
9.642692
11.453992
0.841863
command = [b'MSET'] for key, value in mapping.items(): command += [key, value] return self._execute(command, b'OK')
def mset(self, mapping)
Sets the given keys to their respective values. :meth:`~tredis.RedisClient.mset` replaces existing values with new values, just as regular :meth:`~tredis.RedisClient.set`. See :meth:`~tredis.RedisClient.msetnx` if you don't want to overwrite existing values. :meth:`~tredis.Redis...
3.998384
5.461204
0.732143
command = [b'MSETNX'] for key, value in mapping.items(): command += [key, value] return self._execute(command, 1)
def msetnx(self, mapping)
Sets the given keys to their respective values. :meth:`~tredis.RedisClient.msetnx` will not perform any operation at all even if just a single key already exists. Because of this semantic :meth:`~tredis.RedisClient.msetnx` can be used in order to set different keys representing differen...
3.534297
5.691072
0.621025
return self._execute( [b'PSETEX', key, ascii(milliseconds), value], b'OK')
def psetex(self, key, milliseconds, value)
:meth:`~tredis.RedisClient.psetex` works exactly like :meth:`~tredis.RedisClient.psetex` with the sole difference that the expire time is specified in milliseconds instead of seconds. .. versionadded:: 0.2.0 .. note:: **Time complexity**: ``O(1)`` :param key: The key to set ...
8.728875
9.782497
0.892295
command = [b'SET', key, value] if ex: command += [b'EX', ascii(ex).encode('ascii')] if px: command += [b'PX', ascii(px).encode('ascii')] if nx: command.append(b'NX') if xx: command.append(b'XX') return self._execute...
def set(self, key, value, ex=None, px=None, nx=False, xx=False)
Set key to hold the string value. If key already holds a value, it is overwritten, regardless of its type. Any previous time to live associated with the key is discarded on successful :meth:`~tredis.RedisClient.set` operation. If the value is not one of :class:`str`, :class:`bytes`, or ...
2.1531
2.525175
0.852654
if 0 < bit > 1: raise ValueError('bit must be 1 or 0, not {}'.format(bit)) return self._execute([b'SETBIT', key, ascii(offset), ascii(bit)])
def setbit(self, key, offset, bit)
Sets or clears the bit at offset in the string value stored at key. The bit is either set or cleared depending on value, which can be either 0 or 1. When key does not exist, a new string value is created. The string is grown to make sure it can hold a bit at offset. The offset argument ...
4.543918
6.29819
0.721464
return self._execute([b'SETEX', key, ascii(seconds), value], b'OK')
def setex(self, key, seconds, value)
Set key to hold the string value and set key to timeout after a given number of seconds. :meth:`~tredis.RedisClient.setex` is atomic, and can be reproduced by using :meth:`~tredis.RedisClient.set` and :meth:`~tredis.RedisClient.expire` inside an :meth:`~tredis.RedisClient.multi`...
8.744561
11.314326
0.772875
return self._execute([b'SETRANGE', key, ascii(offset), value])
def setrange(self, key, offset, value)
Overwrites part of the string stored at key, starting at the specified offset, for the entire length of value. If the offset is larger than the current length of the string at key, the string is padded with zero-bytes to make offset fit. Non-existing keys are considered as empty strings,...
9.845748
11.395674
0.86399
return ext.rsv1 and self.rsv1 \ or ext.rsv2 and self.rsv2 \ or ext.rsv3 and self.rsv3 \ or set(ext.names) & set(self.names) \ or set(ext.opcodes) & set(self.opcodes)
def conflicts(self, ext)
Check if the extension conflicts with an already accepted extension. This may be the case when the two extensions use the same reserved bits, or have the same name (when the same extension is negotiated multiple times with different parameters).
3.212818
2.885197
1.113552
for param in params.iterkeys(): if param not in self.defaults: return try: return dict(self.negotiate(name, params)) except (KeyError, ValueError, AssertionError): pass
def negotiate_safe(self, name, params)
`name` and `params` are sent in the HTTP request by the client. Check if the extension name is supported by this extension, and validate the parameters. Returns a dict with accepted parameters, or None if not accepted.
5.25734
5.236553
1.00397
if request.method == 'GET': return get(request) elif request.method == 'POST': return post(request) return HttpResponse('')
def index(request)
Handles a request based on method and calls the appropriate function
2.907556
2.206602
1.317662
res = Result() obj, created = UserPref.objects.get_or_create(user=request.user, defaults={'data': json.dumps(DefaultPrefs.copy())}) data = obj.json() data['subscriptions'] = [_.json() for _ in GallerySubscription.objects.filter(user=request.user)] res.append(data) return JsonResponse(res...
def get(request)
Gets the currently logged in users preferences :returns: json
5.67923
5.857101
0.969632
data = request.POST or json.loads(request.body)['body'] key = data.get('key', None) val = data.get('val', None) res = Result() if key is not None and val is not None: obj, created = UserPref.objects.get_or_create(user=request.user) if created: obj.data = json.dumps(D...
def post(request)
Sets a key to a value on the currently logged in users preferences :param key: Key to set :type key: str :param val: Value to set :type val: primitive :returns: json
3.252861
3.044836
1.068321
'Return best possible guess to post modification timestamp.' if parsed: return feedparser_ts(parsed) if not raw: return None # Parse weird timestamps that feedparser can't handle, e.g.: July 30, 2013 ts, val = None, raw.replace('_', ' ') if not ts: # coreutils' "date" parses virtually everything, but is more e...
def get_modified_date(parsed, raw)
Return best possible guess to post modification timestamp.
5.979344
4.970099
1.203063
'''Get real time routine. TODO support fuzzy matching. :param bus_name: the routine name of the bus. :param cur_station: current station, deaults to starting station of the routine. ''' routines = query_routines(bus_name) if not routines: return rv = []...
def query_realtime_routine(bus_name, cur_station=None)
Get real time routine. TODO support fuzzy matching. :param bus_name: the routine name of the bus. :param cur_station: current station, deaults to starting station of the routine.
5.038339
2.743701
1.83633
root = settings.MEDIA_ROOT.replace('\\', '/') if not root.endswith('/'): root += '/' return path.Path(root)
def getRoot()
Convenience to return the media root with forward slashes
6.146749
3.849048
1.596953
html = render_to_string('frog/video_email.html', { 'user': video.author, 'error': error, 'video': video, 'SITE_URL': FROG_SITE_URL, }) subject, from_email, to = 'Video Processing Finished{}'.format(error or ''), 'noreply@frogmediaserver.com', video.author.email text_...
def emailUser(video, error=None)
Emails the author of the video that it has finished processing
3.602225
3.430443
1.050076
xx = kwargs.pop('xx', False) nx = kwargs.pop('nx', False) ch = kwargs.pop('ch', False) incr = kwargs.pop('incr', False) command = [b'ZADD', key] if xx: command += ['XX'] if nx: command += ['NX'] if ch: command +...
def zadd(self, key, *members, **kwargs)
Adds all the specified members with the specified scores to the sorted set stored at key. It is possible to specify multiple score / member pairs. If a specified member is already a member of the sorted set, the score is updated and the element reinserted at the right position to ensure ...
2.057372
2.039702
1.008663
command = [b'ZRANGE', key, start, stop] if with_scores: command += ['WITHSCORES'] return self._execute(command)
def zrange(self, key, start=0, stop=-1, with_scores=False)
Returns the specified range of elements in the sorted set stored at key. The elements are considered to be ordered from the lowest to the highest score. Lexicographical order is used for elements with equal score. See :meth:`tredis.Client.zrevrange` when you need the elements ordered ...
3.182686
4.951239
0.642806
command = [b'ZRANGEBYSCORE', key, min_score, max_score] if with_scores: command += ['WITHSCORES'] if offset or count: command += ['LIMIT', offset, count] return self._execute(command)
def zrangebyscore(self, key, min_score, max_score, with_scores=False, offset=0, count=0)
Returns all the elements in the sorted set at key with a score between min and max (including elements with score equal to min or max). The elements are considered to be ordered from low to high scores. The elements having the same score are returned in lexicographical order (th...
2.33833
2.967061
0.788097
return self._execute([b'ZREM', key] + list(members))
def zrem(self, key, *members)
Removes the specified members from the sorted set stored at key. Non existing members are ignored. An error is returned when key exists and does not hold a sorted set. .. note:: **Time complexity**: ``O(M*log(N))`` with ``N`` being the number of elements in the sorted s...
5.335255
8.306454
0.642302
return self._execute([b'ZREMRANGEBYSCORE', key, min_score, max_score])
def zremrangebyscore(self, key, min_score, max_score)
Removes all elements in the sorted set stored at key with a score between min and max. Intervals are described in :meth:`~tredis.RedisClient.zrangebyscore`. Returns the number of elements removed. .. note:: **Time complexity**: ``O(log(N)+M)`` with ``N`` being the number o...
3.497702
4.202251
0.83234