INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Extract schema from view args and transform it using the pipeline of schema transformers | def _extract_transform_colander_schema(self, args):
"""
Extract schema from view args and transform it using
the pipeline of schema transformers
:param args:
Arguments from the view decorator.
:rtype: colander.MappingSchema()
:returns: View schema cloned and... |
Creates arguments and parses user input | def main():
"""Creates arguments and parses user input"""
parser = argparse.ArgumentParser(
description=_('Uploads selected file to working pomf.se clone'))
parser.add_argument('files', metavar='file', nargs='*', type=str,
help=_('Files to upload'))
parser.add_argument('-... |
Convert node schema into a parameter object. | def convert(self, schema_node, definition_handler):
"""
Convert node schema into a parameter object.
"""
converted = {
'name': schema_node.name,
'in': self._in,
'required': schema_node.required
}
if schema_node.description:
... |
: param config: Pyramid configurator object: param api_path: where to expose swagger JSON definition view: param permission: pyramid permission for those views: param route_factory: factory for context object for those routes: param kwargs: kwargs that will be passed to CorniceSwagger s generate () | def cornice_enable_openapi_view(
config,
api_path='/api-explorer/swagger.json',
permission=NO_PERMISSION_REQUIRED,
route_factory=None, **kwargs):
"""
:param config:
Pyramid configurator object
:param api_path:
where to expose swagger JSON definition view
:... |
: param config: Pyramid configurator object: param api_explorer_path: where to expose Swagger UI interface view: param permission: pyramid permission for those views: param route_factory: factory for context object for those routes | def cornice_enable_openapi_explorer(
config,
api_explorer_path='/api-explorer',
permission=NO_PERMISSION_REQUIRED,
route_factory=None,
**kwargs):
"""
:param config:
Pyramid configurator object
:param api_explorer_path:
where to expose Swagger UI interf... |
Remove the tabs to spaces and remove the extra spaces/ tabs that are in front of the text in docstrings. | def trim(docstring):
"""
Remove the tabs to spaces, and remove the extra spaces / tabs that are in
front of the text in docstrings.
Implementation taken from http://www.python.org/dev/peps/pep-0257/
"""
if not docstring:
return ''
# Convert tabs to spaces (following the normal Pytho... |
Merge b into a recursively without overwriting values. | def merge_dicts(base, changes):
"""Merge b into a recursively, without overwriting values.
:param base: the dict that will be altered.
:param changes: changes to update base.
"""
for k, v in changes.items():
if isinstance(v, dict):
merge_dicts(base.setdefault(k, {}), v)
... |
Create a viewset method for the provided transition_name | def get_transition_viewset_method(transition_name, **kwargs):
'''
Create a viewset method for the provided `transition_name`
'''
@detail_route(methods=['post'], **kwargs)
def inner_func(self, request, pk=None, **kwargs):
object = self.get_object()
transition_method = getattr(object, ... |
Find all transitions defined on model then create a corresponding viewset action method for each and apply it to Mixin. Finally return Mixin | def get_viewset_transition_action_mixin(model, **kwargs):
'''
Find all transitions defined on `model`, then create a corresponding
viewset action method for each and apply it to `Mixin`. Finally, return
`Mixin`
'''
instance = model()
class Mixin(object):
save_after_transition = True... |
Refresh the project from the original cookiecutter template. | def fresh_cookies(ctx, mold=''):
"""Refresh the project from the original cookiecutter template."""
mold = mold or "https://github.com/Springerle/py-generic-project.git" # TODO: URL from config
tmpdir = os.path.join(tempfile.gettempdir(), "cc-upgrade-pygments-markdown-lexer")
if os.path.isdir('.git'):... |
Perform continuous integration tasks. | def ci(ctx):
"""Perform continuous integration tasks."""
opts = ['']
# 'tox' makes no sense in Travis
if os.environ.get('TRAVIS', '').lower() == 'true':
opts += ['test.pytest']
else:
opts += ['test.tox']
ctx.run("invoke --echo --pty clean --all build --docs check --reports{}".f... |
Return project s metadata as a dict. | def _build_metadata(): # pylint: disable=too-many-locals, too-many-branches
"Return project's metadata as a dict."
# Handle metadata in package source
expected_keys = ('url', 'version', 'license', 'author', 'author_email', 'long_description', 'keywords')
metadata = {}
with io.open(srcfile('src', pac... |
Generate a number in the range [ 0 num_buckets ). | def py_hash(key, num_buckets):
"""Generate a number in the range [0, num_buckets).
Args:
key (int): The key to hash.
num_buckets (int): Number of buckets to use.
Returns:
The bucket number `key` computes to.
Raises:
ValueError: If `num_buckets` is not a positive number... |
Initializer for Sphinx extension API. | def setup(app):
""" Initializer for Sphinx extension API.
See http://www.sphinx-doc.org/en/stable/extdev/index.html#dev-extensions.
"""
lexer = MarkdownLexer()
for alias in lexer.aliases:
app.add_lexer(alias, lexer)
return dict(version=__version__) |
Return a dict of stats. | def load(self):
"""Return a dict of stats."""
ret = {}
# Read the mdstat file
with open(self.get_path(), 'r') as f:
# lines is a list of line (with \n)
lines = f.readlines()
# First line: get the personalities
# The "Personalities" line tells you... |
Return a list of personalities readed from the input line. | def get_personalities(self, line):
"""Return a list of personalities readed from the input line."""
return [split('\W+', i)[1] for i in line.split(':')[1].split(' ') if i.startswith('[')] |
Return a dict of arrays. | def get_arrays(self, lines, personalities=[]):
"""Return a dict of arrays."""
ret = {}
i = 0
while i < len(lines):
try:
# First array line: get the md device
md_device = self.get_md_device_name(lines[i])
except IndexError:
... |
Return a dict of md device define in the line. | def get_md_device(self, line, personalities=[]):
"""Return a dict of md device define in the line."""
ret = {}
splitted = split('\W+', line)
# Raid status
# Active or 'started'. An inactive array is usually faulty.
# Stopped arrays aren't visible here.
ret['statu... |
Return a dict of md status define in the line. | def get_md_status(self, line):
"""Return a dict of md status define in the line."""
ret = {}
splitted = split('\W+', line)
if len(splitted) < 7:
ret['available'] = None
ret['used'] = None
ret['config'] = None
else:
# The final 2 en... |
Return a dict of components in the line. | def get_components(self, line, with_type=True):
"""Return a dict of components in the line.
key: device name (ex: 'sdc1')
value: device role number
"""
ret = {}
# Ignore (F) (see test 08)
line2 = reduce(lambda x, y: x + y, split('\(.+\)', line))
if with_... |
Register signal receivers which send events. | def register_receivers(app, config):
"""Register signal receivers which send events."""
for event_name, event_config in config.items():
event_builders = [
obj_or_import_string(func)
for func in event_config.get('event_builders', [])
]
signal = obj_or_import_strin... |
: param query: | def check(self, query):
"""
:param query:
"""
if query.get_type() != Keyword.DELETE:
return Ok(True)
return Err("Delete queries are forbidden.") |
Returns True if state was successfully changed from idle to scheduled. | def set_scheduled(self):
"""
Returns True if state was successfully changed from idle to scheduled.
"""
with self._idle_lock:
if self._idle:
self._idle = False
return True
return False |
Get statistics. | def post(self, **kwargs):
"""Get statistics."""
data = request.get_json(force=False)
if data is None:
data = {}
result = {}
for query_name, config in data.items():
if config is None or not isinstance(config, dict) \
or (set(config.keys(... |
: param query: | def check(self, query):
"""
:param query:
"""
if query.get_type() not in {Keyword.SELECT, Keyword.DELETE}:
# Only select and delete queries deal with time durations
# All others are not affected by this rule. Bailing out.
return Ok(True)
datap... |
Search for the oldest event timestamp. | def _get_oldest_event_timestamp(self):
"""Search for the oldest event timestamp."""
# Retrieve the oldest event in order to start aggregation
# from there
query_events = Search(
using=self.client,
index=self.event_index
)[0:1].sort(
{'timestamp... |
Get last aggregation date. | def get_bookmark(self):
"""Get last aggregation date."""
if not Index(self.aggregation_alias,
using=self.client).exists():
if not Index(self.event_index,
using=self.client).exists():
return datetime.date.today()
return... |
Set bookmark for starting next aggregation. | def set_bookmark(self):
"""Set bookmark for starting next aggregation."""
def _success_date():
bookmark = {
'date': self.new_bookmark or datetime.datetime.utcnow().
strftime(self.doc_id_suffix)
}
yield dict(_index=self.last_index_writt... |
Format range filter datetime to the closest aggregation interval. | def _format_range_dt(self, d):
"""Format range filter datetime to the closest aggregation interval."""
if not isinstance(d, six.string_types):
d = d.isoformat()
return '{0}||/{1}'.format(
d, self.dt_rounding_map[self.aggregation_interval]) |
Aggregate and return dictionary to be indexed in ES. | def agg_iter(self, lower_limit=None, upper_limit=None):
"""Aggregate and return dictionary to be indexed in ES."""
lower_limit = lower_limit or self.get_bookmark().isoformat()
upper_limit = upper_limit or (
datetime.datetime.utcnow().replace(microsecond=0).isoformat())
aggreg... |
Calculate statistics aggregations. | def run(self, start_date=None, end_date=None, update_bookmark=True):
"""Calculate statistics aggregations."""
# If no events have been indexed there is nothing to aggregate
if not Index(self.event_index, using=self.client).exists():
return
lower_limit = start_date or self.get... |
List the aggregation s bookmarks. | def list_bookmarks(self, start_date=None, end_date=None, limit=None):
"""List the aggregation's bookmarks."""
query = Search(
using=self.client,
index=self.aggregation_alias,
doc_type=self.bookmark_doc_type
).sort({'date': {'order': 'desc'}})
range_ar... |
Delete aggregation documents. | def delete(self, start_date=None, end_date=None):
"""Delete aggregation documents."""
aggs_query = Search(
using=self.client,
index=self.aggregation_alias,
doc_type=self.aggregation_doc_type
).extra(_source=False)
range_args = {}
if start_date... |
Extract the data resolution of a query in seconds E. g. group by time ( 99s ) = > 99 | def parse(self, group_by_stmt):
"""
Extract the data resolution of a query in seconds
E.g. "group by time(99s)" => 99
:param group_by_stmt: A raw InfluxDB group by statement
"""
if not group_by_stmt:
return Resolution.MAX_RESOLUTION
m = self.GROUP_BY... |
Return value on success or raise exception on failure. | def get(self, timeout=None):
"""
Return value on success, or raise exception on failure.
"""
result = None
try:
result = self._result.get(True, timeout=timeout)
except Empty:
raise Timeout()
if isinstance(result, Failure):
six.... |
Process stats events. | def _events_process(event_types=None, eager=False):
"""Process stats events."""
event_types = event_types or list(current_stats.enabled_events)
if eager:
process_events.apply((event_types,), throw=True)
click.secho('Events processed successfully.', fg='green')
else:
process_event... |
Process stats aggregations. | def _aggregations_process(aggregation_types=None,
start_date=None, end_date=None,
update_bookmark=False, eager=False):
"""Process stats aggregations."""
aggregation_types = (aggregation_types or
list(current_stats.enabled_aggregations)... |
Delete computed aggregations. | def _aggregations_delete(aggregation_types=None,
start_date=None, end_date=None):
"""Delete computed aggregations."""
aggregation_types = (aggregation_types or
list(current_stats.enabled_aggregations))
for a in aggregation_types:
aggr_cfg = current_s... |
List aggregation bookmarks. | def _aggregations_list_bookmarks(aggregation_types=None,
start_date=None, end_date=None, limit=None):
"""List aggregation bookmarks."""
aggregation_types = (aggregation_types or
list(current_stats.enabled_aggregations))
for a in aggregation_types:
... |
Load events configuration. | def _events_config(self):
"""Load events configuration."""
# import iter_entry_points here so that it can be mocked in tests
result = {}
for ep in iter_entry_points(
group=self.entry_point_group_events):
for cfg in ep.load()():
if cfg['event_ty... |
Load aggregation configurations. | def _aggregations_config(self):
"""Load aggregation configurations."""
result = {}
for ep in iter_entry_points(
group=self.entry_point_group_aggs):
for cfg in ep.load()():
if cfg['aggregation_name'] not in self.enabled_aggregations:
... |
Load queries configuration. | def _queries_config(self):
"""Load queries configuration."""
result = {}
for ep in iter_entry_points(group=self.entry_point_group_queries):
for cfg in ep.load()():
if cfg['query_name'] not in self.enabled_queries:
continue
elif cfg[... |
Publish events. | def publish(self, event_type, events):
"""Publish events."""
assert event_type in self.events
current_queues.queues['stats-{}'.format(event_type)].publish(events) |
Comsume all pending events. | def consume(self, event_type, no_ack=True, payload=True):
"""Comsume all pending events."""
assert event_type in self.events
return current_queues.queues['stats-{}'.format(event_type)].consume(
payload=payload) |
Flask application initialization. | def init_app(self, app,
entry_point_group_events='invenio_stats.events',
entry_point_group_aggs='invenio_stats.aggregations',
entry_point_group_queries='invenio_stats.queries'):
"""Flask application initialization."""
self.init_config(app)
stat... |
Send a message to this actor. Asynchronous fire - and - forget. | def tell(self, message, sender=no_sender):
""" Send a message to this actor. Asynchronous fire-and-forget.
:param message: The message to send.
:type message: Any
:param sender: The sender of the message. If provided it will be made
available to the receiving actor via the ... |
Get the anonymization salt based on the event timestamp s day. | def get_anonymization_salt(ts):
"""Get the anonymization salt based on the event timestamp's day."""
salt_key = 'stats:salt:{}'.format(ts.date().isoformat())
salt = current_cache.get(salt_key)
if not salt:
salt_bytes = os.urandom(32)
salt = b64encode(salt_bytes).decode('utf-8')
c... |
Lookup country for IP address. | def get_geoip(ip):
"""Lookup country for IP address."""
reader = geolite2.reader()
ip_data = reader.get(ip) or {}
return ip_data.get('country', {}).get('iso_code') |
User information. | def get_user():
"""User information.
.. note::
**Privacy note** A users IP address, user agent string, and user id
(if logged in) is sent to a message queue, where it is stored for about
5 minutes. The information is used to:
- Detect robot visits from the user agent string.
... |
Default permission factory. | def default_permission_factory(query_name, params):
"""Default permission factory.
It enables by default the statistics if they don't have a dedicated
permission factory.
"""
from invenio_stats import current_stats
if current_stats.queries[query_name].permission_factory is None:
return ... |
Load settings from default config and optionally overwrite with config file and commandline parameters ( in that order ). | def load_config():
"""
Load settings from default config and optionally
overwrite with config file and commandline parameters
(in that order).
"""
# We start with the default config
config = flatten(default_config.DEFAULT_CONFIG)
# Read commandline arguments
cli_config = flatten(par... |
Read settings from file: param configfile: | def parse_configfile(configfile):
"""
Read settings from file
:param configfile:
"""
with open(configfile) as f:
try:
return yaml.safe_load(f)
except Exception as e:
logging.fatal("Could not load default config file: %s", e)
exit(-1) |
Register elasticsearch templates for events. | def register_templates():
"""Register elasticsearch templates for events."""
event_templates = [current_stats._events_config[e]
['templates']
for e in
current_stats._events_config]
aggregation_templates = [current_stats._aggregations_confi... |
: param query: | def check(self, query):
"""
:param query:
"""
if query.get_type() in {Keyword.LIST, Keyword.DROP}:
series = query.series_stmt
else:
series = query.from_stmt
if len(series) >= self.min_series_name_length:
return Ok(True)
return... |
Index statistics events. | def process_events(event_types):
"""Index statistics events."""
results = []
for e in event_types:
processor = current_stats.events[e].processor_class(
**current_stats.events[e].processor_config)
results.append((e, processor.run()))
return results |
Aggregate indexed events. | def aggregate_events(aggregations, start_date=None, end_date=None,
update_bookmark=True):
"""Aggregate indexed events."""
start_date = dateutil_parse(start_date) if start_date else None
end_date = dateutil_parse(end_date) if end_date else None
results = []
for a in aggregations:... |
Send a message to actor and return a: class: Future holding a possible reply. | def ask(actor, message):
"""
Send a message to `actor` and return a :class:`Future` holding a possible
reply.
To receive a result, the actor MUST send a reply to `sender`.
:param actor:
:type actor: :class:`ActorRef`.
:param message:
:type message: :type: Any
:return: A future ho... |
Get a list of all queries ( q =... parameters ) from an URL parameter string: param parameters: The url parameter list | def get_queries(parameters):
"""
Get a list of all queries (q=... parameters) from an URL parameter string
:param parameters: The url parameter list
"""
parsed_params = urlparse.parse_qs(parameters)
if 'q' not in parsed_params:
return []
queries = pars... |
Run the actual request | def _handle_request(self, scheme, netloc, path, headers, body=None, method="GET"):
"""
Run the actual request
"""
backend_url = "{}://{}{}".format(scheme, netloc, path)
try:
response = self.http_request.request(backend_url, method=method, body=body, headers=dict(heade... |
Send and log plain text error reply.: param code:: param message: | def send_error(self, code, message=None):
"""
Send and log plain text error reply.
:param code:
:param message:
"""
message = message.strip()
self.log_error("code %d, message %s", code, message)
self.send_response(code)
self.send_header("Content-Ty... |
: type result: HTTPResponse | def _return_response(self, response):
"""
:type result: HTTPResponse
"""
self.filter_headers(response.msg)
if "content-length" in response.msg:
del response.msg["content-length"]
self.send_response(response.status, response.reason)
for header_key, hea... |
Preprocess an event by anonymizing user information. | def anonymize_user(doc):
"""Preprocess an event by anonymizing user information.
The anonymization is done by removing fields that can uniquely identify a
user, such as the user's ID, session ID, IP address and User Agent, and
hashing them to produce a ``visitor_id`` and ``unique_session_id``. To
f... |
Generate event id optimized for ES. | def hash_id(iso_timestamp, msg):
"""Generate event id, optimized for ES."""
return '{0}-{1}'.format(iso_timestamp,
hashlib.sha1(
msg.get('unique_id').encode('utf-8') +
str(msg.get('visitor_id')).
... |
Iterator. | def actionsiter(self):
"""Iterator."""
for msg in self.queue.consume():
try:
for preproc in self.preprocessors:
msg = preproc(msg)
if msg is None:
break
if msg is None:
continu... |
Process events queue. | def run(self):
"""Process events queue."""
return elasticsearch.helpers.bulk(
self.client,
self.actionsiter(),
stats_only=True,
chunk_size=50
) |
num_datapoints = min ( duration/ resolution limit ) | def parse(duration_seconds, resolution_seconds=Resolution.MAX_RESOLUTION, limit=None):
"""
num_datapoints = min(duration/resolution, limit)
:param duration_seconds: Time duration (in seconds) for which datapoints should be returned
:param resolution_seconds: Time interval (in seconds) b... |
Write one data point for each series name to initialize the series: param num_series: Number of different series names to create: param batch_size: Number of series to create at the same time: return: | def create_series(self, num_series, batch_size=5000):
"""
Write one data point for each series name to initialize the series
:param num_series: Number of different series names to create
:param batch_size: Number of series to create at the same time
:return:
"""
d... |
Create sample datapoints between two dates with the given resolution ( in seconds ): param series_name:: param start_date:: param end_date:: param resolution:: param batch_size: | def write_points(self, series_name, start_date, end_date, resolution=10, batch_size=5000):
"""
Create sample datapoints between two dates with the given resolution (in seconds)
:param series_name:
:param start_date:
:param end_date:
:param resolution:
:param batch... |
Register sample events. | def register_events():
"""Register sample events."""
return [
dict(
event_type='file-download',
templates='invenio_stats.contrib.file_download',
processor_class=EventsIndexer,
processor_config=dict(
preprocessors=[
flag_... |
Register sample aggregations. | def register_aggregations():
"""Register sample aggregations."""
return [dict(
aggregation_name='file-download-agg',
templates='invenio_stats.contrib.aggregations.aggr_file_download',
aggregator_class=StatAggregator,
aggregator_config=dict(
client=current_search_clien... |
Register queries. | def register_queries():
"""Register queries."""
return [
dict(
query_name='bucket-file-download-histogram',
query_class=ESDateHistogramQuery,
query_config=dict(
index='stats-file-download',
doc_type='file-download-day-aggregation',
... |
: param query: | def check(self, query):
"""
:param query:
"""
if query.get_type() not in {Keyword.SELECT}:
# Bailing out for non select queries
return Ok(True)
if query.get_resolution() > 0:
return Ok(True)
return Err("Group by statements need a posi... |
Index statistics events. | def declare_queues():
"""Index statistics events."""
return [dict(name='stats-{0}'.format(event['event_type']),
exchange=current_stats.exchange)
for event in current_stats._events_config.values()] |
Parse a raw query string into fields: param raw_query_string: Raw InfluxDB query string | def parse(self, raw_query_string):
"""
Parse a raw query string into fields
:param raw_query_string: Raw InfluxDB query string
"""
self._reset()
if not isinstance(raw_query_string, basestring):
return None
query_string = self._cleanup(raw_query_stri... |
Analyze query tokens and create an InfluxDBStatement from them Return None on error: param tokens: A list of InfluxDB query tokens | def create_query_object(self, tokens):
"""
Analyze query tokens and create an InfluxDBStatement from them
Return None on error
:param tokens: A list of InfluxDB query tokens
"""
try:
query_type = tokens['type']
return getattr(self, 'create_%s_query... |
Parse tokens of select query: param tokens: A list of InfluxDB query tokens | def create_select_query(self, tokens):
"""
Parse tokens of select query
:param tokens: A list of InfluxDB query tokens
"""
if not tokens[Keyword.SELECT]:
return None
if not tokens[Keyword.FROM]:
return None
return SelectQuery(
... |
Parse tokens of list query: param tokens: A list of InfluxDB query tokens | def create_list_query(self, tokens):
"""
Parse tokens of list query
:param tokens: A list of InfluxDB query tokens
"""
if not tokens[Keyword.SERIES]:
# A list series keyword is allowed
# without a series name or regex
tokens[Keyword.SERIES] = '... |
Parse tokens of drop query: param tokens: A list of InfluxDB query tokens | def create_drop_query(self, tokens):
"""
Parse tokens of drop query
:param tokens: A list of InfluxDB query tokens
"""
if not tokens[Keyword.SERIES]:
return None
return DropQuery(self.parse_keyword(Keyword.SERIES, tokens)) |
Parse tokens of delete query: param tokens: A list of InfluxDB query tokens | def create_delete_query(self, tokens):
"""
Parse tokens of delete query
:param tokens: A list of InfluxDB query tokens
"""
# From keyword is required
if not tokens[Keyword.FROM]:
return None
where_stmt = self.parse_keyword(Keyword.WHERE, tokens)
... |
Parse the date range for the query | def _parse_time(self, tokens):
"""
Parse the date range for the query
E.g. WHERE time > now() - 48h AND time < now() - 24h
would result in DateRange(datetime_start, datetime_end)
where
datetime_start would be parsed from now() - 48h
and
datetime_end would... |
Parse resolution from the GROUP BY statement. E. g. GROUP BY time ( 10s ) would mean a 10 second resolution: param tokens:: return: | def _parse_resolution(self, tokens):
"""
Parse resolution from the GROUP BY statement.
E.g. GROUP BY time(10s) would mean a 10 second resolution
:param tokens:
:return:
"""
return self.resolution_parser.parse(self.parse_keyword(Keyword.GROUP_BY, tokens)) |
Parse the number of datapoints of a query. This can be calculated from the given duration and resolution of the query. E. g. if the query has a duation of 2 * 60 * 60 = 7200 seconds and a resolution of 10 seconds then the number of datapoints would be 7200/ 10 = > 7200 datapoints. | def _parse_datapoints(self, parsed_duration, parsed_resolution, limit):
"""
Parse the number of datapoints of a query.
This can be calculated from the given duration and resolution of the query.
E.g. if the query has a duation of 2*60*60 = 7200 seconds and a resolution of 10 seconds
... |
: param query: | def check(self, query):
"""
:param query:
"""
if query.get_type() not in {Keyword.SELECT}:
# Only select queries need to be checked here
# All others are not affected by this rule. Bailing out.
return Ok(True)
earliest_date = query.get_earlies... |
Extract date from string if necessary. | def extract_date(self, date):
"""Extract date from string if necessary.
:returns: the extracted date.
"""
if isinstance(date, six.string_types):
try:
date = dateutil.parser.parse(date)
except ValueError:
raise ValueError(
... |
Validate query arguments. | def validate_arguments(self, interval, start_date, end_date, **kwargs):
"""Validate query arguments."""
if interval not in self.allowed_intervals:
raise InvalidRequestInputError(
'Invalid aggregation time interval for statistic {}.'
).format(self.query_name)
... |
Build the elasticsearch query. | def build_query(self, interval, start_date, end_date, **kwargs):
"""Build the elasticsearch query."""
agg_query = Search(using=self.client,
index=self.index,
doc_type=self.doc_type)[0:0]
if start_date is not None or end_date is not None:
... |
Build the result using the query result. | def process_query_result(self, query_result, interval,
start_date, end_date):
"""Build the result using the query result."""
def build_buckets(agg):
"""Build recursively result buckets."""
bucket_result = dict(
key=agg['key'],
... |
Validate query arguments. | def validate_arguments(self, start_date, end_date, **kwargs):
"""Validate query arguments."""
if set(kwargs) < set(self.required_filters):
raise InvalidRequestInputError(
'Missing one of the required parameters {0} in '
'query {1}'.format(set(self.required_fil... |
Build the elasticsearch query. | def build_query(self, start_date, end_date, **kwargs):
"""Build the elasticsearch query."""
agg_query = Search(using=self.client,
index=self.index,
doc_type=self.doc_type)[0:0]
if start_date is not None or end_date is not None:
ti... |
Build the result using the query result. | def process_query_result(self, query_result, start_date, end_date):
"""Build the result using the query result."""
def build_buckets(agg, fields, bucket_result):
"""Build recursively result buckets."""
# Add metric results for current bucket
for metric in self.metric_... |
Run the query. | def run(self, start_date=None, end_date=None, **kwargs):
"""Run the query."""
start_date = self.extract_date(start_date) if start_date else None
end_date = self.extract_date(end_date) if end_date else None
self.validate_arguments(start_date, end_date, **kwargs)
agg_query = self.... |
Overwrite error handling to suppress socket/ ssl related errors: param client_address: Address of client: param request: Request causing an error | def handle_error(self, request, client_address):
"""
Overwrite error handling to suppress socket/ssl related errors
:param client_address: Address of client
:param request: Request causing an error
"""
cls, e = sys.exc_info()[:2]
if cls is socket.error or cls is s... |
Build a file - download event. | def file_download_event_builder(event, sender_app, obj=None, **kwargs):
"""Build a file-download event."""
event.update(dict(
# When:
timestamp=datetime.datetime.utcnow().isoformat(),
# What:
bucket_id=str(obj.bucket_id),
file_id=str(obj.file_id),
file_key=obj.key... |
Build a record - view event. | def record_view_event_builder(event, sender_app, pid=None, record=None,
**kwargs):
"""Build a record-view event."""
event.update(dict(
# When:
timestamp=datetime.datetime.utcnow().isoformat(),
# What:
record_id=str(record.id),
pid_type=pid.pi... |
Setup consumer | def main():
"""
Setup consumer
"""
config = loader.load_config()
if config.version:
show_version()
if config.show_rules:
show_rules()
if not config.configfile and not (hasattr(config, "status") or hasattr(config, "stop")):
show_configfile_warning()
# Check if we ... |
Check if we can write to the given file | def check_write_permissions(file):
"""
Check if we can write to the given file
Otherwise since we might detach the process to run in the background
we might never find out that writing failed and get an ugly
exit message on startup. For example:
ERROR: Child exited immediately with non-zero exi... |
Show the list of available rules and quit: return: | def show_rules():
"""
Show the list of available rules and quit
:return:
"""
from rules.loader import import_rules
from rules.rule_list import all_rules
rules = import_rules(all_rules)
print("")
for name, rule in rules.iteritems():
heading = "{} (`{}`)".format(rule.descriptio... |
Start the http proxy: param config:: return: | def start_proxy(config):
"""
Start the http proxy
:param config:
:return:
"""
protector = Protector(config.rules, config.whitelist)
protector_daemon = ProtectorDaemon(config=config, protector=protector)
daemon = daemonocle.Daemon(
pidfile=config.pidfile,
detach=(not conf... |
From http:// stackoverflow. com/ a/ 8290508/ 270334: param n:: param iterable: | def batches(iterable, n=1):
"""
From http://stackoverflow.com/a/8290508/270334
:param n:
:param iterable:
"""
l = len(iterable)
for ndx in range(0, l, n):
yield iterable[ndx:min(ndx + n, l)] |
Checks if the user is rooted. | def _is_root():
"""Checks if the user is rooted."""
import os
import ctypes
try:
return os.geteuid() == 0
except AttributeError:
return ctypes.windll.shell32.IsUserAnAdmin() != 0
return False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.