code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
arguments = docopt.docopt(__doc__, version=__version__) colorlogs() # Read input file file wrapper = BMIWrapper( engine=arguments['<engine>'], configfile=arguments['<config>'] or '' ) # add logger if required if not arguments['--disable-logger']: logging.root...
def main()
main bmi runner program
4.352316
4.232186
1.028385
'''return default configurations as simple dict''' ret = dict() for k,v in defConf.items(): ret[k] = v[0] return ret
def get_def_conf()
return default configurations as simple dict
5.975308
4.305546
1.387816
if len(self.moves) == MAX_MOVES: return False elif len(self.moves) % 2: active_engine = self.black_engine active_engine_name = self.black inactive_engine = self.white_engine inactive_engine_name = self.white else: a...
def move(self)
Advance game by single move, if possible. @return: logical indicator if move was performed.
2.712374
2.744486
0.9883
self.put('position startpos moves %s' % Engine._movelisttostr(moves)) self.isready()
def setposition(self, moves=[])
Move list is a list of moves (i.e. ['e2e4', 'e7e5', ...]) each entry as a string. Moves must be in full algebraic notation.
17.439528
15.442803
1.129298
self.go() last_info = "" while True: text = self.stdout.readline().strip() split_text = text.split(' ') print(text) if split_text[0] == "info": last_info = Engine._bestmove_get_info(text) if split_text[0] == "be...
def bestmove(self)
Get proposed best move for current position. @return: dictionary with 'move', 'ponder', 'info' containing best move's UCI notation, ponder value and info dictionary.
3.783036
3.567922
1.060291
result_dict = Engine._get_info_pv(text) result_dict.update(Engine._get_info_score(text)) single_value_fields = ['depth', 'seldepth', 'multipv', 'nodes', 'nps', 'tbhits', 'time'] for field in single_value_fields: result_dict.update(Engine._get_info_singlevalue_subfie...
def _bestmove_get_info(text)
Parse stockfish evaluation output as dictionary. Examples of input: "info depth 2 seldepth 3 multipv 1 score cp -656 nodes 43 nps 43000 tbhits 0 \ time 1 pv g7g6 h3g3 g6f7" "info depth 10 seldepth 12 multipv 1 score mate 5 nodes 2378 nps 1189000 tbhits 0 \ time 2 pv h3g3 g6f7 ...
4.726872
3.325651
1.421337
search = re.search(pattern=field + " (?P<value>\d+)", string=info) return {field: int(search.group("value"))}
def _get_info_singlevalue_subfield(info, field)
Helper function for _bestmove_get_info. Extracts (integer) values for single value fields.
5.230818
4.734119
1.104919
search = re.search(pattern="score (?P<eval>\w+) (?P<value>-?\d+)", string=info) return {"score": {"eval": search.group("eval"), "value": int(search.group("value"))}}
def _get_info_score(info)
Helper function for _bestmove_get_info. Example inputs: score cp -100 <- engine is behind 100 centipawns score mate 3 <- engine has big lead or checkmated opponent
5.270144
4.985186
1.057161
search = re.search(pattern=PV_REGEX, string=info) return {"pv": search.group("move_list")}
def _get_info_pv(info)
Helper function for _bestmove_get_info. Extracts "pv" field from bestmove's info and returns move sequence in UCI notation.
15.342022
9.375908
1.636324
self.put('isready') while True: text = self.stdout.readline().strip() if text == 'readyok': return text
def isready(self)
Used to synchronize the python engine object with the back-end engine. Sends 'isready' and waits for 'readyok.'
6.83769
4.746428
1.440597
results = { "activity_metrics": [SubmittedPRs(index, start, end), ClosedPRs(index, start, end)], "author_metrics": [], "bmi_metrics": [BMIPR(index, start, end)], "time_to_close_metrics": [DaysToClosePRMedian(index, start, end)], "projects_me...
def overview(index, start, end)
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: date to apply ...
6.850226
7.125113
0.96142
results = { "metrics": [SubmittedPRs(index, start, end), ClosedPRs(index, start, end)] } return results
def project_activity(index, start, end)
Compute the metrics for the project activity section of the enriched github pull requests 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 ...
8.607882
10.163136
0.846971
results = { "bmi_metrics": [BMIPR(index, start, end)], "time_to_close_metrics": [], "time_to_close_review_metrics": [DaysToClosePRAverage(index, start, end), DaysToClosePRMedian(index, start, end)], "patchsets_metrics": [] } ret...
def project_process(index, start, end)
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...
8.187963
3.913357
2.092312
prev_month_start = get_prev_month(self.end, self.query.interval_) self.query.since(prev_month_start) agg = super().aggregations() if agg is None: agg = 0 # None is because NaN in ES. Let's convert to 0 return agg
def aggregations(self)
Get the single valued aggregations with respect to the previous time interval.
12.254115
10.866941
1.127651
self.query.by_period() ts = super().timeseries(dataframe=dataframe) ts['value'] = ts['value'].apply(lambda x: float("%.2f" % x)) return ts
def timeseries(self, dataframe=False)
Get the date histogram aggregations. :param dataframe: if true, return a pandas.DataFrame object
6.072505
6.46493
0.939299
closed_timeseries = self.closed.timeseries(dataframe=dataframe) opened_timeseries = self.opened.timeseries(dataframe=dataframe) return calculate_bmi(closed_timeseries, opened_timeseries)
def timeseries(self, dataframe=False)
Get BMIPR as a time series.
5.221455
4.609643
1.132724
# Those metrics are only for Pull Requests # github issues is covered as ITS return { "overview": { "activity_metrics": [ClosedPR, SubmittedPR], "author_metrics": [], "bmi_metrics": [BMIPR], "time_to_close_metr...
def get_section_metrics(cls)
Get the mapping between metrics and sections in Manuscripts report :return: a dict with the mapping between metrics and sections in Manuscripts report
5.180715
4.967738
1.042872
esfilters_close = None esfilters_submit = None if self.esfilters: esfilters_close = self.esfilters.copy() esfilters_submit = self.esfilters.copy() closed = ClosedPR(self.es_url, self.es_index, start=self.start, end=self.end, ...
def __get_metrics(self)
Each metric must have its own filters copy to modify it freely
3.933051
3.649451
1.07771
def_ = { "id": self.id, "name": self.name, "desc": self.desc } return def_
def get_definition(self)
Get the dict with the basic fields used to describe a metrics: id, name and desc :return: a dict with the definition
3.709606
2.936735
1.263173
if not evolutionary: interval = None offset = None else: interval = self.interval offset = self.offset if not interval: raise RuntimeError("Evolutionary query without an interval.") query = ElasticQuery.get_ag...
def get_query(self, evolutionary=False)
Basic query to get the metric values :param evolutionary: if True the metric values time series is returned. If False the aggregated metric value. :return: the DSL query to be sent to Elasticsearch
4.415456
4.491846
0.982994
field = self.FIELD_NAME query = ElasticQuery.get_agg(field=field, date_field=self.FIELD_DATE, start=self.start, end=self.end, filters=self.esfilters) logger.debug("Metric: '%s'...
def get_list(self)
Extract from a DSL aggregated response the values for each bucket :return: a list with the values in a DSL aggregated response
4.796926
4.853096
0.988426
if self.es_url.startswith("http"): url = self.es_url else: url = 'http://' + self.es_url es = Elasticsearch(url) s = Search(using=es, index=self.es_index) s = s.update_from_dict(query) try: response = s.execute() re...
def get_metrics_data(self, query)
Get the metrics data from Elasticsearch given a DSL query :param query: query to be sent to Elasticsearch :return: a dict with the results of executing the query
3.049748
3.096049
0.985045
query = self.get_query(True) res = self.get_metrics_data(query) # Time to convert it to our grimoire timeseries format ts = {"date": [], "value": [], "unixtime": []} agg_id = ElasticQuery.AGGREGATION_ID if 'buckets' not in res['aggregations'][str(agg_id)]: ...
def get_ts(self)
Returns a time series of a specific class A timeseries consists of a unixtime date, labels, some other fields and the data of the specific instantiated class metric per interval. This is built on a hash table. :return: a list with a time series with the values of the metric
4.107211
4.013371
1.023382
query = self.get_query(False) res = self.get_metrics_data(query) # We need to extract the data from the JSON res # If we have agg data use it agg_id = str(ElasticQuery.AGGREGATION_ID) if 'aggregations' in res and 'values' in res['aggregations'][agg_id]: ...
def get_agg(self)
Returns the aggregated value for the metric :return: the value of the metric
4.991065
4.817111
1.036111
# TODO: We just need the last two periods, not the full ts ts = self.get_ts() last = ts['value'][len(ts['value']) - 1] prev = ts['value'][len(ts['value']) - 2] trend = last - prev trend_percentage = None if last == 0: if prev > 0: ...
def get_trend(self)
Get the trend for the last two metric values using the interval defined in the metric :return: a tuple with the metric value for the last interval and the trend percentage between the last two intervals
3.455714
3.036066
1.138221
return { "overview": { "activity_metrics": [Closed, Opened], "author_metrics": [], "bmi_metrics": [BMI], "time_to_close_metrics": [DaysToCloseMedian], "projects_metrics": [Projects] }, "...
def get_section_metrics(cls)
Get the mapping between metrics and sections in Manuscripts report :return: a dict with the mapping between metrics and sections in Manuscripts report
4.171546
4.084347
1.02135
esfilters_closed = None esfilters_opened = None if self.esfilters: esfilters_closed = self.esfilters.copy() esfilters_opened = self.esfilters.copy() closed = self.closed_class(self.es_url, self.es_index, start=self.star...
def __get_metrics(self)
Each metric must have its own filters copy to modify it freely
2.525868
2.283249
1.10626
''' Goes recursevly through the given list of paths in order to find and pass all preset files to ```_load_preset()``` ''' if depth > self.MAX_DEPTH: return for path in paths: try: # avoid empty string if not path:...
def _load_paths(self, paths, depth=0)
Goes recursevly through the given list of paths in order to find and pass all preset files to ```_load_preset()```
3.665586
2.844512
1.288652
''' load, validate and store a single preset file''' try: with open(path, 'r') as f: presetBody = json.load(f) except IOError as e: raise PresetException("IOError: " + e.strerror) except ValueError as e: raise PresetException("JSON dec...
def _load_preset(self, path)
load, validate and store a single preset file
2.603505
2.385223
1.091514
''' Checks if `data` respects this preset specification It will check that every required property is present and for every property type it will make some specific control. ''' for prop in self.properties: if prop.id in data: if prop.type == ...
def validate(self, data)
Checks if `data` respects this preset specification It will check that every required property is present and for every property type it will make some specific control.
3.109582
1.91046
1.627661
if 'format' in request.args: fieldFormat = request.args.get('format') if fieldFormat not in acceptedFormat: raise ValueError("requested format not supported: "+ fieldFormat) return fieldFormat else: return request.accept_mimetypes....
def requestedFormat(request,acceptedFormat)
Return the response format requested by client Client could specify requested format using: (options are processed in this order) - `format` field in http request - `Accept` header in http request Example: chooseFormat(request, ['text/html','application/json'...
2.722671
2.585843
1.052914
def hatFunc(rule, **options): def decorator(f): rule_dict = {'rule':rule, 'view_func':f} rule_dict.update(options) gatherer.append(rule_dict) return decorator return hatFunc
def routes_collector(gatherer)
Decorator utility to collect flask routes in a dictionary. This function together with :func:`add_routes` provides an easy way to split flask routes declaration in multiple modules. :param gatherer: dict in which will be collected routes The decorator provided by this function should be used as the ...
5.146512
6.463274
0.79627
for r in routes: r['rule'] = prefix + r['rule'] fapp.add_url_rule(**r)
def add_routes(fapp, routes, prefix="")
Batch routes registering Register routes to a blueprint/flask_app previously collected with :func:`routes_collector`. :param fapp: bluprint or flask_app to whom attach new routes. :param routes: dict of routes collected by :func:`routes_collector` :param prefix: url prefix under which register all...
3.483128
4.603006
0.756707
''' Return the range of pages to render in a pagination menu. The current page is always kept in the middle except for the edge cases. Reeturns a dict { prev, first, current, last, next } :param current: the current page :param total: total number of pages avai...
def get_centered_pagination(current, total, visible=5)
Return the range of pages to render in a pagination menu. The current page is always kept in the middle except for the edge cases. Reeturns a dict { prev, first, current, last, next } :param current: the current page :param total: total number of pages available ...
3.561947
1.862303
1.912657
return { "overview": { "activity_metrics": [Closed, Submitted], "author_metrics": None, "bmi_metrics": [BMI], "time_to_close_metrics": [DaysToMergeMedian], "projects_metrics": [Projects], }, ...
def get_section_metrics(cls)
Get the mapping between metrics and sections in Manuscripts report :return: a dict with the mapping between metrics and sections in Manuscripts report
4.225484
4.167704
1.013864
esfilters_merge = None esfilters_abandon = None if self.esfilters: esfilters_merge = self.esfilters.copy() esfilters_abandon = self.esfilters.copy() merged = Merged(self.es_url, self.es_index, start=self.start, end=self.end, ...
def __get_metrics(self)
Each metric must have its own filters copy to modify it freely
2.641882
2.416001
1.093494
esfilters_merge = None esfilters_abandon = None esfilters_submit = None if self.esfilters: esfilters_merge = self.esfilters.copy() esfilters_abandon = self.esfilters.copy() esfilters_submit = self.esfilters.copy() merged = Merged(self...
def __get_metrics(self)
Each metric must have its own filters copy to modify it freely
2.555816
2.441456
1.046841
pass class NoPeaksFound(Exception): pass half_max = np.amax(y) / 2.0 s = splrep(x, y - half_max) roots = sproot(s) if len(roots) > 2: raise MultiplePeaks("The dataset appears to have multiple peaks, and " "thus the FWHM can't be determined.") ...
def fwhm(x, y, k=10): # http://stackoverflow.com/questions/10582795/finding-the-full-width-half-maximum-of-a-peak class MultiplePeaks(Exception)
Determine full-with-half-maximum of a peaked set of points, x and y. Assumes that there is only one peak present in the datasset. The function uses a spline interpolation of order k.
3.847067
3.965105
0.970231
parser = argparse.ArgumentParser(description="Smatch calculator -- arguments") parser.add_argument('-f', nargs=2, required=True, type=argparse.FileType('r'), help='Two files containing AMR pairs. AMRs in each file are separated by a single blank line') parser.add_argument('-r', ...
def build_arg_parser()
Build an argument parser using argparse. Use it when python version is 2.7 or later.
3.237785
3.188699
1.015394
usage_str = "Smatch calculator -- arguments" parser = optparse.OptionParser(usage=usage_str) parser.add_option("-f", "--files", nargs=2, dest="f", type="string", help='Two files containing AMR pairs. AMRs in each file are ' \ 'separated by a single blank...
def build_arg_parser2()
Build an argument parser using optparse. Use it when python version is 2.5 or 2.6.
3.270445
3.237193
1.010272
# Compute candidate pool - all possible node match candidates. # In the hill-climbing, we only consider candidate in this pool to save computing time. # weight_dict is a dictionary that maps a pair of node (candidate_mappings, weight_dict) = compute_pool(instance1, attribute1, relation1, ...
def get_best_match(instance1, attribute1, relation1, instance2, attribute2, relation2, prefix1, prefix2, doinstance=True, doattribute=True, dorelation=True)
Get the highest triple match number between two sets of triples via hill-climbing. Arguments: instance1: instance triples of AMR 1 ("instance", node name, node value) attribute1: attribute triples of AMR 1 (attribute name, node name, attribute value) relation1: relation triples of AMR 1 (rel...
3.190554
2.991079
1.06669
random.seed() matched_dict = {} result = [] # list to store node indices that have no concept match no_word_match = [] for i, candidates in enumerate(candidate_mapping): if not candidates: # no possible mapping result.append(-1) continue #...
def smart_init_mapping(candidate_mapping, instance1, instance2)
Initialize mapping based on the concept mapping (smart initialization) Arguments: candidate_mapping: candidate node match list instance1: instance triples of AMR 1 instance2: instance triples of AMR 2 Returns: initialized node mapping between two AMRs
3.502184
3.163162
1.107178
# if needed, a fixed seed could be passed here to generate same random (to help debugging) random.seed() matched_dict = {} result = [] for c in candidate_mapping: candidates = list(c) if not candidates: # -1 indicates no possible mapping result.append(-1)...
def random_init_mapping(candidate_mapping)
Generate a random node mapping. Args: candidate_mapping: candidate_mapping: candidate node match list Returns: randomly-generated node mapping between two AMRs
3.643041
3.706006
0.98301
# If this mapping has been investigated before, retrieve the value instead of re-computing. if veryVerbose: print("Computing match for mapping", file=DEBUG_LOG) print(mapping, file=DEBUG_LOG) if tuple(mapping) in match_triple_dict: if veryVerbose: print("saved value"...
def compute_match(mapping, weight_dict)
Given a node mapping, compute match number based on weight_dict. Args: mappings: a list of node index in AMR 2. The ith element (value j) means node i in AMR 1 maps to node j in AMR 2. Returns: matching triple number Complexity: O(m*n) , m is the node number of AMR 1, n is the node number of AMR 2
3.052362
2.840244
1.074683
# new node mapping after moving new_mapping = (node_id, new_id) # node mapping before moving old_mapping = (node_id, old_id) # new nodes mapping list (all node pairs) new_mapping_list = mapping[:] new_mapping_list[node_id] = new_id # if this mapping is already been investigated, use...
def move_gain(mapping, node_id, old_id, new_id, weight_dict, match_num)
Compute the triple match number gain from the move operation Arguments: mapping: current node mapping node_id: remapped node in AMR 1 old_id: original node id in AMR 2 to which node_id is mapped new_id: new node in to which node_id is mapped weight_dict: weight dictionary ...
3.147121
3.046586
1.032999
new_mapping_list = mapping[:] # Before swapping, node_id1 maps to mapping_id1, and node_id2 maps to mapping_id2 # After swapping, node_id1 maps to mapping_id2 and node_id2 maps to mapping_id1 new_mapping_list[node_id1] = mapping_id2 new_mapping_list[node_id2] = mapping_id1 if tuple(new_mapp...
def swap_gain(mapping, node_id1, mapping_id1, node_id2, mapping_id2, weight_dict, match_num)
Compute the triple match number gain from the swapping Arguments: mapping: current node mapping list node_id1: node 1 index in AMR 1 mapping_id1: the node index in AMR 2 node 1 maps to (in the current mapping) node_id2: node 2 index in AMR 1 mapping_id2: the node index in AMR 2 node 2 maps to (i...
1.511797
1.482313
1.019891
result = [] for instance1_item, m in zip(instance1, mapping): r = instance1_item[1] + "(" + instance1_item[2] + ")" if m == -1: r += "-Null" else: instance2_item = instance2[m] r += "-" + instance2_item[1] + "(" + instance2_item[2] + ")" r...
def print_alignment(mapping, instance1, instance2)
print the alignment based on a node mapping Args: mapping: current node mapping list instance1: nodes of AMR 1 instance2: nodes of AMR 2
2.73899
2.722974
1.005882
if test_num == 0 or gold_num == 0: return 0.00, 0.00, 0.00 precision = float(match_num) / float(test_num) recall = float(match_num) / float(gold_num) if (precision + recall) != 0: f_score = 2 * precision * recall / (precision + recall) if veryVerbose: print("F-sc...
def compute_f(match_num, test_num, gold_num)
Compute the f-score based on the matching triple number, triple number of AMR set 1, triple number of AMR set 2 Args: match_num: matching triple number test_num: triple number of AMR 1 (test file) gold_num: triple number of ...
2.00505
2.060752
0.97297
while True: cur_amr1 = amr.AMR.get_amr_line(f1) cur_amr2 = amr.AMR.get_amr_line(f2) if not cur_amr1 and not cur_amr2: pass elif not cur_amr1: print("Error: File 1 has less AMRs than file 2", file=ERROR_LOG) print("Ignoring remaining AMRs", fil...
def generate_amr_lines(f1, f2)
Read one AMR line at a time from each file handle :param f1: file handle (or any iterable of strings) to read AMR 1 lines from :param f2: file handle (or any iterable of strings) to read AMR 2 lines from :return: generator of cur_amr1, cur_amr2 pairs: one-line AMR strings
2.106616
2.020508
1.042617
# matching triple number, triple number in test file, triple number in gold file total_match_num = total_test_num = total_gold_num = 0 # Read amr pairs from two files for sent_num, (cur_amr1, cur_amr2) in enumerate(generate_amr_lines(f1, f2), start=1): best_match_num, test_triple_num, gold_...
def score_amr_pairs(f1, f2, justinstance=False, justattribute=False, justrelation=False)
Score one pair of AMR lines at a time from each file handle :param f1: file handle (or any iterable of strings) to read AMR 1 lines from :param f2: file handle (or any iterable of strings) to read AMR 2 lines from :param justinstance: just pay attention to matching instances :param justattribute: just p...
3.215518
3.118084
1.031248
global verbose global veryVerbose global iteration_num global single_score global pr_flag global match_triple_dict # set the iteration number # total iteration number = restart number + 1 iteration_num = arguments.r + 1 if arguments.ms: single_score = False if ar...
def main(arguments)
Main function of smatch score calculation
5.336418
5.145511
1.037102
'''convert volume metadata from es to archivant format This function makes side effect on input volume output example:: { 'id': 'AU0paPZOMZchuDv1iDv8', 'type': 'volume', 'metadata': {'_language': 'en', ...
def normalize_volume(volume)
convert volume metadata from es to archivant format This function makes side effect on input volume output example:: { 'id': 'AU0paPZOMZchuDv1iDv8', 'type': 'volume', 'metadata': {'_language': 'en', 'key1': ...
7.473595
1.52546
4.89924
''' Convert attachment metadata from es to archivant format This function makes side effect on input attachment ''' res = dict() res['type'] = 'attachment' res['id'] = attachment['id'] del(attachment['id']) res['url'] = attachment['url'] del(a...
def normalize_attachment(attachment)
Convert attachment metadata from es to archivant format This function makes side effect on input attachment
6.897736
2.856177
2.415024
'''convert volume metadata from archivant to es format''' id = volume.get('id', None) res = dict() res.update(volume['metadata']) denorm_attachments = list() for a in volume['attachments']: denorm_attachments.append(Archivant.denormalize_attachment(a)) ...
def denormalize_volume(volume)
convert volume metadata from archivant to es format
7.433531
3.946831
1.883418
'''convert attachment metadata from archivant to es format''' res = dict() ext = ['id', 'url'] for k in ext: if k in attachment['metadata']: raise ValueError("metadata section could not contain special key '{}'".format(k)) res[k] = attachment[k] ...
def denormalize_attachment(attachment)
convert attachment metadata from archivant to es format
10.744715
5.750843
1.868372
'''iterate over all stored volumes''' for raw_volume in self._db.iterate_all(): v = self.normalize_volume(raw_volume) del v['score'] yield v
def iter_all_volumes(self)
iterate over all stored volumes
8.924143
8.394923
1.06304
''' delete attachments from a volume ''' log.debug("deleting attachments from volume '{}': {}".format(volumeID, attachmentsID)) rawVolume = self._req_raw_volume(volumeID) insID = [a['id'] for a in rawVolume['_source']['_attachments']] # check that all requested file are present ...
def delete_attachments(self, volumeID, attachmentsID)
delete attachments from a volume
4.680437
5.001624
0.935784
''' add attachments to an already existing volume ''' log.debug("adding new attachments to volume '{}': {}".format(volumeID, attachments)) if not attachments: return rawVolume = self._req_raw_volume(volumeID) attsID = list() for index, a in enumerate(attachmen...
def insert_attachments(self, volumeID, attachments)
add attachments to an already existing volume
5.277611
5.290184
0.997623
'''Insert a new volume Returns the ID of the added volume `metadata` must be a dict containg metadata of the volume:: { "_language" : "it", # language of the metadata "key1" : "value1", # attribute "key2" : "value2", ... ...
def insert_volume(self, metadata, attachments=[])
Insert a new volume Returns the ID of the added volume `metadata` must be a dict containg metadata of the volume:: { "_language" : "it", # language of the metadata "key1" : "value1", # attribute "key2" : "value2", ... ...
4.567962
2.083521
2.192424
''' store file and return a dict containing assembled metadata param `file` must be a path or a File Object param `metadata` must be a dict: { "name" : "nome_buffo.ext" # name of the file (extension included) [optional if a path was given] ...
def _assemble_attachment(self, file, metadata)
store file and return a dict containing assembled metadata param `file` must be a path or a File Object param `metadata` must be a dict: { "name" : "nome_buffo.ext" # name of the file (extension included) [optional if a path was given] ...
3.066866
1.990608
1.540668
'''update existing volume metadata the given metadata will substitute the old one ''' log.debug('updating volume metadata: {}'.format(volumeID)) rawVolume = self._req_raw_volume(volumeID) normalized = self.normalize_volume(rawVolume) normalized['metadata'] = me...
def update_volume(self, volumeID, metadata)
update existing volume metadata the given metadata will substitute the old one
7.092243
5.00126
1.418091
'''update an existing attachment the given metadata dict will be merged with the old one. only the following fields could be updated: [name, mime, notes, download_count] ''' log.debug('updating metadata of attachment {} from volume {}'.format(attachmentID, volumeID)) ...
def update_attachment(self, volumeID, attachmentID, metadata)
update an existing attachment the given metadata dict will be merged with the old one. only the following fields could be updated: [name, mime, notes, download_count]
2.93428
2.26253
1.296902
'''iterate over fsdb files no more attached to any volume''' for fid in self._fsdb: if not self._db.file_is_attached('fsdb:///' + fid): yield fid
def dangling_files(self)
iterate over fsdb files no more attached to any volume
15.707922
6.43059
2.442688
'''shrink local fsdb by removing dangling and/or corrupted files return number of deleted files ''' log.debug('shrinking local fsdb [danglings={}, corrupted={}]'.format(dangling, corrupted)) count = 0 if dangling: for fid in self.dangling_files(): ...
def shrink_local_fsdb(self, dangling=True, corrupted=True, dryrun=False)
shrink local fsdb by removing dangling and/or corrupted files return number of deleted files
2.772475
2.394987
1.157616
length = _UNPACK_INT(data[position:position + 4])[0] position += 4 if length < 1 or obj_end - position < length: raise InvalidBSON("invalid string length") end = position + length - 1 if data[end:end + 1] != b"\x00": raise InvalidBSON("invalid end of string") return _utf_8_d...
def _get_string(data, position, obj_end, dummy)
Decode a BSON string to python unicode string.
3.048703
2.655957
1.147874
obj_size = _UNPACK_INT(data[position:position + 4])[0] end = position + obj_size - 1 if data[end:position + obj_size] != b"\x00": raise InvalidBSON("bad eoo") if end >= obj_end: raise InvalidBSON("invalid object length") obj = _elements_to_dict(data, position + 4, end, opts, sub...
def _get_object(data, position, obj_end, opts)
Decode a BSON subdocument to opts.document_class or bson.dbref.DBRef.
4.305545
3.768788
1.142422
end = position + 1 return data[position:end] == b"\x01", end
def _get_boolean(data, position, dummy0, dummy1)
Decode a BSON true/false to python True/False.
5.056539
4.633036
1.091409
end = position + 8 millis = _UNPACK_LONG(data[position:end])[0] diff = ((millis % 1000) + 1000) % 1000 seconds = (millis - diff) / 1000 micros = diff * 1000 if opts.tz_aware: return EPOCH_AWARE + datetime.timedelta( seconds=seconds, microseconds=micros), end else: ...
def _get_date(data, position, dummy, opts)
Decode a BSON datetime to python datetime.datetime.
2.852115
2.643153
1.079058
code, position = _get_string(data, position + 4, obj_end, opts) scope, position = _get_object(data, position, obj_end, opts) return Code(code, scope), position
def _get_code_w_scope(data, position, obj_end, opts)
Decode a BSON code_w_scope to bson.code.Code.
3.027645
2.632243
1.150215
pattern, position = _get_c_string(data, position) bson_flags, position = _get_c_string(data, position) bson_re = Regex(pattern, bson_flags) return bson_re, position
def _get_regex(data, position, dummy0, dummy1)
Decode a BSON regex to bson.regex.Regex or a python pattern object.
4.739697
3.383706
1.400741
if type(opts.document_class) == tuple: result = opts.document_class[0](**opts.document_class[1]) if not subdocument else dict() else: result = opts.document_class() if not subdocument else dict() end = obj_end - 1 while position < end: (key, value, position) = _element_to_di...
def _elements_to_dict(data, position, obj_end, opts, subdocument=None)
Decode a BSON document.
2.496726
2.33623
1.068699
try: obj_size = _UNPACK_INT(data[:4])[0] except struct.error as exc: raise InvalidBSON(str(exc)) if obj_size != len(data): raise InvalidBSON("invalid object size") if data[obj_size - 1:obj_size] != b"\x00": raise InvalidBSON("bad eoo") try: return _elemen...
def _bson_to_dict(data, opts)
Decode a BSON string to document_class.
3.411101
3.308823
1.03091
data = b"".join([_element_to_bson(key, val, check_keys, opts) for key, val in iteritems(value)]) return b"\x03" + name + _PACK_INT(len(data) + 5) + data + b"\x00"
def _encode_mapping(name, value, check_keys, opts)
Encode a mapping type.
4.567817
4.330404
1.054825
if value.utcoffset() is not None: value = value - value.utcoffset() millis = int(calendar.timegm(value.timetuple()) * 1000 + value.microsecond / 1000) return b"\x09" + name + _PACK_LONG(millis)
def _encode_datetime(name, value, dummy0, dummy1)
Encode datetime.datetime.
2.811082
2.649406
1.061023
cstring = _make_c_string(value) cstrlen = len(cstring) if not value.scope: return b"\x0D" + name + _PACK_INT(cstrlen) + cstring scope = _dict_to_bson(value.scope, False, opts, False) full_length = _PACK_INT(8 + cstrlen + len(scope)) return b"\x0F" + name + full_length + _PACK_INT(cs...
def _encode_code(name, value, dummy, opts)
Encode bson.code.Code.
4.834534
4.255992
1.135936
# remove initial slash if present res = re.sub('^/', '', sim) res = re.sub('/$', '', res) return '^/?' + re.sub('\*', '[^/]+', res) + '/?$'
def simToReg(self, sim)
Convert simplified domain expression to regular expression
6.79434
5.686529
1.194813
return self.match_domain(dom) and self.match_action(act)
def match(self, dom, act)
Check if the given `domain` and `act` are allowed by this capability
4.561104
4.31143
1.05791
'''convert an actions bitmask into a list of action strings''' res = [] for a in self.__class__.ACTIONS: aBit = self.__class__.action_bitmask(a) if ((self & aBit) == aBit): res.append(a) return res
def to_list(self)
convert an actions bitmask into a list of action strings
5.820374
3.79263
1.534654
'''convert list of actions into the corresponding bitmask''' bitmask = 0 for a in actions: bitmask |= cls.action_bitmask(a) return Action(bitmask)
def from_list(cls, actions)
convert list of actions into the corresponding bitmask
5.700612
3.997845
1.425921
return { "overview": { "activity_metrics": [Commits], "author_metrics": [Authors], "bmi_metrics": [], "time_to_close_metrics": [], "projects_metrics": [Projects] }, "com_channels": { ...
def get_section_metrics(cls)
Get the mapping between metrics and sections in Manuscripts report :return: a dict with the mapping between metrics and sections in Manuscripts report
4.635249
4.594024
1.008974
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
def str_val(val)
Format the value of a metric value to a string :param val: number to be formatted :return: a string with the formatted value
2.481317
2.730498
0.908741
'''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))
def load_cfg(path, envvar_prefix='LIBREANT_', debug=False)
wrapper of config_utils.load_configs
5.471734
3.694881
1.480896
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
def files_in_subdir(dir, subdir)
Find all files in a directory.
1.801622
1.843897
0.977073
results = { "activity_metrics": [Commits(index, start, end)], "author_metrics": [Authors(index, start, end)], "bmi_metrics": [], "time_to_close_metrics": [], "projects_metrics": [] } return results
def overview(index, start, end)
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 ...
6.753586
7.475021
0.903487
results = { "metrics": [Commits(index, start, end), Authors(index, start, end)] } return results
def project_activity(index, start, end)
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 ...
9.206721
11.51268
0.799703
results = { "author_metrics": [Authors(index, start, end)], "people_top_metrics": [Authors(index, start, end)], "orgs_top_metrics": [Organizations(index, start, end)], } return results
def project_community(index, start, end)
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...
5.600917
3.285458
1.70476
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)
def aggregations(self)
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
10.971146
8.689159
1.262625
self.query.get_cardinality("author_uuid").by_period() return super().timeseries(dataframe)
def timeseries(self, dataframe=False)
Get the date histogram aggregations. :param dataframe: if true, return a pandas.DataFrame object
37.06102
40.09819
0.924257
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, start, end)], "projects_met...
def overview(index, start, end)
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 ...
5.560233
5.6811
0.978725
results = { "metrics": [OpenedIssues(index, start, end), ClosedIssues(index, start, end)] } return results
def project_activity(index, start, end)
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...
7.672846
9.769366
0.785399
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_metrics": [] } return results
def project_process(index, start, end)
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...
7.114673
2.950988
2.410946
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.opened.query.since(prev_m...
def aggregations(self)
Get the aggregation value for BMI with respect to the previous time interval.
6.592285
5.980192
1.102353
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) except AttributeError: buf.value = init return bu...
def create_string_buffer(init, size=None, encoding=sys.getdefaultencoding())
create_string_buffer(aString) -> character array create_string_buffer(anInteger) -> character array create_string_buffer(aString, anInteger) -> character array
2.136104
2.341892
0.912128
c_level = level level = LEVELS_F2PY[c_level] logger.log(level, message)
def c_log(level, message)
python logger to be called from fortran
7.557953
6.500824
1.162615
return {x: getattr(struct, x) for x in dict(struct._fields_).keys()}
def struct2dict(struct)
convert a ctypes structure to a dictionary
4.512785
4.681855
0.963888
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)
def structs2records(structs)
convert one or more structs and generate dictionaries
4.401617
4.410394
0.99801
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.dtypes == object] if '...
def structs2pandas(structs)
convert ctypes structure or structure array to pandas data frame
6.075104
6.19798
0.980175
@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.argtypes): ...
def wrap(func)
Return wrapped function with type conversion and sanity checks.
3.01277
2.926687
1.029413
prefix = 'lib' suffix = '.so' if platform.system() == 'Darwin': suffix = '.dylib' if platform.system() == 'Windows': prefix = '' suffix = '.dll' return prefix + self.engine + suffix
def _libname(self)
Return platform-specific modelf90 shared library name.
2.793499
2.469584
1.131162
# 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': pathname = 'DYLD_LIBRARY_P...
def _library_path(self)
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 ...
3.794141
3.722309
1.019298