code stringlengths 52 7.75k | docs stringlengths 1 5.85k |
|---|---|
def str_val(val):
str_val = val
if val is None:
str_val = "NA"
elif type(val) == float:
str_val = '%0.2f' % val
else:
str_val = str(val)
return str_val | Format the value of a metric value to a string
:param val: number to be formatted
:return: a string with the formatted value |
def load_cfg(path, envvar_prefix='LIBREANT_', debug=False):
'''wrapper of config_utils.load_configs'''
try:
return load_configs(envvar_prefix, path=path)
except Exception as e:
if debug:
raise
else:
die(str(e)f load_cfg(path, envvar_prefix='LIBREANT_', debug=F... | wrapper of config_utils.load_configs |
def files_in_subdir(dir, subdir):
paths = []
for (path, dirs, files) in os.walk(os.path.join(dir, subdir)):
for file in files:
paths.append(os.path.relpath(os.path.join(path, file), dir))
return paths | Find all files in a directory. |
def overview(index, start, end):
results = {
"activity_metrics": [Commits(index, start, end)],
"author_metrics": [Authors(index, start, end)],
"bmi_metrics": [],
"time_to_close_metrics": [],
"projects_metrics": []
}
return results | Compute metrics in the overview section for enriched git indexes.
Returns a dictionary. Each key in the dictionary is the name of
a metric, the value is the value of that metric. Value can be
a complex object (eg, a time series).
:param index: index object
:param start: start date to get the data ... |
def project_activity(index, start, end):
results = {
"metrics": [Commits(index, start, end),
Authors(index, start, end)]
}
return results | Compute the metrics for the project activity section of the enriched
git index.
Returns a dictionary containing a "metric" key. This key contains the
metrics for this section.
:param index: index object
:param start: start date to get the data from
:param end: end date to get the data upto
... |
def project_community(index, start, end):
results = {
"author_metrics": [Authors(index, start, end)],
"people_top_metrics": [Authors(index, start, end)],
"orgs_top_metrics": [Organizations(index, start, end)],
}
return results | Compute the metrics for the project community section of the enriched
git index.
Returns a dictionary containing "author_metrics", "people_top_metrics"
and "orgs_top_metrics" as the keys and the related Metrics as the values.
:param index: index object
:param start: start date to get the data from... |
def aggregations(self):
prev_month_start = get_prev_month(self.end, self.query.interval_)
self.query.since(prev_month_start)
self.query.get_terms("author_name")
return self.query.get_list(dataframe=True) | Override parent method. Obtain list of the terms and their corresponding
values using "terms" aggregations for the previous time period.
:returns: a data frame containing terms and their corresponding values |
def timeseries(self, dataframe=False):
self.query.get_cardinality("author_uuid").by_period()
return super().timeseries(dataframe) | Get the date histogram aggregations.
:param dataframe: if true, return a pandas.DataFrame object |
def overview(index, start, end):
results = {
"activity_metrics": [OpenedIssues(index, start, end),
ClosedIssues(index, start, end)],
"author_metrics": [],
"bmi_metrics": [BMI(index, start, end)],
"time_to_close_metrics": [DaysToCloseMedian(index, st... | Compute metrics in the overview section for enriched github issues
indexes.
Returns a dictionary. Each key in the dictionary is the name of
a metric, the value is the value of that metric. Value can be
a complex object (eg, a time series).
:param index: index object
:param start: start date to ... |
def project_activity(index, start, end):
results = {
"metrics": [OpenedIssues(index, start, end),
ClosedIssues(index, start, end)]
}
return results | Compute the metrics for the project activity section of the enriched
github issues index.
Returns a dictionary containing a "metric" key. This key contains the
metrics for this section.
:param index: index object
:param start: start date to get the data from
:param end: end date to get the dat... |
def project_process(index, start, end):
results = {
"bmi_metrics": [BMI(index, start, end)],
"time_to_close_metrics": [DaysToCloseAverage(index, start, end),
DaysToCloseMedian(index, start, end)],
"time_to_close_review_metrics": [],
"patchsets_... | Compute the metrics for the project process section of the enriched
github issues index.
Returns a dictionary containing "bmi_metrics", "time_to_close_metrics",
"time_to_close_review_metrics" and patchsets_metrics as the keys and
the related Metrics as the values.
time_to_close_title and time_to_cl... |
def aggregations(self):
prev_month_start = get_prev_month(self.end,
self.closed.query.interval_)
self.closed.query.since(prev_month_start,
field="closed_at")
closed_agg = self.closed.aggregations()
self.o... | Get the aggregation value for BMI with respect to the previous
time interval. |
def create_string_buffer(init, size=None, encoding=sys.getdefaultencoding()):
if isinstance(init, six.string_types + (six.binary_type,)):
if size is None:
size = len(init) + 1
buftype = c_char * size
buf = buftype()
try:
buf.value = init.encode(encoding)
... | create_string_buffer(aString) -> character array
create_string_buffer(anInteger) -> character array
create_string_buffer(aString, anInteger) -> character array |
def c_log(level, message):
c_level = level
level = LEVELS_F2PY[c_level]
logger.log(level, message) | python logger to be called from fortran |
def struct2dict(struct):
return {x: getattr(struct, x) for x in dict(struct._fields_).keys()} | convert a ctypes structure to a dictionary |
def structs2records(structs):
try:
n = len(structs)
except TypeError:
# no array
yield struct2dict(structs)
# just 1
return
for i in range(n):
struct = structs[i]
yield struct2dict(struct) | convert one or more structs and generate dictionaries |
def structs2pandas(structs):
try:
import pandas
records = list(structs2records(structs))
df = pandas.DataFrame.from_records(records)
# TODO: do this for string columns, for now just for id
# How can we check for string columns, this is not nice:
# df.columns[df.d... | convert ctypes structure or structure array to pandas data frame |
def wrap(func):
@functools.wraps(func, assigned=('restype', 'argtypes'))
def wrapped(*args):
if len(args) != len(func.argtypes):
logger.warn("{} {} not of same length",
args, func.argtypes)
typed_args = []
for (arg, argtype) in zip(args, func.arg... | Return wrapped function with type conversion and sanity checks. |
def _libname(self):
prefix = 'lib'
suffix = '.so'
if platform.system() == 'Darwin':
suffix = '.dylib'
if platform.system() == 'Windows':
prefix = ''
suffix = '.dll'
return prefix + self.engine + suffix | Return platform-specific modelf90 shared library name. |
def _library_path(self):
# engine is an existing library name
# TODO change add directory to library path
if os.path.isfile(self.engine):
return self.engine
pathname = 'LD_LIBRARY_PATH'
separator = ':'
if platform.system() == 'Darwin':
p... | Return full path to the shared library.
A couple of regular unix paths like ``/usr/lib/`` is searched by
default. If your library is not in one of those, set a
``LD_LIBRARY_PATH`` environment variable to the directory with your
shared library.
If the library cannot be found, a ... |
def _load_library(self):
path = self._library_path()
logger.info("Loading library from path {}".format(path))
library_dir = os.path.dirname(path)
if platform.system() == 'Windows':
import win32api
olddir = os.getcwd()
os.chdir(library_dir)
... | Return the fortran library, loaded with |
def initialize(self, configfile=None):
if configfile is not None:
self.configfile = configfile
try:
self.configfile
except AttributeError:
raise ValueError("Specify configfile during construction or during initialize")
abs_name = os.path.absp... | Initialize and load the Fortran library (and model, if applicable).
The Fortran library is loaded and ctypes is used to annotate functions
inside the library. The Fortran library's initialization is called.
Normally a path to an ``*.ini`` model file is passed to the
:meth:`__init__`. I... |
def finalize(self):
self.library.finalize.argtypes = []
self.library.finalize.restype = c_int
ierr = wrap(self.library.finalize)()
# always go back to previous directory
logger.info('cd {}'.format(self.original_dir))
# This one doesn't work.
os.chdir(self... | Shutdown the library and clean up the model.
Note that the Fortran library's cleanup code is not up to snuff yet,
so the cleanup is not perfect. Note also that the working directory is
changed back to the original one. |
def update(self, dt=-1):
self.library.update.argtypes = [c_double]
self.library.update.restype = c_int
if dt == -1:
# use default timestep
dt = self.get_time_step()
result = wrap(self.library.update)(dt)
return result | Return type string, compatible with numpy. |
def get_var_count(self):
n = c_int()
self.library.get_var_count.argtypes = [POINTER(c_int)]
self.library.get_var_count(byref(n))
return n.value | Return number of variables |
def get_var_name(self, i):
i = c_int(i)
name = create_string_buffer(MAXSTRLEN)
self.library.get_var_name.argtypes = [c_int, c_char_p]
self.library.get_var_name(i, name)
return name.value | Return variable name |
def get_var_type(self, name):
name = create_string_buffer(name)
type_ = create_string_buffer(MAXSTRLEN)
self.library.get_var_type.argtypes = [c_char_p, c_char_p]
self.library.get_var_type(name, type_)
return type_.value | Return type string, compatible with numpy. |
def inq_compound(self, name):
name = create_string_buffer(name)
self.library.inq_compound.argtypes = [c_char_p, POINTER(c_int)]
self.library.inq_compound.restype = None
nfields = c_int()
self.library.inq_compound(name, byref(nfields))
return nfields.value | Return the number of fields and size (not yet) of a compound type. |
def inq_compound_field(self, name, index):
typename = create_string_buffer(name)
index = c_int(index + 1)
fieldname = create_string_buffer(MAXSTRLEN)
fieldtype = create_string_buffer(MAXSTRLEN)
rank = c_int()
arraytype = ndpointer(dtype='int32',
... | Lookup the type,rank and shape of a compound field |
def make_compound_ctype(self, varname):
# look up the type name
compoundname = self.get_var_type(varname)
nfields = self.inq_compound(compoundname)
# for all the fields look up the type, rank and shape
fields = []
for i in range(nfields):
(fieldname,... | Create a ctypes type that corresponds to a compound type in memory. |
def get_var_rank(self, name):
name = create_string_buffer(name)
rank = c_int()
self.library.get_var_rank.argtypes = [c_char_p, POINTER(c_int)]
self.library.get_var_rank.restype = None
self.library.get_var_rank(name, byref(rank))
return rank.value | Return array rank or 0 for scalar. |
def get_var_shape(self, name):
rank = self.get_var_rank(name)
name = create_string_buffer(name)
arraytype = ndpointer(dtype='int32',
ndim=1,
shape=(MAXDIMS, ),
flags='F')
shape = np.empty((... | Return shape of the array. |
def get_start_time(self):
start_time = c_double()
self.library.get_start_time.argtypes = [POINTER(c_double)]
self.library.get_start_time.restype = None
self.library.get_start_time(byref(start_time))
return start_time.value | returns start time |
def get_end_time(self):
end_time = c_double()
self.library.get_end_time.argtypes = [POINTER(c_double)]
self.library.get_end_time.restype = None
self.library.get_end_time(byref(end_time))
return end_time.value | returns end time of simulation |
def get_current_time(self):
current_time = c_double()
self.library.get_current_time.argtypes = [POINTER(c_double)]
self.library.get_current_time.restype = None
self.library.get_current_time(byref(current_time))
return current_time.value | returns current time of simulation |
def get_time_step(self):
time_step = c_double()
self.library.get_time_step.argtypes = [POINTER(c_double)]
self.library.get_time_step.restype = None
self.library.get_time_step(byref(time_step))
return time_step.value | returns current time step of simulation |
def get_var(self, name):
# How many dimensions.
rank = self.get_var_rank(name)
# The shape array is fixed size
shape = np.empty((MAXDIMS, ), dtype='int32', order='F')
shape = self.get_var_shape(name)
# there should be nothing here...
assert sum(shape[rank... | Return an nd array from model library |
def set_logger(self, logger):
# we don't expect anything back
try:
self.library.set_logger.restype = None
except AttributeError:
logger.warn("Tried to set logger but method is not implemented in %s", self.engine)
return
# as an argument we ne... | subscribe to fortran log messages |
def set_current_time(self, current_time):
current_time = c_double(current_time)
try:
self.library.set_current_time.argtypes = [POINTER(c_double)]
self.library.set_current_time.restype = None
self.library.set_current_time(byref(current_time))
except At... | sets current time of simulation |
def validate_book(body):
'''
This does not only accept/refuse a book. It also returns an ENHANCED
version of body, with (mostly fts-related) additional fields.
This function is idempotent.
'''
if '_language' not in body:
raise ValueError('language needed')
if len(body['_language']) ... | This does not only accept/refuse a book. It also returns an ENHANCED
version of body, with (mostly fts-related) additional fields.
This function is idempotent. |
def clone_index(self, new_indexname, index_conf=None):
'''Clone current index
All entries of the current index will be copied into the newly
created one named `new_indexname`
:param index_conf: Configuration to be used in the new index creation.
T... | Clone current index
All entries of the current index will be copied into the newly
created one named `new_indexname`
:param index_conf: Configuration to be used in the new index creation.
This param will be passed directly to :py:func:`DB.create_index` |
def mlt(self, _id):
'''
High-level method to do "more like this".
Its exact implementation can vary.
'''
query = {
'query': {'more_like_this': {
'like': {'_id': _id},
'min_term_freq': 1,
'min_doc_freq'... | High-level method to do "more like this".
Its exact implementation can vary. |
def file_is_attached(self, url):
'''return true if at least one book has
file with the given url as attachment
'''
body = self._get_search_field('_attachments.url', url)
return self.es.count(index=self.index_name, body=body)['count'] > f file_is_attached(self, url):
''... | return true if at least one book has
file with the given url as attachment |
def add_book(self, body, doc_type='book'):
'''
Call it like this:
db.add_book(doc_type='book',
body={'title': 'foobar', '_language': 'it'})
'''
body = validate_book(body)
body['_insertion_date'] = current_time_millisec()
return self.es.index(index=... | Call it like this:
db.add_book(doc_type='book',
body={'title': 'foobar', '_language': 'it'}) |
def delete_all(self):
'''Delete all books from the index'''
def delete_action_gen():
scanner = scan(self.es,
index=self.index_name,
query={'query': {'match_all':{}}})
for v in scanner:
yield { '_op_type': 'dele... | Delete all books from the index |
def update_book(self, id, body, doc_type='book'):
''' Update a book
The "body" is merged with the current one.
Yes, it is NOT overwritten.
In case of concurrency conflict
this function could raise `elasticsearch.ConflictError`
'''
# note that we ... | Update a book
The "body" is merged with the current one.
Yes, it is NOT overwritten.
In case of concurrency conflict
this function could raise `elasticsearch.ConflictError` |
def modify_book(self, id, body, doc_type='book', version=None):
''' replace the entire book body
Instead of `update_book` this function
will overwrite the book content with param body
If param `version` is given, it will be checked that the
changes are applied u... | replace the entire book body
Instead of `update_book` this function
will overwrite the book content with param body
If param `version` is given, it will be checked that the
changes are applied upon that document version.
If the document version provided is d... |
def increment_download_count(self, id, attachmentID, doc_type='book'):
'''
Increment the download counter of a specific file
'''
body = self.es.get(index=self.index_name, id=id, doc_type='book', _source_include='_attachments')['_source']
for attachment in body['_attachments']:
... | Increment the download counter of a specific file |
def __add_types(self, raw_conf):
typed_conf = {}
for s in raw_conf.keys():
typed_conf[s] = {}
for option in raw_conf[s]:
val = raw_conf[s][option]
if len(val) > 1 and (val[0] == '"' and val[-1] == '"'):
# It is a stri... | Convert to int, boolean, list, None types config items |
def Elasticsearch(*args, **kwargs):
check_version = kwargs.pop('check_version', True)
es = Elasticsearch_official(*args, **kwargs)
if check_version:
es_version = es.info()['version']['number'].split('.')
if(int(es_version[0]) != int(es_pylib_version[0])):
raise RuntimeError(... | Elasticsearch wrapper function
Wrapper function around the official Elasticsearch class that adds
a simple version check upon initialization.
In particular it checks if the major version of the library in use
match the one of the cluster that we are tring to interact with.
The check can be skipped ... |
def from_envvars(prefix=None, environ=None, envvars=None, as_json=True):
conf = {}
if environ is None:
environ = os.environ
if prefix is None and envvars is None:
raise RuntimeError('Must either give prefix or envvars argument')
# if it's a list, convert to dict
if isinstance(e... | Load environment variables in a dictionary
Values are parsed as JSON. If parsing fails with a ValueError,
values are instead used as verbatim strings.
:param prefix: If ``None`` is passed as envvars, all variables from
``environ`` starting with this prefix are imported. The
... |
def load_configs(envvar_prefix, path=None):
'''Load configuration
The following steps will be undertake:
* It will attempt to load configs from file:
if `path` is provided, it will be used, otherwise the path
will be taken from envvar `envvar_prefix` + "SETTINGS".
* all envv... | Load configuration
The following steps will be undertake:
* It will attempt to load configs from file:
if `path` is provided, it will be used, otherwise the path
will be taken from envvar `envvar_prefix` + "SETTINGS".
* all envvars starting with `envvar_prefix` will be loaded. |
def get_trend(timeseries):
last = timeseries['value'][len(timeseries['value']) - 1]
prev = timeseries['value'][len(timeseries['value']) - 2]
trend = last - prev
trend_percentage = None
if last == 0:
if prev > 0:
trend_percentage = -100
else:
trend_perce... | Using the values returned by get_timeseries(), compare the current
Metric value with it's previous period's value
:param timeseries: data returned from the get_timeseries() method
:returns: the last period value and relative change |
def calculate_bmi(closed, submitted):
if sorted(closed.keys()) != sorted(submitted.keys()):
raise AttributeError("The buckets supplied are not congruent!")
dates = closed.index.values
closed_values = closed['value']
submitted_values = submitted['value']
ratios = []
for x, y in zip... | BMI is the ratio of the number of closed items to the number of total items
submitted in a particular period of analysis. The items can be issues, pull
requests and such
:param closed: dataframe returned from get_timeseries() containing closed items
:param submitted: dataframe returned from get_timeser... |
def buckets_to_df(buckets):
cleaned_buckets = []
for item in buckets:
if type(item) == str:
return item
temp = {}
for key, val in item.items():
try:
temp[key] = val['value']
except Exception as e:
temp[key] = val
... | Takes in aggregation buckets and converts them into a pandas dataframe
after cleaning the buckets. If a DateTime field is present(usually having the name:
"key_as_string") parses it to datetime object and then it uses it as key
:param buckets: elasticsearch aggregation buckets to be converted to a DataFram... |
def add_query(self, key_val={}):
q = Q("match", **key_val)
self.search = self.search.query(q)
return self | Add an es_dsl query object to the es_dsl Search object
:param key_val: a key-value pair(dict) containing the query to be added to the search object
:returns: self, which allows the method to be chainable with the other methods |
def add_inverse_query(self, key_val={}):
q = Q("match", **key_val)
self.search = self.search.query(~q)
return self | Add an es_dsl inverse query object to the es_dsl Search object
:param key_val: a key-value pair(dict) containing the query to be added to the search object
:returns: self, which allows the method to be chainable with the other methods |
def get_sum(self, field=None):
if not field:
raise AttributeError("Please provide field to apply aggregation to!")
agg = A("sum", field=field)
self.aggregations['sum_' + field] = agg
return self | Create a sum aggregation object and add it to the aggregation dict
:param field: the field present in the index that is to be aggregated
:returns: self, which allows the method to be chainable with the other methods |
def get_average(self, field=None):
if not field:
raise AttributeError("Please provide field to apply aggregation to!")
agg = A("avg", field=field)
self.aggregations['avg_' + field] = agg
return self | Create an avg aggregation object and add it to the aggregation dict
:param field: the field present in the index that is to be aggregated
:returns: self, which allows the method to be chainable with the other methods |
def get_percentiles(self, field=None, percents=None):
if not field:
raise AttributeError("Please provide field to apply aggregation to!")
if not percents:
percents = [1.0, 5.0, 25.0, 50.0, 75.0, 95.0, 99.0]
agg = A("percentiles", field=field, percents=percents)
... | Create a percentile aggregation object and add it to the aggregation dict
:param field: the field present in the index that is to be aggregated
:param percents: the specific percentiles to be calculated
default: [1.0, 5.0, 25.0, 50.0, 75.0, 95.0, 99.0]
:returns: self, w... |
def get_terms(self, field=None):
if not field:
raise AttributeError("Please provide field to apply aggregation to!")
agg = A("terms", field=field, size=self.size, order={"_count": "desc"})
self.aggregations['terms_' + field] = agg
return self | Create a terms aggregation object and add it to the aggregation dict
:param field: the field present in the index that is to be aggregated
:returns: self, which allows the method to be chainable with the other methods |
def get_min(self, field=None):
if not field:
raise AttributeError("Please provide field to apply aggregation to!")
agg = A("min", field=field)
self.aggregations['min_' + field] = agg
return self | Create a min aggregation object and add it to the aggregation dict
:param field: the field present in the index that is to be aggregated
:returns: self, which allows the method to be chainable with the other methods |
def get_max(self, field=None):
if not field:
raise AttributeError("Please provide field to apply aggregation to!")
agg = A("max", field=field)
self.aggregations['max_' + field] = agg
return self | Create a max aggregation object and add it to the aggregation dict
:param field: the field present in the index that is to be aggregated
:returns: self, which allows the method to be chainable with the other methods |
def get_cardinality(self, field=None):
if not field:
raise AttributeError("Please provide field to apply aggregation to!")
agg = A("cardinality", field=field, precision_threshold=self.precision_threshold)
self.aggregations['cardinality_' + field] = agg
return self | Create a cardinality aggregation object and add it to the aggregation dict
:param field: the field present in the index that is to be aggregated
:returns: self, which allows the method to be chainable with the other methods |
def get_extended_stats(self, field=None):
if not field:
raise AttributeError("Please provide field to apply aggregation to!")
agg = A("extended_stats", field=field)
self.aggregations['extended_stats_' + field] = agg
return self | Create an extended_stats aggregation object and add it to the aggregation dict
:param field: the field present in the index that is to be aggregated
:returns: self, which allows the method to be chainable with the other methods |
def add_custom_aggregation(self, agg, name=None):
agg_name = name if name else 'custom_agg'
self.aggregations[agg_name] = agg
return self | Takes in an es_dsl Aggregation object and adds it to the aggregation dict.
Can be used to add custom aggregations such as moving averages
:param agg: aggregation to be added to the es_dsl search object
:param name: name of the aggregation object (optional)
:returns: self, which allows t... |
def since(self, start, field=None):
if not field:
field = "grimoire_creation_date"
self.start_date = start
date_dict = {field: {"gte": "{}".format(self.start_date.isoformat())}}
self.search = self.search.filter("range", **date_dict)
return self | Add the start date to query data starting from that date
sets the default start date for each query
:param start: date to start looking at the fields (from date)
:param field: specific field for the start date in range filter
for the Search object
:returns: self, w... |
def until(self, end, field=None):
if not field:
field = "grimoire_creation_date"
self.end_date = end
date_dict = {field: {"lte": "{}".format(self.end_date.isoformat())}}
self.search = self.search.filter("range", **date_dict)
return self | Add the end date to query data upto that date
sets the default end date for each query
:param end: date to stop looking at the fields (to date)
:param field: specific field for the end date in range filter
for the Search object
:returns: self, which allows the meth... |
def by_organizations(self, field=None):
# this functions is currently only for issues and PRs
agg_field = field if field else "author_org_name"
agg_key = "terms_" + agg_field
if agg_key in self.aggregations.keys():
agg = self.aggregations[agg_key]
else:
... | Used to seggregate the data acording to organizations. This method
pops the latest aggregation from the self.aggregations dict and
adds it as a nested aggregation under itself
:param field: the field to create the parent agg (optional)
default: author_org_name
:ret... |
def by_period(self, field=None, period=None, timezone=None, start=None, end=None):
hist_period = period if period else self.interval_
time_zone = timezone if timezone else "UTC"
start_ = start if start else self.start_date
end_ = end if end else self.end_date
bounds = ... | Create a date histogram aggregation using the last added aggregation for the
current object. Add this date_histogram aggregation into self.aggregations
:param field: the index field to create the histogram from
:param period: the interval which elasticsearch supports, ex: "month", "week" and su... |
def get_bounds(self, start=None, end=None):
bounds = {}
if start or end:
# Extend bounds so we have data until start and end
start_ts = None
end_ts = None
if start:
start = start.replace(microsecond=0)
start_ts = ... | Get bounds for the date_histogram method
:param start: start date to set the extended_bounds min field
:param end: end date to set the extended_bounds max field
:returns bounds: a dictionary containing the min and max fields
required to set the bounds in date_histogram ... |
def reset_aggregations(self):
temp_search = self.search.to_dict()
if 'aggs' in temp_search.keys():
del temp_search['aggs']
self.search.from_dict(temp_search)
self.parent_agg_counter = 0
self.child_agg_counter = 0
self.child_agg_counter_dict = def... | Remove all aggregations added to the search object |
def fetch_aggregation_results(self):
self.reset_aggregations()
for key, val in self.aggregations.items():
self.search.aggs.bucket(self.parent_agg_counter, val)
self.parent_agg_counter += 1
self.search = self.search.extra(size=0)
response = self.search.... | Loops though the self.aggregations dict and adds them to the Search object
in order in which they were created. Queries elasticsearch and returns a dict
containing the results
:returns: a dictionary containing the response from elasticsearch |
def fetch_results_from_source(self, *fields, dataframe=False):
if not fields:
raise AttributeError("Please provide the fields to get from elasticsearch!")
self.reset_aggregations()
self.search = self.search.extra(_source=fields)
self.search = self.search.extra(siz... | Get values for specific fields in the elasticsearch index, from source
:param fields: a list of fields that have to be retrieved from the index
:param dataframe: if true, will return the data in the form of a pandas.DataFrame
:returns: a list of dicts(key_val pairs) containing the values for th... |
def get_timeseries(self, child_agg_count=0, dataframe=False):
res = self.fetch_aggregation_results()
ts = {"date": [], "value": [], "unixtime": []}
if 'buckets' not in res['aggregations'][str(self.parent_agg_counter - 1)]:
raise RuntimeError("Aggregation results have no b... | Get time series data for the specified fields and period of analysis
:param child_agg_count: the child aggregation count to be used
default = 0
:param dataframe: if dataframe=True, return a pandas.DataFrame object
:returns: dictionary containing "date", "value" a... |
def get_aggs(self):
res = self.fetch_aggregation_results()
if 'aggregations' in res and 'values' in res['aggregations'][str(self.parent_agg_counter - 1)]:
try:
agg = res['aggregations'][str(self.parent_agg_counter - 1)]['values']["50.0"]
if agg == 'N... | Compute the values for single valued aggregations
:returns: the single aggregation value |
def get_list(self, dataframe=False):
res = self.fetch_aggregation_results()
keys = []
values = []
for bucket in res['aggregations'][str(self.parent_agg_counter - 1)]['buckets']:
keys.append(bucket['key'])
values.append(bucket['doc_count'])
resul... | Compute the value for multi-valued aggregations
:returns: a dict containing 'keys' and their corresponding 'values' |
def import_volumes(source, ignore_conflicts, yes):
'''Import volumes
SOURCE must be a json file and must follow the same structure used in `libreant-db export`.
Pass - to read from standard input.
'''
volumes = json.load(source)
tot = len(volumes)
if not yes:
click.confirm("Are you ... | Import volumes
SOURCE must be a json file and must follow the same structure used in `libreant-db export`.
Pass - to read from standard input. |
def attach_list(filepaths, notes):
'''
all the arguments are lists
returns a list of dictionaries; each dictionary "represent" an attachment
'''
assert type(filepaths) in (list, tuple)
assert type(notes) in (list, tuple)
# this if clause means "if those lists are not of the same length"
... | all the arguments are lists
returns a list of dictionaries; each dictionary "represent" an attachment |
def _param_fields(kwargs, fields):
if fields is None:
return
if type(fields) in [list, set, frozenset, tuple]:
fields = {x: True for x in fields}
if type(fields) == dict:
fields.setdefault("_id", False)
kwargs["projection"] = fields | Normalize the "fields" argument to most find methods |
def find_method(func):
def wrapped(*args, **kwargs):
# Normalize the fields argument if passed as a positional param.
if len(args) == 3 and func.__name__ in ("find", "find_one", "find_by_id", "find_by_ids"):
_param_fields(kwargs, args[2])
args = (args[0], args[1])
elif "fields" in kwargs:
... | Decorator that manages smart defaults or transforms for common find methods:
- fields/projection: list of fields to be returned. Contrary to pymongo, _id won't be added automatically
- json: performs a json_clone on the results. Beware of performance!
- timeout
- return_document |
def patch_cursor(cursor, batch_size=None, limit=None, skip=None, sort=None, **kwargs):
if type(batch_size) == int:
cursor.batch_size(batch_size)
if limit is not None:
cursor.limit(limit)
if sort is not None:
cursor.sort(sort)
if skip is not None:
cursor.skip(skip) | Adds batch_size, limit, sort parameters to a DB cursor |
def exists(self, query, **args):
return bool(self.find(query, **args).limit(1).count()) | Returns True if the search matches at least one document |
def _collection_with_options(self, kwargs):
# class DocumentClassWithFields(self.document_class):
# _fetched_fields = kwargs.get("projection")
# mongokat_collection = self
read_preference = kwargs.get("read_preference") or getattr(self.collection, "read_preference", No... | Returns a copy of the pymongo collection with various options set up |
def find_one(self, *args, **kwargs):
doc = self._collection_with_options(kwargs).find_one(*args, **kwargs)
if doc is None:
return None
return doc | Get a single document from the database. |
def find_by_id(self, _id, **kwargs):
if type(_id) == dict and _id.get("_id"):
return self.find_one({"_id": ObjectId(_id["_id"])}, **kwargs)
return self.find_one({"_id": ObjectId(_id)}, **kwargs) | Pass me anything that looks like an _id : str, ObjectId, {"_id": str}, {"_id": ObjectId} |
def find_by_ids(self, _ids, projection=None, **kwargs):
id_list = [ObjectId(_id) for _id in _ids]
if len(_ids) == 0:
return [] # FIXME : this should be an empty cursor !
# Optimized path when only fetching the _id field.
# Be mindful this might not filter missing... | Does a big _id:$in query on any iterator |
def find_by_b64id(self, _id, **kwargs):
return self.find_one({"_id": ObjectId(base64.b64decode(_id))}, **kwargs) | Pass me a base64-encoded ObjectId |
def find_by_b64ids(self, _ids, **kwargs):
return self.find_by_ids([ObjectId(base64.b64decode(_id)) for _id in _ids], **kwargs) | Pass me a list of base64-encoded ObjectId |
def iter_column(self, query=None, field="_id", **kwargs):
find_kwargs = {
"projection": {"_id": False}
}
find_kwargs["projection"][field] = True
cursor = self._collection_with_options(kwargs).find(query, **find_kwargs) # We only want 1 field: bypass the ORM
... | Return one field as an iterator.
Beware that if your query returns records where the field is not set, it will raise a KeyError. |
def find_random(self, **kwargs):
import random
max = self.count(**kwargs)
if max:
num = random.randint(0, max - 1)
return next(self.find(**kwargs).skip(num)) | return one random document from the collection |
def insert(self, data, return_object=False):
obj = self(data) # pylint: disable=E1102
obj.save()
if return_object:
return obj
else:
return obj["_id"] | Inserts the data as a new document. |
def trigger(self, event, filter=None, update=None, documents=None, ids=None, replacements=None):
if not self.has_trigger(event):
return
if documents is not None:
pass
elif ids is not None:
documents = self.find_by_ids(ids, read_use="primary")
... | Trigger the after_save hook on documents, if present. |
def fetch(self, spec=None, *args, **kwargs):
if spec is None:
spec = {}
for key in self.structure:
if key in spec:
if isinstance(spec[key], dict):
spec[key].update({'$exists': True})
else:
spec[key] = {'$exi... | return all document which match the structure of the object
`fetch()` takes the same arguments than the the pymongo.collection.find method.
The query is launch against the db and collection of the object. |
def fetch_one(self, *args, **kwargs):
bson_obj = self.fetch(*args, **kwargs)
count = bson_obj.count()
if count > 1:
raise MultipleResultsFound("%s results found" % count)
elif count == 1:
# return self(bson_obj.next(), fetched_fields=kwargs.get("projectio... | return one document which match the structure of the object
`fetch_one()` takes the same arguments than the the pymongo.collection.find method.
If multiple documents are found, raise a MultipleResultsFound exception.
If no document is found, return None
The query is launch against the db... |
def usage(ecode, msg=''):
print >> sys.stderr, __doc__
if msg:
print >> sys.stderr, msg
sys.exit(ecode) | Print usage and msg and exit with given code. |
def add(msgid, transtr, fuzzy):
global MESSAGES
if not fuzzy and transtr and not transtr.startswith('\0'):
MESSAGES[msgid] = transtr | Add a non-fuzzy translation to the dictionary. |
def generate():
global MESSAGES
keys = MESSAGES.keys()
# the keys are sorted in the .mo file
keys.sort()
offsets = []
ids = strs = ''
for _id in keys:
# For each string, we need size and file offset. Each string is NUL
# terminated; the NUL does not count into the size.... | Return the generated output. |
def get_es_requirements(es_version):
'''Get the requirements string for elasticsearch-py library
Returns a suitable requirements string for the elsaticsearch-py library
according to the elasticsearch version to be supported (es_version)'''
# accepts version range in the form `2.x`
es_version = es_... | Get the requirements string for elasticsearch-py library
Returns a suitable requirements string for the elsaticsearch-py library
according to the elasticsearch version to be supported (es_version) |
def run(self):
# thanks to deluge guys ;)
po_dir = os.path.join(os.path.dirname(__file__), 'webant', 'translations')
print('Compiling po files from "{}"...'.format(po_dir))
for lang in os.listdir(po_dir):
sys.stdout.write("\tCompiling {}... ".format(lang))
... | Compile all message catalogs .po files into .mo files.
Skips not changed file based on source mtime. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.