id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
19,700
chaoss/grimoirelab-elk
grimoire_elk/utils.py
get_time_diff_days
def get_time_diff_days(start_txt, end_txt): ''' Number of days between two days ''' if start_txt is None or end_txt is None: return None start = parser.parse(start_txt) end = parser.parse(end_txt) seconds_day = float(60 * 60 * 24) diff_days = \ (end - start).total_seconds() / seconds_day diff_days = float('%.2f' % diff_days) return diff_days
python
def get_time_diff_days(start_txt, end_txt): ''' Number of days between two days ''' if start_txt is None or end_txt is None: return None start = parser.parse(start_txt) end = parser.parse(end_txt) seconds_day = float(60 * 60 * 24) diff_days = \ (end - start).total_seconds() / seconds_day diff_days = float('%.2f' % diff_days) return diff_days
[ "def", "get_time_diff_days", "(", "start_txt", ",", "end_txt", ")", ":", "if", "start_txt", "is", "None", "or", "end_txt", "is", "None", ":", "return", "None", "start", "=", "parser", ".", "parse", "(", "start_txt", ")", "end", "=", "parser", ".", "parse...
Number of days between two days
[ "Number", "of", "days", "between", "two", "days" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/utils.py#L391-L405
19,701
chaoss/grimoirelab-elk
grimoire_elk/enriched/jira.py
JiraEnrich.enrich_fields
def enrich_fields(cls, fields, eitem): """Enrich the fields property of an issue. Loops through al properties in issue['fields'], using those that are relevant to enrich eitem with new properties. Those properties are user defined, depending on options configured in Jira. For example, if SCRUM is activated, we have a field named "Story Points". :param fields: fields property of an issue :param eitem: enriched item, which will be modified adding more properties """ for field in fields: if field.startswith('customfield_'): if type(fields[field]) is dict: if 'name' in fields[field]: if fields[field]['name'] == "Story Points": eitem['story_points'] = fields[field]['value'] elif fields[field]['name'] == "Sprint": value = fields[field]['value'] if value: sprint = value[0].partition(",name=")[2].split(',')[0] sprint_start = value[0].partition(",startDate=")[2].split(',')[0] sprint_end = value[0].partition(",endDate=")[2].split(',')[0] sprint_complete = value[0].partition(",completeDate=")[2].split(',')[0] eitem['sprint'] = sprint eitem['sprint_start'] = cls.fix_value_null(sprint_start) eitem['sprint_end'] = cls.fix_value_null(sprint_end) eitem['sprint_complete'] = cls.fix_value_null(sprint_complete)
python
def enrich_fields(cls, fields, eitem): for field in fields: if field.startswith('customfield_'): if type(fields[field]) is dict: if 'name' in fields[field]: if fields[field]['name'] == "Story Points": eitem['story_points'] = fields[field]['value'] elif fields[field]['name'] == "Sprint": value = fields[field]['value'] if value: sprint = value[0].partition(",name=")[2].split(',')[0] sprint_start = value[0].partition(",startDate=")[2].split(',')[0] sprint_end = value[0].partition(",endDate=")[2].split(',')[0] sprint_complete = value[0].partition(",completeDate=")[2].split(',')[0] eitem['sprint'] = sprint eitem['sprint_start'] = cls.fix_value_null(sprint_start) eitem['sprint_end'] = cls.fix_value_null(sprint_end) eitem['sprint_complete'] = cls.fix_value_null(sprint_complete)
[ "def", "enrich_fields", "(", "cls", ",", "fields", ",", "eitem", ")", ":", "for", "field", "in", "fields", ":", "if", "field", ".", "startswith", "(", "'customfield_'", ")", ":", "if", "type", "(", "fields", "[", "field", "]", ")", "is", "dict", ":",...
Enrich the fields property of an issue. Loops through al properties in issue['fields'], using those that are relevant to enrich eitem with new properties. Those properties are user defined, depending on options configured in Jira. For example, if SCRUM is activated, we have a field named "Story Points". :param fields: fields property of an issue :param eitem: enriched item, which will be modified adding more properties
[ "Enrich", "the", "fields", "property", "of", "an", "issue", "." ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/jira.py#L197-L226
19,702
chaoss/grimoirelab-elk
grimoire_elk/enriched/mediawiki.py
MediaWikiEnrich.get_review_sh
def get_review_sh(self, revision, item): """ Add sorting hat enrichment fields for the author of the revision """ identity = self.get_sh_identity(revision) update = parser.parse(item[self.get_field_date()]) erevision = self.get_item_sh_fields(identity, update) return erevision
python
def get_review_sh(self, revision, item): identity = self.get_sh_identity(revision) update = parser.parse(item[self.get_field_date()]) erevision = self.get_item_sh_fields(identity, update) return erevision
[ "def", "get_review_sh", "(", "self", ",", "revision", ",", "item", ")", ":", "identity", "=", "self", ".", "get_sh_identity", "(", "revision", ")", "update", "=", "parser", ".", "parse", "(", "item", "[", "self", ".", "get_field_date", "(", ")", "]", "...
Add sorting hat enrichment fields for the author of the revision
[ "Add", "sorting", "hat", "enrichment", "fields", "for", "the", "author", "of", "the", "revision" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/mediawiki.py#L109-L116
19,703
chaoss/grimoirelab-elk
grimoire_elk/enriched/github.py
GitHubEnrich.get_github_cache
def get_github_cache(self, kind, key_): """ Get cache data for items of _type using key_ as the cache dict key """ cache = {} res_size = 100 # best size? from_ = 0 index_github = "github/" + kind url = self.elastic.url + "/" + index_github url += "/_search" + "?" + "size=%i" % res_size r = self.requests.get(url) type_items = r.json() if 'hits' not in type_items: logger.info("No github %s data in ES" % (kind)) else: while len(type_items['hits']['hits']) > 0: for hit in type_items['hits']['hits']: item = hit['_source'] cache[item[key_]] = item from_ += res_size r = self.requests.get(url + "&from=%i" % from_) type_items = r.json() if 'hits' not in type_items: break return cache
python
def get_github_cache(self, kind, key_): cache = {} res_size = 100 # best size? from_ = 0 index_github = "github/" + kind url = self.elastic.url + "/" + index_github url += "/_search" + "?" + "size=%i" % res_size r = self.requests.get(url) type_items = r.json() if 'hits' not in type_items: logger.info("No github %s data in ES" % (kind)) else: while len(type_items['hits']['hits']) > 0: for hit in type_items['hits']['hits']: item = hit['_source'] cache[item[key_]] = item from_ += res_size r = self.requests.get(url + "&from=%i" % from_) type_items = r.json() if 'hits' not in type_items: break return cache
[ "def", "get_github_cache", "(", "self", ",", "kind", ",", "key_", ")", ":", "cache", "=", "{", "}", "res_size", "=", "100", "# best size?", "from_", "=", "0", "index_github", "=", "\"github/\"", "+", "kind", "url", "=", "self", ".", "elastic", ".", "ur...
Get cache data for items of _type using key_ as the cache dict key
[ "Get", "cache", "data", "for", "items", "of", "_type", "using", "key_", "as", "the", "cache", "dict", "key" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/github.py#L194-L222
19,704
chaoss/grimoirelab-elk
grimoire_elk/enriched/github.py
GitHubEnrich.get_time_to_first_attention
def get_time_to_first_attention(self, item): """Get the first date at which a comment or reaction was made to the issue by someone other than the user who created the issue """ comment_dates = [str_to_datetime(comment['created_at']) for comment in item['comments_data'] if item['user']['login'] != comment['user']['login']] reaction_dates = [str_to_datetime(reaction['created_at']) for reaction in item['reactions_data'] if item['user']['login'] != reaction['user']['login']] reaction_dates.extend(comment_dates) if reaction_dates: return min(reaction_dates) return None
python
def get_time_to_first_attention(self, item): comment_dates = [str_to_datetime(comment['created_at']) for comment in item['comments_data'] if item['user']['login'] != comment['user']['login']] reaction_dates = [str_to_datetime(reaction['created_at']) for reaction in item['reactions_data'] if item['user']['login'] != reaction['user']['login']] reaction_dates.extend(comment_dates) if reaction_dates: return min(reaction_dates) return None
[ "def", "get_time_to_first_attention", "(", "self", ",", "item", ")", ":", "comment_dates", "=", "[", "str_to_datetime", "(", "comment", "[", "'created_at'", "]", ")", "for", "comment", "in", "item", "[", "'comments_data'", "]", "if", "item", "[", "'user'", "...
Get the first date at which a comment or reaction was made to the issue by someone other than the user who created the issue
[ "Get", "the", "first", "date", "at", "which", "a", "comment", "or", "reaction", "was", "made", "to", "the", "issue", "by", "someone", "other", "than", "the", "user", "who", "created", "the", "issue" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/github.py#L267-L278
19,705
chaoss/grimoirelab-elk
grimoire_elk/enriched/github.py
GitHubEnrich.get_time_to_merge_request_response
def get_time_to_merge_request_response(self, item): """Get the first date at which a review was made on the PR by someone other than the user who created the PR """ review_dates = [str_to_datetime(review['created_at']) for review in item['review_comments_data'] if item['user']['login'] != review['user']['login']] if review_dates: return min(review_dates) return None
python
def get_time_to_merge_request_response(self, item): review_dates = [str_to_datetime(review['created_at']) for review in item['review_comments_data'] if item['user']['login'] != review['user']['login']] if review_dates: return min(review_dates) return None
[ "def", "get_time_to_merge_request_response", "(", "self", ",", "item", ")", ":", "review_dates", "=", "[", "str_to_datetime", "(", "review", "[", "'created_at'", "]", ")", "for", "review", "in", "item", "[", "'review_comments_data'", "]", "if", "item", "[", "'...
Get the first date at which a review was made on the PR by someone other than the user who created the PR
[ "Get", "the", "first", "date", "at", "which", "a", "review", "was", "made", "on", "the", "PR", "by", "someone", "other", "than", "the", "user", "who", "created", "the", "PR" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/github.py#L280-L288
19,706
chaoss/grimoirelab-elk
grimoire_elk/enriched/crates.py
CratesEnrich.get_rich_events
def get_rich_events(self, item): """ In the events there are some common fields with the crate. The name of the field must be the same in the create and in the downloads event so we can filer using it in crate and event at the same time. * Fields that don't change: the field does not change with the events in a create so the value is always the same in the events of a create. * Fields that change: the value of the field changes with events """ if "version_downloads_data" not in item['data']: return [] # To get values from the task eitem = self.get_rich_item(item) for sample in item['data']["version_downloads_data"]["version_downloads"]: event = deepcopy(eitem) event['download_sample_id'] = sample['id'] event['sample_date'] = sample['date'] sample_date = parser.parse(event['sample_date']) event['sample_version'] = sample['version'] event['sample_downloads'] = sample['downloads'] event.update(self.get_grimoire_fields(sample_date.isoformat(), "downloads_event")) yield event
python
def get_rich_events(self, item): if "version_downloads_data" not in item['data']: return [] # To get values from the task eitem = self.get_rich_item(item) for sample in item['data']["version_downloads_data"]["version_downloads"]: event = deepcopy(eitem) event['download_sample_id'] = sample['id'] event['sample_date'] = sample['date'] sample_date = parser.parse(event['sample_date']) event['sample_version'] = sample['version'] event['sample_downloads'] = sample['downloads'] event.update(self.get_grimoire_fields(sample_date.isoformat(), "downloads_event")) yield event
[ "def", "get_rich_events", "(", "self", ",", "item", ")", ":", "if", "\"version_downloads_data\"", "not", "in", "item", "[", "'data'", "]", ":", "return", "[", "]", "# To get values from the task", "eitem", "=", "self", ".", "get_rich_item", "(", "item", ")", ...
In the events there are some common fields with the crate. The name of the field must be the same in the create and in the downloads event so we can filer using it in crate and event at the same time. * Fields that don't change: the field does not change with the events in a create so the value is always the same in the events of a create. * Fields that change: the value of the field changes with events
[ "In", "the", "events", "there", "are", "some", "common", "fields", "with", "the", "crate", ".", "The", "name", "of", "the", "field", "must", "be", "the", "same", "in", "the", "create", "and", "in", "the", "downloads", "event", "so", "we", "can", "filer...
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/crates.py#L99-L125
19,707
chaoss/grimoirelab-elk
grimoire_elk/enriched/twitter.py
TwitterEnrich.get_item_project
def get_item_project(self, eitem): """ Get project mapping enrichment field. Twitter mappings is pretty special so it needs a special implementacion. """ project = None eitem_project = {} ds_name = self.get_connector_name() # data source name in projects map if ds_name not in self.prjs_map: return eitem_project for tag in eitem['hashtags_analyzed']: # lcanas: hashtag provided in projects.json file should not be case sensitive T6876 tags2project = CaseInsensitiveDict(self.prjs_map[ds_name]) if tag in tags2project: project = tags2project[tag] break if project is None: project = DEFAULT_PROJECT eitem_project = {"project": project} eitem_project.update(self.add_project_levels(project)) return eitem_project
python
def get_item_project(self, eitem): project = None eitem_project = {} ds_name = self.get_connector_name() # data source name in projects map if ds_name not in self.prjs_map: return eitem_project for tag in eitem['hashtags_analyzed']: # lcanas: hashtag provided in projects.json file should not be case sensitive T6876 tags2project = CaseInsensitiveDict(self.prjs_map[ds_name]) if tag in tags2project: project = tags2project[tag] break if project is None: project = DEFAULT_PROJECT eitem_project = {"project": project} eitem_project.update(self.add_project_levels(project)) return eitem_project
[ "def", "get_item_project", "(", "self", ",", "eitem", ")", ":", "project", "=", "None", "eitem_project", "=", "{", "}", "ds_name", "=", "self", ".", "get_connector_name", "(", ")", "# data source name in projects map", "if", "ds_name", "not", "in", "self", "."...
Get project mapping enrichment field. Twitter mappings is pretty special so it needs a special implementacion.
[ "Get", "project", "mapping", "enrichment", "field", "." ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/twitter.py#L93-L121
19,708
chaoss/grimoirelab-elk
grimoire_elk/enriched/jenkins.py
JenkinsEnrich.get_fields_from_job_name
def get_fields_from_job_name(self, job_name): """Analyze a Jenkins job name, producing a dictionary The produced dictionary will include information about the category and subcategory of the job name, and any extra information which could be useful. For each deployment of a Jenkins dashboard, an implementation of this function should be produced, according to the needs of the users. :param job: job name to Analyze :returns: dictionary with categorization information """ extra_fields = { 'category': None, 'installer': None, 'scenario': None, 'testproject': None, 'pod': None, 'loop': None, 'branch': None } try: components = job_name.split('-') if len(components) < 2: return extra_fields kind = components[1] if kind == 'os': extra_fields['category'] = 'parent/main' extra_fields['installer'] = components[0] extra_fields['scenario'] = '-'.join(components[2:-3]) elif kind == 'deploy': extra_fields['category'] = 'deploy' extra_fields['installer'] = components[0] else: extra_fields['category'] = 'test' extra_fields['testproject'] = components[0] extra_fields['installer'] = components[1] extra_fields['pod'] = components[-3] extra_fields['loop'] = components[-2] extra_fields['branch'] = components[-1] except IndexError as ex: # Just DEBUG level because it is just for OPNFV logger.debug('Problems parsing job name %s', job_name) logger.debug(ex) return extra_fields
python
def get_fields_from_job_name(self, job_name): extra_fields = { 'category': None, 'installer': None, 'scenario': None, 'testproject': None, 'pod': None, 'loop': None, 'branch': None } try: components = job_name.split('-') if len(components) < 2: return extra_fields kind = components[1] if kind == 'os': extra_fields['category'] = 'parent/main' extra_fields['installer'] = components[0] extra_fields['scenario'] = '-'.join(components[2:-3]) elif kind == 'deploy': extra_fields['category'] = 'deploy' extra_fields['installer'] = components[0] else: extra_fields['category'] = 'test' extra_fields['testproject'] = components[0] extra_fields['installer'] = components[1] extra_fields['pod'] = components[-3] extra_fields['loop'] = components[-2] extra_fields['branch'] = components[-1] except IndexError as ex: # Just DEBUG level because it is just for OPNFV logger.debug('Problems parsing job name %s', job_name) logger.debug(ex) return extra_fields
[ "def", "get_fields_from_job_name", "(", "self", ",", "job_name", ")", ":", "extra_fields", "=", "{", "'category'", ":", "None", ",", "'installer'", ":", "None", ",", "'scenario'", ":", "None", ",", "'testproject'", ":", "None", ",", "'pod'", ":", "None", "...
Analyze a Jenkins job name, producing a dictionary The produced dictionary will include information about the category and subcategory of the job name, and any extra information which could be useful. For each deployment of a Jenkins dashboard, an implementation of this function should be produced, according to the needs of the users. :param job: job name to Analyze :returns: dictionary with categorization information
[ "Analyze", "a", "Jenkins", "job", "name", "producing", "a", "dictionary" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/jenkins.py#L122-L174
19,709
chaoss/grimoirelab-elk
grimoire_elk/enriched/jenkins.py
JenkinsEnrich.extract_builton
def extract_builton(self, built_on, regex): """Extracts node name using a regular expression. Node name is expected to be group 1. """ pattern = re.compile(regex, re.M | re.I) match = pattern.search(built_on) if match and len(match.groups()) >= 1: node_name = match.group(1) else: msg = "Node name not extracted, using builtOn as it is: " + regex + ":" + built_on logger.warning(msg) node_name = built_on return node_name
python
def extract_builton(self, built_on, regex): pattern = re.compile(regex, re.M | re.I) match = pattern.search(built_on) if match and len(match.groups()) >= 1: node_name = match.group(1) else: msg = "Node name not extracted, using builtOn as it is: " + regex + ":" + built_on logger.warning(msg) node_name = built_on return node_name
[ "def", "extract_builton", "(", "self", ",", "built_on", ",", "regex", ")", ":", "pattern", "=", "re", ".", "compile", "(", "regex", ",", "re", ".", "M", "|", "re", ".", "I", ")", "match", "=", "pattern", ".", "search", "(", "built_on", ")", "if", ...
Extracts node name using a regular expression. Node name is expected to be group 1.
[ "Extracts", "node", "name", "using", "a", "regular", "expression", ".", "Node", "name", "is", "expected", "to", "be", "group", "1", "." ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/jenkins.py#L176-L189
19,710
chaoss/grimoirelab-elk
grimoire_elk/enriched/study_ceres_onion.py
onion_study
def onion_study(in_conn, out_conn, data_source): """Build and index for onion from a given Git index. :param in_conn: ESPandasConnector to read from. :param out_conn: ESPandasConnector to write to. :param data_source: name of the date source to generate onion from. :return: number of documents written in ElasticSearch enriched index. """ onion = OnionStudy(in_connector=in_conn, out_connector=out_conn, data_source=data_source) ndocs = onion.analyze() return ndocs
python
def onion_study(in_conn, out_conn, data_source): onion = OnionStudy(in_connector=in_conn, out_connector=out_conn, data_source=data_source) ndocs = onion.analyze() return ndocs
[ "def", "onion_study", "(", "in_conn", ",", "out_conn", ",", "data_source", ")", ":", "onion", "=", "OnionStudy", "(", "in_connector", "=", "in_conn", ",", "out_connector", "=", "out_conn", ",", "data_source", "=", "data_source", ")", "ndocs", "=", "onion", "...
Build and index for onion from a given Git index. :param in_conn: ESPandasConnector to read from. :param out_conn: ESPandasConnector to write to. :param data_source: name of the date source to generate onion from. :return: number of documents written in ElasticSearch enriched index.
[ "Build", "and", "index", "for", "onion", "from", "a", "given", "Git", "index", "." ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/study_ceres_onion.py#L371-L381
19,711
chaoss/grimoirelab-elk
grimoire_elk/enriched/study_ceres_onion.py
ESOnionConnector.read_block
def read_block(self, size=None, from_date=None): """Read author commits by Quarter, Org and Project. :param from_date: not used here. Incremental mode not supported yet. :param size: not used here. :return: DataFrame with commit count per author, split by quarter, org and project. """ # Get quarters corresponding to All items (Incremental mode NOT SUPPORTED) quarters = self.__quarters() for quarter in quarters: logger.info(self.__log_prefix + " Quarter: " + str(quarter)) date_range = {self._timeframe_field: {'gte': quarter.start_time, 'lte': quarter.end_time}} orgs = self.__list_uniques(date_range, self.AUTHOR_ORG) projects = self.__list_uniques(date_range, self.PROJECT) # Get global data s = self.__build_search(date_range) response = s.execute() for timing in response.aggregations[self.TIMEFRAME].buckets: yield self.__build_dataframe(timing).copy() # Get global data by Org for org_name in orgs: logger.info(self.__log_prefix + " Quarter: " + str(quarter) + " Org: " + org_name) s = self.__build_search(date_range, org_name=org_name) response = s.execute() for timing in response.aggregations[self.TIMEFRAME].buckets: yield self.__build_dataframe(timing, org_name=org_name).copy() # Get project specific data for project in projects: logger.info(self.__log_prefix + " Quarter: " + str(quarter) + " Project: " + project) # Global project s = self.__build_search(date_range, project_name=project) response = s.execute() for timing in response.aggregations[self.TIMEFRAME].buckets: yield self.__build_dataframe(timing, project_name=project).copy() # Split by Org for org_name in orgs: logger.info(self.__log_prefix + " Quarter: " + str(quarter) + " Project: " + project + " Org: " + org_name) s = self.__build_search(date_range, project_name=project, org_name=org_name) response = s.execute() for timing in response.aggregations[self.TIMEFRAME].buckets: yield self.__build_dataframe(timing, project_name=project, org_name=org_name).copy()
python
def read_block(self, size=None, from_date=None): # Get quarters corresponding to All items (Incremental mode NOT SUPPORTED) quarters = self.__quarters() for quarter in quarters: logger.info(self.__log_prefix + " Quarter: " + str(quarter)) date_range = {self._timeframe_field: {'gte': quarter.start_time, 'lte': quarter.end_time}} orgs = self.__list_uniques(date_range, self.AUTHOR_ORG) projects = self.__list_uniques(date_range, self.PROJECT) # Get global data s = self.__build_search(date_range) response = s.execute() for timing in response.aggregations[self.TIMEFRAME].buckets: yield self.__build_dataframe(timing).copy() # Get global data by Org for org_name in orgs: logger.info(self.__log_prefix + " Quarter: " + str(quarter) + " Org: " + org_name) s = self.__build_search(date_range, org_name=org_name) response = s.execute() for timing in response.aggregations[self.TIMEFRAME].buckets: yield self.__build_dataframe(timing, org_name=org_name).copy() # Get project specific data for project in projects: logger.info(self.__log_prefix + " Quarter: " + str(quarter) + " Project: " + project) # Global project s = self.__build_search(date_range, project_name=project) response = s.execute() for timing in response.aggregations[self.TIMEFRAME].buckets: yield self.__build_dataframe(timing, project_name=project).copy() # Split by Org for org_name in orgs: logger.info(self.__log_prefix + " Quarter: " + str(quarter) + " Project: " + project + " Org: " + org_name) s = self.__build_search(date_range, project_name=project, org_name=org_name) response = s.execute() for timing in response.aggregations[self.TIMEFRAME].buckets: yield self.__build_dataframe(timing, project_name=project, org_name=org_name).copy()
[ "def", "read_block", "(", "self", ",", "size", "=", "None", ",", "from_date", "=", "None", ")", ":", "# Get quarters corresponding to All items (Incremental mode NOT SUPPORTED)", "quarters", "=", "self", ".", "__quarters", "(", ")", "for", "quarter", "in", "quarters...
Read author commits by Quarter, Org and Project. :param from_date: not used here. Incremental mode not supported yet. :param size: not used here. :return: DataFrame with commit count per author, split by quarter, org and project.
[ "Read", "author", "commits", "by", "Quarter", "Org", "and", "Project", "." ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/study_ceres_onion.py#L72-L131
19,712
chaoss/grimoirelab-elk
grimoire_elk/enriched/study_ceres_onion.py
ESOnionConnector.__quarters
def __quarters(self, from_date=None): """Get a set of quarters with available items from a given index date. :param from_date: :return: list of `pandas.Period` corresponding to quarters """ s = Search(using=self._es_conn, index=self._es_index) if from_date: # Work around to solve conversion problem of '__' to '.' in field name q = Q('range') q.__setattr__(self._sort_on_field, {'gte': from_date}) s = s.filter(q) # from:to parameters (=> from: 0, size: 0) s = s[0:0] s.aggs.bucket(self.TIMEFRAME, 'date_histogram', field=self._timeframe_field, interval='quarter', min_doc_count=1) response = s.execute() quarters = [] for quarter in response.aggregations[self.TIMEFRAME].buckets: period = pandas.Period(quarter.key_as_string, 'Q') quarters.append(period) return quarters
python
def __quarters(self, from_date=None): s = Search(using=self._es_conn, index=self._es_index) if from_date: # Work around to solve conversion problem of '__' to '.' in field name q = Q('range') q.__setattr__(self._sort_on_field, {'gte': from_date}) s = s.filter(q) # from:to parameters (=> from: 0, size: 0) s = s[0:0] s.aggs.bucket(self.TIMEFRAME, 'date_histogram', field=self._timeframe_field, interval='quarter', min_doc_count=1) response = s.execute() quarters = [] for quarter in response.aggregations[self.TIMEFRAME].buckets: period = pandas.Period(quarter.key_as_string, 'Q') quarters.append(period) return quarters
[ "def", "__quarters", "(", "self", ",", "from_date", "=", "None", ")", ":", "s", "=", "Search", "(", "using", "=", "self", ".", "_es_conn", ",", "index", "=", "self", ".", "_es_index", ")", "if", "from_date", ":", "# Work around to solve conversion problem of...
Get a set of quarters with available items from a given index date. :param from_date: :return: list of `pandas.Period` corresponding to quarters
[ "Get", "a", "set", "of", "quarters", "with", "available", "items", "from", "a", "given", "index", "date", "." ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/study_ceres_onion.py#L214-L239
19,713
chaoss/grimoirelab-elk
grimoire_elk/enriched/study_ceres_onion.py
ESOnionConnector.__list_uniques
def __list_uniques(self, date_range, field_name): """Retrieve a list of unique values in a given field within a date range. :param date_range: :param field_name: :return: list of unique values. """ # Get project list s = Search(using=self._es_conn, index=self._es_index) s = s.filter('range', **date_range) # from:to parameters (=> from: 0, size: 0) s = s[0:0] s.aggs.bucket('uniques', 'terms', field=field_name, size=1000) response = s.execute() uniques_list = [] for item in response.aggregations.uniques.buckets: uniques_list.append(item.key) return uniques_list
python
def __list_uniques(self, date_range, field_name): # Get project list s = Search(using=self._es_conn, index=self._es_index) s = s.filter('range', **date_range) # from:to parameters (=> from: 0, size: 0) s = s[0:0] s.aggs.bucket('uniques', 'terms', field=field_name, size=1000) response = s.execute() uniques_list = [] for item in response.aggregations.uniques.buckets: uniques_list.append(item.key) return uniques_list
[ "def", "__list_uniques", "(", "self", ",", "date_range", ",", "field_name", ")", ":", "# Get project list", "s", "=", "Search", "(", "using", "=", "self", ".", "_es_conn", ",", "index", "=", "self", ".", "_es_index", ")", "s", "=", "s", ".", "filter", ...
Retrieve a list of unique values in a given field within a date range. :param date_range: :param field_name: :return: list of unique values.
[ "Retrieve", "a", "list", "of", "unique", "values", "in", "a", "given", "field", "within", "a", "date", "range", "." ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/study_ceres_onion.py#L241-L259
19,714
chaoss/grimoirelab-elk
grimoire_elk/enriched/study_ceres_onion.py
ESOnionConnector.__build_dataframe
def __build_dataframe(self, timing, project_name=None, org_name=None): """Build a DataFrame from a time bucket. :param timing: :param project_name: :param org_name: :return: """ date_list = [] uuid_list = [] name_list = [] contribs_list = [] latest_ts_list = [] logger.debug(self.__log_prefix + " timing: " + timing.key_as_string) for author in timing[self.AUTHOR_UUID].buckets: latest_ts_list.append(timing[self.LATEST_TS].value_as_string) date_list.append(timing.key_as_string) uuid_list.append(author.key) if author[self.AUTHOR_NAME] and author[self.AUTHOR_NAME].buckets \ and len(author[self.AUTHOR_NAME].buckets) > 0: name_list.append(author[self.AUTHOR_NAME].buckets[0].key) else: name_list.append("Unknown") contribs_list.append(author[self.CONTRIBUTIONS].value) df = pandas.DataFrame() df[self.TIMEFRAME] = date_list df[self.AUTHOR_UUID] = uuid_list df[self.AUTHOR_NAME] = name_list df[self.CONTRIBUTIONS] = contribs_list df[self.TIMESTAMP] = latest_ts_list if not project_name: project_name = "_Global_" df[self.PROJECT] = project_name if not org_name: org_name = "_Global_" df[self.AUTHOR_ORG] = org_name return df
python
def __build_dataframe(self, timing, project_name=None, org_name=None): date_list = [] uuid_list = [] name_list = [] contribs_list = [] latest_ts_list = [] logger.debug(self.__log_prefix + " timing: " + timing.key_as_string) for author in timing[self.AUTHOR_UUID].buckets: latest_ts_list.append(timing[self.LATEST_TS].value_as_string) date_list.append(timing.key_as_string) uuid_list.append(author.key) if author[self.AUTHOR_NAME] and author[self.AUTHOR_NAME].buckets \ and len(author[self.AUTHOR_NAME].buckets) > 0: name_list.append(author[self.AUTHOR_NAME].buckets[0].key) else: name_list.append("Unknown") contribs_list.append(author[self.CONTRIBUTIONS].value) df = pandas.DataFrame() df[self.TIMEFRAME] = date_list df[self.AUTHOR_UUID] = uuid_list df[self.AUTHOR_NAME] = name_list df[self.CONTRIBUTIONS] = contribs_list df[self.TIMESTAMP] = latest_ts_list if not project_name: project_name = "_Global_" df[self.PROJECT] = project_name if not org_name: org_name = "_Global_" df[self.AUTHOR_ORG] = org_name return df
[ "def", "__build_dataframe", "(", "self", ",", "timing", ",", "project_name", "=", "None", ",", "org_name", "=", "None", ")", ":", "date_list", "=", "[", "]", "uuid_list", "=", "[", "]", "name_list", "=", "[", "]", "contribs_list", "=", "[", "]", "lates...
Build a DataFrame from a time bucket. :param timing: :param project_name: :param org_name: :return:
[ "Build", "a", "DataFrame", "from", "a", "time", "bucket", "." ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/study_ceres_onion.py#L285-L326
19,715
chaoss/grimoirelab-elk
grimoire_elk/enriched/study_ceres_onion.py
OnionStudy.process
def process(self, items_block): """Process a DataFrame to compute Onion. :param items_block: items to be processed. Expects to find a pandas DataFrame. """ logger.info(self.__log_prefix + " Authors to process: " + str(len(items_block))) onion_enrich = Onion(items_block) df_onion = onion_enrich.enrich(member_column=ESOnionConnector.AUTHOR_UUID, events_column=ESOnionConnector.CONTRIBUTIONS) # Get and store Quarter as String df_onion['quarter'] = df_onion[ESOnionConnector.TIMEFRAME].map(lambda x: str(pandas.Period(x, 'Q'))) # Add metadata: enriched on timestamp df_onion['metadata__enriched_on'] = datetime.utcnow().isoformat() df_onion['data_source'] = self.data_source df_onion['grimoire_creation_date'] = df_onion[ESOnionConnector.TIMEFRAME] logger.info(self.__log_prefix + " Final new events: " + str(len(df_onion))) return self.ProcessResults(processed=len(df_onion), out_items=df_onion)
python
def process(self, items_block): logger.info(self.__log_prefix + " Authors to process: " + str(len(items_block))) onion_enrich = Onion(items_block) df_onion = onion_enrich.enrich(member_column=ESOnionConnector.AUTHOR_UUID, events_column=ESOnionConnector.CONTRIBUTIONS) # Get and store Quarter as String df_onion['quarter'] = df_onion[ESOnionConnector.TIMEFRAME].map(lambda x: str(pandas.Period(x, 'Q'))) # Add metadata: enriched on timestamp df_onion['metadata__enriched_on'] = datetime.utcnow().isoformat() df_onion['data_source'] = self.data_source df_onion['grimoire_creation_date'] = df_onion[ESOnionConnector.TIMEFRAME] logger.info(self.__log_prefix + " Final new events: " + str(len(df_onion))) return self.ProcessResults(processed=len(df_onion), out_items=df_onion)
[ "def", "process", "(", "self", ",", "items_block", ")", ":", "logger", ".", "info", "(", "self", ".", "__log_prefix", "+", "\" Authors to process: \"", "+", "str", "(", "len", "(", "items_block", ")", ")", ")", "onion_enrich", "=", "Onion", "(", "items_blo...
Process a DataFrame to compute Onion. :param items_block: items to be processed. Expects to find a pandas DataFrame.
[ "Process", "a", "DataFrame", "to", "compute", "Onion", "." ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/study_ceres_onion.py#L346-L368
19,716
chaoss/grimoirelab-elk
grimoire_elk/enriched/projects.py
GrimoireLibProjects.get_projects
def get_projects(self): """ Get the projects list from database """ repos_list = [] gerrit_projects_db = self.projects_db db = Database(user="root", passwd="", host="localhost", port=3306, scrdb=None, shdb=gerrit_projects_db, prjdb=None) sql = """ SELECT DISTINCT(repository_name) FROM project_repositories WHERE data_source='scr' """ repos_list_raw = db.execute(sql) # Convert from review.openstack.org_openstack/rpm-packaging-tools to # openstack_rpm-packaging-tools for repo in repos_list_raw: # repo_name = repo[0].replace("review.openstack.org_","") repo_name = repo[0].replace(self.repository + "_", "") repos_list.append(repo_name) return repos_list
python
def get_projects(self): repos_list = [] gerrit_projects_db = self.projects_db db = Database(user="root", passwd="", host="localhost", port=3306, scrdb=None, shdb=gerrit_projects_db, prjdb=None) sql = """ SELECT DISTINCT(repository_name) FROM project_repositories WHERE data_source='scr' """ repos_list_raw = db.execute(sql) # Convert from review.openstack.org_openstack/rpm-packaging-tools to # openstack_rpm-packaging-tools for repo in repos_list_raw: # repo_name = repo[0].replace("review.openstack.org_","") repo_name = repo[0].replace(self.repository + "_", "") repos_list.append(repo_name) return repos_list
[ "def", "get_projects", "(", "self", ")", ":", "repos_list", "=", "[", "]", "gerrit_projects_db", "=", "self", ".", "projects_db", "db", "=", "Database", "(", "user", "=", "\"root\"", ",", "passwd", "=", "\"\"", ",", "host", "=", "\"localhost\"", ",", "po...
Get the projects list from database
[ "Get", "the", "projects", "list", "from", "database" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/projects.py#L37-L62
19,717
chaoss/grimoirelab-elk
grimoire_elk/enriched/enrich.py
metadata
def metadata(func): """Add metadata to an item. Decorator that adds metadata to a given item such as the gelk revision used. """ @functools.wraps(func) def decorator(self, *args, **kwargs): eitem = func(self, *args, **kwargs) metadata = { 'metadata__gelk_version': self.gelk_version, 'metadata__gelk_backend_name': self.__class__.__name__, 'metadata__enriched_on': datetime_utcnow().isoformat() } eitem.update(metadata) return eitem return decorator
python
def metadata(func): @functools.wraps(func) def decorator(self, *args, **kwargs): eitem = func(self, *args, **kwargs) metadata = { 'metadata__gelk_version': self.gelk_version, 'metadata__gelk_backend_name': self.__class__.__name__, 'metadata__enriched_on': datetime_utcnow().isoformat() } eitem.update(metadata) return eitem return decorator
[ "def", "metadata", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "decorator", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "eitem", "=", "func", "(", "self", ",", "*", "args", ",", "*", "*"...
Add metadata to an item. Decorator that adds metadata to a given item such as the gelk revision used.
[ "Add", "metadata", "to", "an", "item", "." ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/enrich.py#L78-L95
19,718
chaoss/grimoirelab-elk
grimoire_elk/enriched/enrich.py
Enrich.get_grimoire_fields
def get_grimoire_fields(self, creation_date, item_name): """ Return common grimoire fields for all data sources """ grimoire_date = None try: grimoire_date = str_to_datetime(creation_date).isoformat() except Exception as ex: pass name = "is_" + self.get_connector_name() + "_" + item_name return { "grimoire_creation_date": grimoire_date, name: 1 }
python
def get_grimoire_fields(self, creation_date, item_name): grimoire_date = None try: grimoire_date = str_to_datetime(creation_date).isoformat() except Exception as ex: pass name = "is_" + self.get_connector_name() + "_" + item_name return { "grimoire_creation_date": grimoire_date, name: 1 }
[ "def", "get_grimoire_fields", "(", "self", ",", "creation_date", ",", "item_name", ")", ":", "grimoire_date", "=", "None", "try", ":", "grimoire_date", "=", "str_to_datetime", "(", "creation_date", ")", ".", "isoformat", "(", ")", "except", "Exception", "as", ...
Return common grimoire fields for all data sources
[ "Return", "common", "grimoire", "fields", "for", "all", "data", "sources" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/enrich.py#L489-L503
19,719
chaoss/grimoirelab-elk
grimoire_elk/enriched/enrich.py
Enrich.add_project_levels
def add_project_levels(cls, project): """ Add project sub levels extra items """ eitem_path = '' eitem_project_levels = {} if project is not None: subprojects = project.split('.') for i in range(0, len(subprojects)): if i > 0: eitem_path += "." eitem_path += subprojects[i] eitem_project_levels['project_' + str(i + 1)] = eitem_path return eitem_project_levels
python
def add_project_levels(cls, project): eitem_path = '' eitem_project_levels = {} if project is not None: subprojects = project.split('.') for i in range(0, len(subprojects)): if i > 0: eitem_path += "." eitem_path += subprojects[i] eitem_project_levels['project_' + str(i + 1)] = eitem_path return eitem_project_levels
[ "def", "add_project_levels", "(", "cls", ",", "project", ")", ":", "eitem_path", "=", "''", "eitem_project_levels", "=", "{", "}", "if", "project", "is", "not", "None", ":", "subprojects", "=", "project", ".", "split", "(", "'.'", ")", "for", "i", "in", ...
Add project sub levels extra items
[ "Add", "project", "sub", "levels", "extra", "items" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/enrich.py#L515-L529
19,720
chaoss/grimoirelab-elk
grimoire_elk/enriched/enrich.py
Enrich.get_item_metadata
def get_item_metadata(self, eitem): """ In the projects.json file, inside each project, there is a field called "meta" which has a dictionary with fields to be added to the enriched items for this project. This fields must be added with the prefix cm_ (custom metadata). This method fetch the metadata fields for the project in which the eitem is included. :param eitem: enriched item to search metadata for :return: a dictionary with the metadata fields """ eitem_metadata = {} # Get the project entry for the item, which includes the metadata project = self.find_item_project(eitem) if project and 'meta' in self.json_projects[project]: meta_fields = self.json_projects[project]['meta'] if isinstance(meta_fields, dict): eitem_metadata = {CUSTOM_META_PREFIX + "_" + field: value for field, value in meta_fields.items()} return eitem_metadata
python
def get_item_metadata(self, eitem): eitem_metadata = {} # Get the project entry for the item, which includes the metadata project = self.find_item_project(eitem) if project and 'meta' in self.json_projects[project]: meta_fields = self.json_projects[project]['meta'] if isinstance(meta_fields, dict): eitem_metadata = {CUSTOM_META_PREFIX + "_" + field: value for field, value in meta_fields.items()} return eitem_metadata
[ "def", "get_item_metadata", "(", "self", ",", "eitem", ")", ":", "eitem_metadata", "=", "{", "}", "# Get the project entry for the item, which includes the metadata", "project", "=", "self", ".", "find_item_project", "(", "eitem", ")", "if", "project", "and", "'meta'"...
In the projects.json file, inside each project, there is a field called "meta" which has a dictionary with fields to be added to the enriched items for this project. This fields must be added with the prefix cm_ (custom metadata). This method fetch the metadata fields for the project in which the eitem is included. :param eitem: enriched item to search metadata for :return: a dictionary with the metadata fields
[ "In", "the", "projects", ".", "json", "file", "inside", "each", "project", "there", "is", "a", "field", "called", "meta", "which", "has", "a", "dictionary", "with", "fields", "to", "be", "added", "to", "the", "enriched", "items", "for", "this", "project", ...
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/enrich.py#L607-L630
19,721
chaoss/grimoirelab-elk
grimoire_elk/enriched/enrich.py
Enrich.get_domain
def get_domain(self, identity): """ Get the domain from a SH identity """ domain = None if identity['email']: try: domain = identity['email'].split("@")[1] except IndexError: # logger.warning("Bad email format: %s" % (identity['email'])) pass return domain
python
def get_domain(self, identity): domain = None if identity['email']: try: domain = identity['email'].split("@")[1] except IndexError: # logger.warning("Bad email format: %s" % (identity['email'])) pass return domain
[ "def", "get_domain", "(", "self", ",", "identity", ")", ":", "domain", "=", "None", "if", "identity", "[", "'email'", "]", ":", "try", ":", "domain", "=", "identity", "[", "'email'", "]", ".", "split", "(", "\"@\"", ")", "[", "1", "]", "except", "I...
Get the domain from a SH identity
[ "Get", "the", "domain", "from", "a", "SH", "identity" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/enrich.py#L640-L649
19,722
chaoss/grimoirelab-elk
grimoire_elk/enriched/enrich.py
Enrich.get_enrollment
def get_enrollment(self, uuid, item_date): """ Get the enrollment for the uuid when the item was done """ # item_date must be offset-naive (utc) if item_date and item_date.tzinfo: item_date = (item_date - item_date.utcoffset()).replace(tzinfo=None) enrollments = self.get_enrollments(uuid) enroll = self.unaffiliated_group if enrollments: for enrollment in enrollments: if not item_date: enroll = enrollment.organization.name break elif item_date >= enrollment.start and item_date <= enrollment.end: enroll = enrollment.organization.name break return enroll
python
def get_enrollment(self, uuid, item_date): # item_date must be offset-naive (utc) if item_date and item_date.tzinfo: item_date = (item_date - item_date.utcoffset()).replace(tzinfo=None) enrollments = self.get_enrollments(uuid) enroll = self.unaffiliated_group if enrollments: for enrollment in enrollments: if not item_date: enroll = enrollment.organization.name break elif item_date >= enrollment.start and item_date <= enrollment.end: enroll = enrollment.organization.name break return enroll
[ "def", "get_enrollment", "(", "self", ",", "uuid", ",", "item_date", ")", ":", "# item_date must be offset-naive (utc)", "if", "item_date", "and", "item_date", ".", "tzinfo", ":", "item_date", "=", "(", "item_date", "-", "item_date", ".", "utcoffset", "(", ")", ...
Get the enrollment for the uuid when the item was done
[ "Get", "the", "enrollment", "for", "the", "uuid", "when", "the", "item", "was", "done" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/enrich.py#L658-L674
19,723
chaoss/grimoirelab-elk
grimoire_elk/enriched/enrich.py
Enrich.__get_item_sh_fields_empty
def __get_item_sh_fields_empty(self, rol, undefined=False): """ Return a SH identity with all fields to empty_field """ # If empty_field is None, the fields do not appear in index patterns empty_field = '' if not undefined else '-- UNDEFINED --' return { rol + "_id": empty_field, rol + "_uuid": empty_field, rol + "_name": empty_field, rol + "_user_name": empty_field, rol + "_domain": empty_field, rol + "_gender": empty_field, rol + "_gender_acc": None, rol + "_org_name": empty_field, rol + "_bot": False }
python
def __get_item_sh_fields_empty(self, rol, undefined=False): # If empty_field is None, the fields do not appear in index patterns empty_field = '' if not undefined else '-- UNDEFINED --' return { rol + "_id": empty_field, rol + "_uuid": empty_field, rol + "_name": empty_field, rol + "_user_name": empty_field, rol + "_domain": empty_field, rol + "_gender": empty_field, rol + "_gender_acc": None, rol + "_org_name": empty_field, rol + "_bot": False }
[ "def", "__get_item_sh_fields_empty", "(", "self", ",", "rol", ",", "undefined", "=", "False", ")", ":", "# If empty_field is None, the fields do not appear in index patterns", "empty_field", "=", "''", "if", "not", "undefined", "else", "'-- UNDEFINED --'", "return", "{", ...
Return a SH identity with all fields to empty_field
[ "Return", "a", "SH", "identity", "with", "all", "fields", "to", "empty_field" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/enrich.py#L676-L690
19,724
chaoss/grimoirelab-elk
grimoire_elk/enriched/enrich.py
Enrich.get_item_sh_fields
def get_item_sh_fields(self, identity=None, item_date=None, sh_id=None, rol='author'): """ Get standard SH fields from a SH identity """ eitem_sh = self.__get_item_sh_fields_empty(rol) if identity: # Use the identity to get the SortingHat identity sh_ids = self.get_sh_ids(identity, self.get_connector_name()) eitem_sh[rol + "_id"] = sh_ids.get('id', '') eitem_sh[rol + "_uuid"] = sh_ids.get('uuid', '') eitem_sh[rol + "_name"] = identity.get('name', '') eitem_sh[rol + "_user_name"] = identity.get('username', '') eitem_sh[rol + "_domain"] = self.get_identity_domain(identity) elif sh_id: # Use the SortingHat id to get the identity eitem_sh[rol + "_id"] = sh_id eitem_sh[rol + "_uuid"] = self.get_uuid_from_id(sh_id) else: # No data to get a SH identity. Return an empty one. return eitem_sh # If the identity does not exists return and empty identity if rol + "_uuid" not in eitem_sh or not eitem_sh[rol + "_uuid"]: return self.__get_item_sh_fields_empty(rol, undefined=True) # Get the SH profile to use first this data profile = self.get_profile_sh(eitem_sh[rol + "_uuid"]) if profile: # If name not in profile, keep its old value (should be empty or identity's name field value) eitem_sh[rol + "_name"] = profile.get('name', eitem_sh[rol + "_name"]) email = profile.get('email', None) if email: eitem_sh[rol + "_domain"] = self.get_email_domain(email) eitem_sh[rol + "_gender"] = profile.get('gender', self.unknown_gender) eitem_sh[rol + "_gender_acc"] = profile.get('gender_acc', 0) elif not profile and sh_id: logger.warning("Can't find SH identity profile: %s", sh_id) # Ensure we always write gender fields if not eitem_sh.get(rol + "_gender"): eitem_sh[rol + "_gender"] = self.unknown_gender eitem_sh[rol + "_gender_acc"] = 0 eitem_sh[rol + "_org_name"] = self.get_enrollment(eitem_sh[rol + "_uuid"], item_date) eitem_sh[rol + "_bot"] = self.is_bot(eitem_sh[rol + '_uuid']) return eitem_sh
python
def get_item_sh_fields(self, identity=None, item_date=None, sh_id=None, rol='author'): eitem_sh = self.__get_item_sh_fields_empty(rol) if identity: # Use the identity to get the SortingHat identity sh_ids = self.get_sh_ids(identity, self.get_connector_name()) eitem_sh[rol + "_id"] = sh_ids.get('id', '') eitem_sh[rol + "_uuid"] = sh_ids.get('uuid', '') eitem_sh[rol + "_name"] = identity.get('name', '') eitem_sh[rol + "_user_name"] = identity.get('username', '') eitem_sh[rol + "_domain"] = self.get_identity_domain(identity) elif sh_id: # Use the SortingHat id to get the identity eitem_sh[rol + "_id"] = sh_id eitem_sh[rol + "_uuid"] = self.get_uuid_from_id(sh_id) else: # No data to get a SH identity. Return an empty one. return eitem_sh # If the identity does not exists return and empty identity if rol + "_uuid" not in eitem_sh or not eitem_sh[rol + "_uuid"]: return self.__get_item_sh_fields_empty(rol, undefined=True) # Get the SH profile to use first this data profile = self.get_profile_sh(eitem_sh[rol + "_uuid"]) if profile: # If name not in profile, keep its old value (should be empty or identity's name field value) eitem_sh[rol + "_name"] = profile.get('name', eitem_sh[rol + "_name"]) email = profile.get('email', None) if email: eitem_sh[rol + "_domain"] = self.get_email_domain(email) eitem_sh[rol + "_gender"] = profile.get('gender', self.unknown_gender) eitem_sh[rol + "_gender_acc"] = profile.get('gender_acc', 0) elif not profile and sh_id: logger.warning("Can't find SH identity profile: %s", sh_id) # Ensure we always write gender fields if not eitem_sh.get(rol + "_gender"): eitem_sh[rol + "_gender"] = self.unknown_gender eitem_sh[rol + "_gender_acc"] = 0 eitem_sh[rol + "_org_name"] = self.get_enrollment(eitem_sh[rol + "_uuid"], item_date) eitem_sh[rol + "_bot"] = self.is_bot(eitem_sh[rol + '_uuid']) return eitem_sh
[ "def", "get_item_sh_fields", "(", "self", ",", "identity", "=", "None", ",", "item_date", "=", "None", ",", "sh_id", "=", "None", ",", "rol", "=", "'author'", ")", ":", "eitem_sh", "=", "self", ".", "__get_item_sh_fields_empty", "(", "rol", ")", "if", "i...
Get standard SH fields from a SH identity
[ "Get", "standard", "SH", "fields", "from", "a", "SH", "identity" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/enrich.py#L692-L741
19,725
chaoss/grimoirelab-elk
grimoire_elk/enriched/enrich.py
Enrich.get_item_sh
def get_item_sh(self, item, roles=None, date_field=None): """ Add sorting hat enrichment fields for different roles If there are no roles, just add the author fields. """ eitem_sh = {} # Item enriched author_field = self.get_field_author() if not roles: roles = [author_field] if not date_field: item_date = str_to_datetime(item[self.get_field_date()]) else: item_date = str_to_datetime(item[date_field]) users_data = self.get_users_data(item) for rol in roles: if rol in users_data: identity = self.get_sh_identity(item, rol) eitem_sh.update(self.get_item_sh_fields(identity, item_date, rol=rol)) if not eitem_sh[rol + '_org_name']: eitem_sh[rol + '_org_name'] = SH_UNKNOWN_VALUE if not eitem_sh[rol + '_name']: eitem_sh[rol + '_name'] = SH_UNKNOWN_VALUE if not eitem_sh[rol + '_user_name']: eitem_sh[rol + '_user_name'] = SH_UNKNOWN_VALUE # Add the author field common in all data sources rol_author = 'author' if author_field in users_data and author_field != rol_author: identity = self.get_sh_identity(item, author_field) eitem_sh.update(self.get_item_sh_fields(identity, item_date, rol=rol_author)) if not eitem_sh['author_org_name']: eitem_sh['author_org_name'] = SH_UNKNOWN_VALUE if not eitem_sh['author_name']: eitem_sh['author_name'] = SH_UNKNOWN_VALUE if not eitem_sh['author_user_name']: eitem_sh['author_user_name'] = SH_UNKNOWN_VALUE return eitem_sh
python
def get_item_sh(self, item, roles=None, date_field=None): eitem_sh = {} # Item enriched author_field = self.get_field_author() if not roles: roles = [author_field] if not date_field: item_date = str_to_datetime(item[self.get_field_date()]) else: item_date = str_to_datetime(item[date_field]) users_data = self.get_users_data(item) for rol in roles: if rol in users_data: identity = self.get_sh_identity(item, rol) eitem_sh.update(self.get_item_sh_fields(identity, item_date, rol=rol)) if not eitem_sh[rol + '_org_name']: eitem_sh[rol + '_org_name'] = SH_UNKNOWN_VALUE if not eitem_sh[rol + '_name']: eitem_sh[rol + '_name'] = SH_UNKNOWN_VALUE if not eitem_sh[rol + '_user_name']: eitem_sh[rol + '_user_name'] = SH_UNKNOWN_VALUE # Add the author field common in all data sources rol_author = 'author' if author_field in users_data and author_field != rol_author: identity = self.get_sh_identity(item, author_field) eitem_sh.update(self.get_item_sh_fields(identity, item_date, rol=rol_author)) if not eitem_sh['author_org_name']: eitem_sh['author_org_name'] = SH_UNKNOWN_VALUE if not eitem_sh['author_name']: eitem_sh['author_name'] = SH_UNKNOWN_VALUE if not eitem_sh['author_user_name']: eitem_sh['author_user_name'] = SH_UNKNOWN_VALUE return eitem_sh
[ "def", "get_item_sh", "(", "self", ",", "item", ",", "roles", "=", "None", ",", "date_field", "=", "None", ")", ":", "eitem_sh", "=", "{", "}", "# Item enriched", "author_field", "=", "self", ".", "get_field_author", "(", ")", "if", "not", "roles", ":", ...
Add sorting hat enrichment fields for different roles If there are no roles, just add the author fields.
[ "Add", "sorting", "hat", "enrichment", "fields", "for", "different", "roles" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/enrich.py#L801-L852
19,726
chaoss/grimoirelab-elk
grimoire_elk/enriched/enrich.py
Enrich.get_sh_ids
def get_sh_ids(self, identity, backend_name): """ Return the Sorting Hat id and uuid for an identity """ # Convert the dict to tuple so it is hashable identity_tuple = tuple(identity.items()) sh_ids = self.__get_sh_ids_cache(identity_tuple, backend_name) return sh_ids
python
def get_sh_ids(self, identity, backend_name): # Convert the dict to tuple so it is hashable identity_tuple = tuple(identity.items()) sh_ids = self.__get_sh_ids_cache(identity_tuple, backend_name) return sh_ids
[ "def", "get_sh_ids", "(", "self", ",", "identity", ",", "backend_name", ")", ":", "# Convert the dict to tuple so it is hashable", "identity_tuple", "=", "tuple", "(", "identity", ".", "items", "(", ")", ")", "sh_ids", "=", "self", ".", "__get_sh_ids_cache", "(", ...
Return the Sorting Hat id and uuid for an identity
[ "Return", "the", "Sorting", "Hat", "id", "and", "uuid", "for", "an", "identity" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/enrich.py#L867-L872
19,727
chaoss/grimoirelab-elk
grimoire_elk/elastic_items.py
ElasticItems.get_repository_filter_raw
def get_repository_filter_raw(self, term=False): """ Returns the filter to be used in queries in a repository items """ perceval_backend_name = self.get_connector_name() filter_ = get_repository_filter(self.perceval_backend, perceval_backend_name, term) return filter_
python
def get_repository_filter_raw(self, term=False): perceval_backend_name = self.get_connector_name() filter_ = get_repository_filter(self.perceval_backend, perceval_backend_name, term) return filter_
[ "def", "get_repository_filter_raw", "(", "self", ",", "term", "=", "False", ")", ":", "perceval_backend_name", "=", "self", ".", "get_connector_name", "(", ")", "filter_", "=", "get_repository_filter", "(", "self", ".", "perceval_backend", ",", "perceval_backend_nam...
Returns the filter to be used in queries in a repository items
[ "Returns", "the", "filter", "to", "be", "used", "in", "queries", "in", "a", "repository", "items" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/elastic_items.py#L67-L71
19,728
chaoss/grimoirelab-elk
grimoire_elk/elastic_items.py
ElasticItems.set_filter_raw
def set_filter_raw(self, filter_raw): """Filter to be used when getting items from Ocean index""" self.filter_raw = filter_raw self.filter_raw_dict = [] splitted = re.compile(FILTER_SEPARATOR).split(filter_raw) for fltr_raw in splitted: fltr = self.__process_filter(fltr_raw) self.filter_raw_dict.append(fltr)
python
def set_filter_raw(self, filter_raw): self.filter_raw = filter_raw self.filter_raw_dict = [] splitted = re.compile(FILTER_SEPARATOR).split(filter_raw) for fltr_raw in splitted: fltr = self.__process_filter(fltr_raw) self.filter_raw_dict.append(fltr)
[ "def", "set_filter_raw", "(", "self", ",", "filter_raw", ")", ":", "self", ".", "filter_raw", "=", "filter_raw", "self", ".", "filter_raw_dict", "=", "[", "]", "splitted", "=", "re", ".", "compile", "(", "FILTER_SEPARATOR", ")", ".", "split", "(", "filter_...
Filter to be used when getting items from Ocean index
[ "Filter", "to", "be", "used", "when", "getting", "items", "from", "Ocean", "index" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/elastic_items.py#L104-L114
19,729
chaoss/grimoirelab-elk
grimoire_elk/elastic_items.py
ElasticItems.set_filter_raw_should
def set_filter_raw_should(self, filter_raw_should): """Bool filter should to be used when getting items from Ocean index""" self.filter_raw_should = filter_raw_should self.filter_raw_should_dict = [] splitted = re.compile(FILTER_SEPARATOR).split(filter_raw_should) for fltr_raw in splitted: fltr = self.__process_filter(fltr_raw) self.filter_raw_should_dict.append(fltr)
python
def set_filter_raw_should(self, filter_raw_should): self.filter_raw_should = filter_raw_should self.filter_raw_should_dict = [] splitted = re.compile(FILTER_SEPARATOR).split(filter_raw_should) for fltr_raw in splitted: fltr = self.__process_filter(fltr_raw) self.filter_raw_should_dict.append(fltr)
[ "def", "set_filter_raw_should", "(", "self", ",", "filter_raw_should", ")", ":", "self", ".", "filter_raw_should", "=", "filter_raw_should", "self", ".", "filter_raw_should_dict", "=", "[", "]", "splitted", "=", "re", ".", "compile", "(", "FILTER_SEPARATOR", ")", ...
Bool filter should to be used when getting items from Ocean index
[ "Bool", "filter", "should", "to", "be", "used", "when", "getting", "items", "from", "Ocean", "index" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/elastic_items.py#L116-L126
19,730
chaoss/grimoirelab-elk
grimoire_elk/elastic_items.py
ElasticItems.fetch
def fetch(self, _filter=None, ignore_incremental=False): """ Fetch the items from raw or enriched index. An optional _filter could be provided to filter the data collected """ logger.debug("Creating a elastic items generator.") scroll_id = None page = self.get_elastic_items(scroll_id, _filter=_filter, ignore_incremental=ignore_incremental) if not page: return [] scroll_id = page["_scroll_id"] scroll_size = page['hits']['total'] if scroll_size == 0: logger.warning("No results found from %s", self.elastic.anonymize_url(self.elastic.index_url)) return while scroll_size > 0: logger.debug("Fetching from %s: %d received", self.elastic.anonymize_url(self.elastic.index_url), len(page['hits']['hits'])) for item in page['hits']['hits']: eitem = item['_source'] yield eitem page = self.get_elastic_items(scroll_id, _filter=_filter, ignore_incremental=ignore_incremental) if not page: break scroll_size = len(page['hits']['hits']) logger.debug("Fetching from %s: done receiving", self.elastic.anonymize_url(self.elastic.index_url))
python
def fetch(self, _filter=None, ignore_incremental=False): logger.debug("Creating a elastic items generator.") scroll_id = None page = self.get_elastic_items(scroll_id, _filter=_filter, ignore_incremental=ignore_incremental) if not page: return [] scroll_id = page["_scroll_id"] scroll_size = page['hits']['total'] if scroll_size == 0: logger.warning("No results found from %s", self.elastic.anonymize_url(self.elastic.index_url)) return while scroll_size > 0: logger.debug("Fetching from %s: %d received", self.elastic.anonymize_url(self.elastic.index_url), len(page['hits']['hits'])) for item in page['hits']['hits']: eitem = item['_source'] yield eitem page = self.get_elastic_items(scroll_id, _filter=_filter, ignore_incremental=ignore_incremental) if not page: break scroll_size = len(page['hits']['hits']) logger.debug("Fetching from %s: done receiving", self.elastic.anonymize_url(self.elastic.index_url))
[ "def", "fetch", "(", "self", ",", "_filter", "=", "None", ",", "ignore_incremental", "=", "False", ")", ":", "logger", ".", "debug", "(", "\"Creating a elastic items generator.\"", ")", "scroll_id", "=", "None", "page", "=", "self", ".", "get_elastic_items", "...
Fetch the items from raw or enriched index. An optional _filter could be provided to filter the data collected
[ "Fetch", "the", "items", "from", "raw", "or", "enriched", "index", ".", "An", "optional", "_filter", "could", "be", "provided", "to", "filter", "the", "data", "collected" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/elastic_items.py#L140-L174
19,731
chaoss/grimoirelab-elk
utils/index_mapping.py
find_uuid
def find_uuid(es_url, index): """ Find the unique identifier field for a given index """ uid_field = None # Get the first item to detect the data source and raw/enriched type res = requests.get('%s/%s/_search?size=1' % (es_url, index)) first_item = res.json()['hits']['hits'][0]['_source'] fields = first_item.keys() if 'uuid' in fields: uid_field = 'uuid' else: # Non perceval backend uuid_value = res.json()['hits']['hits'][0]['_id'] logging.debug("Finding unique id for %s with value %s", index, uuid_value) for field in fields: if first_item[field] == uuid_value: logging.debug("Found unique id for %s: %s", index, field) uid_field = field break if not uid_field: logging.error("Can not find uid field for %s. Can not copy the index.", index) logging.error("Try to copy it directly with elasticdump or similar.") sys.exit(1) return uid_field
python
def find_uuid(es_url, index): uid_field = None # Get the first item to detect the data source and raw/enriched type res = requests.get('%s/%s/_search?size=1' % (es_url, index)) first_item = res.json()['hits']['hits'][0]['_source'] fields = first_item.keys() if 'uuid' in fields: uid_field = 'uuid' else: # Non perceval backend uuid_value = res.json()['hits']['hits'][0]['_id'] logging.debug("Finding unique id for %s with value %s", index, uuid_value) for field in fields: if first_item[field] == uuid_value: logging.debug("Found unique id for %s: %s", index, field) uid_field = field break if not uid_field: logging.error("Can not find uid field for %s. Can not copy the index.", index) logging.error("Try to copy it directly with elasticdump or similar.") sys.exit(1) return uid_field
[ "def", "find_uuid", "(", "es_url", ",", "index", ")", ":", "uid_field", "=", "None", "# Get the first item to detect the data source and raw/enriched type", "res", "=", "requests", ".", "get", "(", "'%s/%s/_search?size=1'", "%", "(", "es_url", ",", "index", ")", ")"...
Find the unique identifier field for a given index
[ "Find", "the", "unique", "identifier", "field", "for", "a", "given", "index" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/utils/index_mapping.py#L62-L89
19,732
chaoss/grimoirelab-elk
utils/index_mapping.py
find_mapping
def find_mapping(es_url, index): """ Find the mapping given an index """ mapping = None backend = find_perceval_backend(es_url, index) if backend: mapping = backend.get_elastic_mappings() if mapping: logging.debug("MAPPING FOUND:\n%s", json.dumps(json.loads(mapping['items']), indent=True)) return mapping
python
def find_mapping(es_url, index): mapping = None backend = find_perceval_backend(es_url, index) if backend: mapping = backend.get_elastic_mappings() if mapping: logging.debug("MAPPING FOUND:\n%s", json.dumps(json.loads(mapping['items']), indent=True)) return mapping
[ "def", "find_mapping", "(", "es_url", ",", "index", ")", ":", "mapping", "=", "None", "backend", "=", "find_perceval_backend", "(", "es_url", ",", "index", ")", "if", "backend", ":", "mapping", "=", "backend", ".", "get_elastic_mappings", "(", ")", "if", "...
Find the mapping given an index
[ "Find", "the", "mapping", "given", "an", "index" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/utils/index_mapping.py#L130-L142
19,733
chaoss/grimoirelab-elk
utils/index_mapping.py
get_elastic_items
def get_elastic_items(elastic, elastic_scroll_id=None, limit=None): """ Get the items from the index """ scroll_size = limit if not limit: scroll_size = DEFAULT_LIMIT if not elastic: return None url = elastic.index_url max_process_items_pack_time = "5m" # 10 minutes url += "/_search?scroll=%s&size=%i" % (max_process_items_pack_time, scroll_size) if elastic_scroll_id: # Just continue with the scrolling url = elastic.url url += "/_search/scroll" scroll_data = { "scroll": max_process_items_pack_time, "scroll_id": elastic_scroll_id } res = requests.post(url, data=json.dumps(scroll_data)) else: query = """ { "query": { "bool": { "must": [] } } } """ logging.debug("%s\n%s", url, json.dumps(json.loads(query), indent=4)) res = requests.post(url, data=query) rjson = None try: rjson = res.json() except Exception: logging.error("No JSON found in %s", res.text) logging.error("No results found from %s", url) return rjson
python
def get_elastic_items(elastic, elastic_scroll_id=None, limit=None): scroll_size = limit if not limit: scroll_size = DEFAULT_LIMIT if not elastic: return None url = elastic.index_url max_process_items_pack_time = "5m" # 10 minutes url += "/_search?scroll=%s&size=%i" % (max_process_items_pack_time, scroll_size) if elastic_scroll_id: # Just continue with the scrolling url = elastic.url url += "/_search/scroll" scroll_data = { "scroll": max_process_items_pack_time, "scroll_id": elastic_scroll_id } res = requests.post(url, data=json.dumps(scroll_data)) else: query = """ { "query": { "bool": { "must": [] } } } """ logging.debug("%s\n%s", url, json.dumps(json.loads(query), indent=4)) res = requests.post(url, data=query) rjson = None try: rjson = res.json() except Exception: logging.error("No JSON found in %s", res.text) logging.error("No results found from %s", url) return rjson
[ "def", "get_elastic_items", "(", "elastic", ",", "elastic_scroll_id", "=", "None", ",", "limit", "=", "None", ")", ":", "scroll_size", "=", "limit", "if", "not", "limit", ":", "scroll_size", "=", "DEFAULT_LIMIT", "if", "not", "elastic", ":", "return", "None"...
Get the items from the index
[ "Get", "the", "items", "from", "the", "index" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/utils/index_mapping.py#L145-L190
19,734
chaoss/grimoirelab-elk
utils/index_mapping.py
fetch
def fetch(elastic, backend, limit=None, search_after_value=None, scroll=True): """ Fetch the items from raw or enriched index """ logging.debug("Creating a elastic items generator.") elastic_scroll_id = None search_after = search_after_value while True: if scroll: rjson = get_elastic_items(elastic, elastic_scroll_id, limit) else: rjson = get_elastic_items_search(elastic, search_after, limit) if rjson and "_scroll_id" in rjson: elastic_scroll_id = rjson["_scroll_id"] if rjson and "hits" in rjson: if not rjson["hits"]["hits"]: break for hit in rjson["hits"]["hits"]: item = hit['_source'] if 'sort' in hit: search_after = hit['sort'] try: backend._fix_item(item) except Exception: pass yield item else: logging.error("No results found from %s", elastic.index_url) break return
python
def fetch(elastic, backend, limit=None, search_after_value=None, scroll=True): logging.debug("Creating a elastic items generator.") elastic_scroll_id = None search_after = search_after_value while True: if scroll: rjson = get_elastic_items(elastic, elastic_scroll_id, limit) else: rjson = get_elastic_items_search(elastic, search_after, limit) if rjson and "_scroll_id" in rjson: elastic_scroll_id = rjson["_scroll_id"] if rjson and "hits" in rjson: if not rjson["hits"]["hits"]: break for hit in rjson["hits"]["hits"]: item = hit['_source'] if 'sort' in hit: search_after = hit['sort'] try: backend._fix_item(item) except Exception: pass yield item else: logging.error("No results found from %s", elastic.index_url) break return
[ "def", "fetch", "(", "elastic", ",", "backend", ",", "limit", "=", "None", ",", "search_after_value", "=", "None", ",", "scroll", "=", "True", ")", ":", "logging", ".", "debug", "(", "\"Creating a elastic items generator.\"", ")", "elastic_scroll_id", "=", "No...
Fetch the items from raw or enriched index
[ "Fetch", "the", "items", "from", "raw", "or", "enriched", "index" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/utils/index_mapping.py#L261-L294
19,735
chaoss/grimoirelab-elk
utils/index_mapping.py
export_items
def export_items(elastic_url, in_index, out_index, elastic_url_out=None, search_after=False, search_after_value=None, limit=None, copy=False): """ Export items from in_index to out_index using the correct mapping """ if not limit: limit = DEFAULT_LIMIT if search_after_value: search_after_value_timestamp = int(search_after_value[0]) search_after_value_uuid = search_after_value[1] search_after_value = [search_after_value_timestamp, search_after_value_uuid] logging.info("Exporting items from %s/%s to %s", elastic_url, in_index, out_index) count_res = requests.get('%s/%s/_count' % (elastic_url, in_index)) try: count_res.raise_for_status() except requests.exceptions.HTTPError: if count_res.status_code == 404: logging.error("The index does not exists: %s", in_index) else: logging.error(count_res.text) sys.exit(1) logging.info("Total items to copy: %i", count_res.json()['count']) # Time to upload the items with the correct mapping elastic_in = ElasticSearch(elastic_url, in_index) if not copy: # Create the correct mapping for the data sources detected from in_index ds_mapping = find_mapping(elastic_url, in_index) else: logging.debug('Using the input index mapping') ds_mapping = extract_mapping(elastic_url, in_index) if not elastic_url_out: elastic_out = ElasticSearch(elastic_url, out_index, mappings=ds_mapping) else: elastic_out = ElasticSearch(elastic_url_out, out_index, mappings=ds_mapping) # Time to just copy from in_index to our_index uid_field = find_uuid(elastic_url, in_index) backend = find_perceval_backend(elastic_url, in_index) if search_after: total = elastic_out.bulk_upload(fetch(elastic_in, backend, limit, search_after_value, scroll=False), uid_field) else: total = elastic_out.bulk_upload(fetch(elastic_in, backend, limit), uid_field) logging.info("Total items copied: %i", total)
python
def export_items(elastic_url, in_index, out_index, elastic_url_out=None, search_after=False, search_after_value=None, limit=None, copy=False): if not limit: limit = DEFAULT_LIMIT if search_after_value: search_after_value_timestamp = int(search_after_value[0]) search_after_value_uuid = search_after_value[1] search_after_value = [search_after_value_timestamp, search_after_value_uuid] logging.info("Exporting items from %s/%s to %s", elastic_url, in_index, out_index) count_res = requests.get('%s/%s/_count' % (elastic_url, in_index)) try: count_res.raise_for_status() except requests.exceptions.HTTPError: if count_res.status_code == 404: logging.error("The index does not exists: %s", in_index) else: logging.error(count_res.text) sys.exit(1) logging.info("Total items to copy: %i", count_res.json()['count']) # Time to upload the items with the correct mapping elastic_in = ElasticSearch(elastic_url, in_index) if not copy: # Create the correct mapping for the data sources detected from in_index ds_mapping = find_mapping(elastic_url, in_index) else: logging.debug('Using the input index mapping') ds_mapping = extract_mapping(elastic_url, in_index) if not elastic_url_out: elastic_out = ElasticSearch(elastic_url, out_index, mappings=ds_mapping) else: elastic_out = ElasticSearch(elastic_url_out, out_index, mappings=ds_mapping) # Time to just copy from in_index to our_index uid_field = find_uuid(elastic_url, in_index) backend = find_perceval_backend(elastic_url, in_index) if search_after: total = elastic_out.bulk_upload(fetch(elastic_in, backend, limit, search_after_value, scroll=False), uid_field) else: total = elastic_out.bulk_upload(fetch(elastic_in, backend, limit), uid_field) logging.info("Total items copied: %i", total)
[ "def", "export_items", "(", "elastic_url", ",", "in_index", ",", "out_index", ",", "elastic_url_out", "=", "None", ",", "search_after", "=", "False", ",", "search_after_value", "=", "None", ",", "limit", "=", "None", ",", "copy", "=", "False", ")", ":", "i...
Export items from in_index to out_index using the correct mapping
[ "Export", "items", "from", "in_index", "to", "out_index", "using", "the", "correct", "mapping" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/utils/index_mapping.py#L297-L347
19,736
chaoss/grimoirelab-elk
grimoire_elk/enriched/gerrit.py
GerritEnrich._fix_review_dates
def _fix_review_dates(self, item): """Convert dates so ES detect them""" for date_field in ['timestamp', 'createdOn', 'lastUpdated']: if date_field in item.keys(): date_ts = item[date_field] item[date_field] = unixtime_to_datetime(date_ts).isoformat() if 'patchSets' in item.keys(): for patch in item['patchSets']: pdate_ts = patch['createdOn'] patch['createdOn'] = unixtime_to_datetime(pdate_ts).isoformat() if 'approvals' in patch: for approval in patch['approvals']: adate_ts = approval['grantedOn'] approval['grantedOn'] = unixtime_to_datetime(adate_ts).isoformat() if 'comments' in item.keys(): for comment in item['comments']: cdate_ts = comment['timestamp'] comment['timestamp'] = unixtime_to_datetime(cdate_ts).isoformat()
python
def _fix_review_dates(self, item): for date_field in ['timestamp', 'createdOn', 'lastUpdated']: if date_field in item.keys(): date_ts = item[date_field] item[date_field] = unixtime_to_datetime(date_ts).isoformat() if 'patchSets' in item.keys(): for patch in item['patchSets']: pdate_ts = patch['createdOn'] patch['createdOn'] = unixtime_to_datetime(pdate_ts).isoformat() if 'approvals' in patch: for approval in patch['approvals']: adate_ts = approval['grantedOn'] approval['grantedOn'] = unixtime_to_datetime(adate_ts).isoformat() if 'comments' in item.keys(): for comment in item['comments']: cdate_ts = comment['timestamp'] comment['timestamp'] = unixtime_to_datetime(cdate_ts).isoformat()
[ "def", "_fix_review_dates", "(", "self", ",", "item", ")", ":", "for", "date_field", "in", "[", "'timestamp'", ",", "'createdOn'", ",", "'lastUpdated'", "]", ":", "if", "date_field", "in", "item", ".", "keys", "(", ")", ":", "date_ts", "=", "item", "[", ...
Convert dates so ES detect them
[ "Convert", "dates", "so", "ES", "detect", "them" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/gerrit.py#L145-L166
19,737
chaoss/grimoirelab-elk
grimoire_elk/enriched/bugzilla.py
BugzillaEnrich.get_sh_identity
def get_sh_identity(self, item, identity_field=None): """ Return a Sorting Hat identity using bugzilla user data """ def fill_list_identity(identity, user_list_data): """ Fill identity with user data in first item in list """ identity['username'] = user_list_data[0]['__text__'] if '@' in identity['username']: identity['email'] = identity['username'] if 'name' in user_list_data[0]: identity['name'] = user_list_data[0]['name'] return identity identity = {} for field in ['name', 'email', 'username']: # Basic fields in Sorting Hat identity[field] = None user = item # by default a specific user dict is used if 'data' in item and type(item) == dict: user = item['data'][identity_field] identity = fill_list_identity(identity, user) return identity
python
def get_sh_identity(self, item, identity_field=None): def fill_list_identity(identity, user_list_data): """ Fill identity with user data in first item in list """ identity['username'] = user_list_data[0]['__text__'] if '@' in identity['username']: identity['email'] = identity['username'] if 'name' in user_list_data[0]: identity['name'] = user_list_data[0]['name'] return identity identity = {} for field in ['name', 'email', 'username']: # Basic fields in Sorting Hat identity[field] = None user = item # by default a specific user dict is used if 'data' in item and type(item) == dict: user = item['data'][identity_field] identity = fill_list_identity(identity, user) return identity
[ "def", "get_sh_identity", "(", "self", ",", "item", ",", "identity_field", "=", "None", ")", ":", "def", "fill_list_identity", "(", "identity", ",", "user_list_data", ")", ":", "\"\"\" Fill identity with user data in first item in list \"\"\"", "identity", "[", "'userna...
Return a Sorting Hat identity using bugzilla user data
[ "Return", "a", "Sorting", "Hat", "identity", "using", "bugzilla", "user", "data" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/bugzilla.py#L47-L70
19,738
chaoss/grimoirelab-elk
grimoire_elk/enriched/ceres_base.py
CeresBase.analyze
def analyze(self): """Populate an enriched index by processing input items in blocks. :return: total number of out_items written. """ from_date = self._out.latest_date() if from_date: logger.info("Reading items since " + from_date) else: logger.info("Reading items since the beginning of times") cont = 0 total_processed = 0 total_written = 0 for item_block in self._in.read_block(size=self._block_size, from_date=from_date): cont = cont + len(item_block) process_results = self.process(item_block) total_processed += process_results.processed if len(process_results.out_items) > 0: self._out.write(process_results.out_items) total_written += len(process_results.out_items) else: logger.info("No new items to be written this time.") logger.info( "Items read/to be written/total read/total processed/total written: " "{0}/{1}/{2}/{3}/{4}".format(str(len(item_block)), str(len(process_results.out_items)), str(cont), str(total_processed), str(total_written))) logger.info("SUMMARY: Items total read/total processed/total written: " "{0}/{1}/{2}".format(str(cont), str(total_processed), str(total_written))) logger.info("This is the end.") return total_written
python
def analyze(self): from_date = self._out.latest_date() if from_date: logger.info("Reading items since " + from_date) else: logger.info("Reading items since the beginning of times") cont = 0 total_processed = 0 total_written = 0 for item_block in self._in.read_block(size=self._block_size, from_date=from_date): cont = cont + len(item_block) process_results = self.process(item_block) total_processed += process_results.processed if len(process_results.out_items) > 0: self._out.write(process_results.out_items) total_written += len(process_results.out_items) else: logger.info("No new items to be written this time.") logger.info( "Items read/to be written/total read/total processed/total written: " "{0}/{1}/{2}/{3}/{4}".format(str(len(item_block)), str(len(process_results.out_items)), str(cont), str(total_processed), str(total_written))) logger.info("SUMMARY: Items total read/total processed/total written: " "{0}/{1}/{2}".format(str(cont), str(total_processed), str(total_written))) logger.info("This is the end.") return total_written
[ "def", "analyze", "(", "self", ")", ":", "from_date", "=", "self", ".", "_out", ".", "latest_date", "(", ")", "if", "from_date", ":", "logger", ".", "info", "(", "\"Reading items since \"", "+", "from_date", ")", "else", ":", "logger", ".", "info", "(", ...
Populate an enriched index by processing input items in blocks. :return: total number of out_items written.
[ "Populate", "an", "enriched", "index", "by", "processing", "input", "items", "in", "blocks", "." ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/ceres_base.py#L77-L119
19,739
chaoss/grimoirelab-elk
grimoire_elk/enriched/ceres_base.py
ESConnector.read_item
def read_item(self, from_date=None): """Read items and return them one by one. :param from_date: start date for incremental reading. :return: next single item when any available. :raises ValueError: `metadata__timestamp` field not found in index :raises NotFoundError: index not found in ElasticSearch """ search_query = self._build_search_query(from_date) for hit in helpers.scan(self._es_conn, search_query, scroll='300m', index=self._es_index, preserve_order=True): yield hit
python
def read_item(self, from_date=None): search_query = self._build_search_query(from_date) for hit in helpers.scan(self._es_conn, search_query, scroll='300m', index=self._es_index, preserve_order=True): yield hit
[ "def", "read_item", "(", "self", ",", "from_date", "=", "None", ")", ":", "search_query", "=", "self", ".", "_build_search_query", "(", "from_date", ")", "for", "hit", "in", "helpers", ".", "scan", "(", "self", ".", "_es_conn", ",", "search_query", ",", ...
Read items and return them one by one. :param from_date: start date for incremental reading. :return: next single item when any available. :raises ValueError: `metadata__timestamp` field not found in index :raises NotFoundError: index not found in ElasticSearch
[ "Read", "items", "and", "return", "them", "one", "by", "one", "." ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/ceres_base.py#L161-L175
19,740
chaoss/grimoirelab-elk
grimoire_elk/enriched/ceres_base.py
ESConnector.read_block
def read_block(self, size, from_date=None): """Read items and return them in blocks. :param from_date: start date for incremental reading. :param size: block size. :return: next block of items when any available. :raises ValueError: `metadata__timestamp` field not found in index :raises NotFoundError: index not found in ElasticSearch """ search_query = self._build_search_query(from_date) hits_block = [] for hit in helpers.scan(self._es_conn, search_query, scroll='300m', index=self._es_index, preserve_order=True): hits_block.append(hit) if len(hits_block) % size == 0: yield hits_block # Reset hits block hits_block = [] if len(hits_block) > 0: yield hits_block
python
def read_block(self, size, from_date=None): search_query = self._build_search_query(from_date) hits_block = [] for hit in helpers.scan(self._es_conn, search_query, scroll='300m', index=self._es_index, preserve_order=True): hits_block.append(hit) if len(hits_block) % size == 0: yield hits_block # Reset hits block hits_block = [] if len(hits_block) > 0: yield hits_block
[ "def", "read_block", "(", "self", ",", "size", ",", "from_date", "=", "None", ")", ":", "search_query", "=", "self", ".", "_build_search_query", "(", "from_date", ")", "hits_block", "=", "[", "]", "for", "hit", "in", "helpers", ".", "scan", "(", "self", ...
Read items and return them in blocks. :param from_date: start date for incremental reading. :param size: block size. :return: next block of items when any available. :raises ValueError: `metadata__timestamp` field not found in index :raises NotFoundError: index not found in ElasticSearch
[ "Read", "items", "and", "return", "them", "in", "blocks", "." ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/ceres_base.py#L177-L203
19,741
chaoss/grimoirelab-elk
grimoire_elk/enriched/ceres_base.py
ESConnector.write
def write(self, items): """Upload items to ElasticSearch. :param items: items to be uploaded. """ if self._read_only: raise IOError("Cannot write, Connector created as Read Only") # Uploading info to the new ES docs = [] for item in items: doc = { "_index": self._es_index, "_type": "item", "_id": item["_id"], "_source": item["_source"] } docs.append(doc) # TODO exception and error handling helpers.bulk(self._es_conn, docs) logger.info(self.__log_prefix + " Written: " + str(len(docs)))
python
def write(self, items): if self._read_only: raise IOError("Cannot write, Connector created as Read Only") # Uploading info to the new ES docs = [] for item in items: doc = { "_index": self._es_index, "_type": "item", "_id": item["_id"], "_source": item["_source"] } docs.append(doc) # TODO exception and error handling helpers.bulk(self._es_conn, docs) logger.info(self.__log_prefix + " Written: " + str(len(docs)))
[ "def", "write", "(", "self", ",", "items", ")", ":", "if", "self", ".", "_read_only", ":", "raise", "IOError", "(", "\"Cannot write, Connector created as Read Only\"", ")", "# Uploading info to the new ES", "docs", "=", "[", "]", "for", "item", "in", "items", ":...
Upload items to ElasticSearch. :param items: items to be uploaded.
[ "Upload", "items", "to", "ElasticSearch", "." ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/ceres_base.py#L205-L225
19,742
chaoss/grimoirelab-elk
grimoire_elk/enriched/ceres_base.py
ESConnector.create_alias
def create_alias(self, alias_name): """Creates an alias pointing to the index configured in this connection""" return self._es_conn.indices.put_alias(index=self._es_index, name=alias_name)
python
def create_alias(self, alias_name): return self._es_conn.indices.put_alias(index=self._es_index, name=alias_name)
[ "def", "create_alias", "(", "self", ",", "alias_name", ")", ":", "return", "self", ".", "_es_conn", ".", "indices", ".", "put_alias", "(", "index", "=", "self", ".", "_es_index", ",", "name", "=", "alias_name", ")" ]
Creates an alias pointing to the index configured in this connection
[ "Creates", "an", "alias", "pointing", "to", "the", "index", "configured", "in", "this", "connection" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/ceres_base.py#L292-L295
19,743
chaoss/grimoirelab-elk
grimoire_elk/enriched/ceres_base.py
ESConnector.exists_alias
def exists_alias(self, alias_name, index_name=None): """Check whether or not the given alias exists :return: True if alias already exist""" return self._es_conn.indices.exists_alias(index=index_name, name=alias_name)
python
def exists_alias(self, alias_name, index_name=None): return self._es_conn.indices.exists_alias(index=index_name, name=alias_name)
[ "def", "exists_alias", "(", "self", ",", "alias_name", ",", "index_name", "=", "None", ")", ":", "return", "self", ".", "_es_conn", ".", "indices", ".", "exists_alias", "(", "index", "=", "index_name", ",", "name", "=", "alias_name", ")" ]
Check whether or not the given alias exists :return: True if alias already exist
[ "Check", "whether", "or", "not", "the", "given", "alias", "exists" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/ceres_base.py#L297-L302
19,744
chaoss/grimoirelab-elk
grimoire_elk/enriched/ceres_base.py
ESConnector._build_search_query
def _build_search_query(self, from_date): """Build an ElasticSearch search query to retrieve items for read methods. :param from_date: date to start retrieving items from. :return: JSON query in dict format """ sort = [{self._sort_on_field: {"order": "asc"}}] filters = [] if self._repo: filters.append({"term": {"origin": self._repo}}) if from_date: filters.append({"range": {self._sort_on_field: {"gte": from_date}}}) if filters: query = {"bool": {"filter": filters}} else: query = {"match_all": {}} search_query = { "query": query, "sort": sort } return search_query
python
def _build_search_query(self, from_date): sort = [{self._sort_on_field: {"order": "asc"}}] filters = [] if self._repo: filters.append({"term": {"origin": self._repo}}) if from_date: filters.append({"range": {self._sort_on_field: {"gte": from_date}}}) if filters: query = {"bool": {"filter": filters}} else: query = {"match_all": {}} search_query = { "query": query, "sort": sort } return search_query
[ "def", "_build_search_query", "(", "self", ",", "from_date", ")", ":", "sort", "=", "[", "{", "self", ".", "_sort_on_field", ":", "{", "\"order\"", ":", "\"asc\"", "}", "}", "]", "filters", "=", "[", "]", "if", "self", ".", "_repo", ":", "filters", "...
Build an ElasticSearch search query to retrieve items for read methods. :param from_date: date to start retrieving items from. :return: JSON query in dict format
[ "Build", "an", "ElasticSearch", "search", "query", "to", "retrieve", "items", "for", "read", "methods", "." ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/ceres_base.py#L304-L330
19,745
chaoss/grimoirelab-elk
grimoire_elk/raw/elastic.py
ElasticOcean.add_params
def add_params(cls, cmdline_parser): """ Shared params in all backends """ parser = cmdline_parser parser.add_argument("-e", "--elastic_url", default="http://127.0.0.1:9200", help="Host with elastic search (default: http://127.0.0.1:9200)") parser.add_argument("--elastic_url-enrich", help="Host with elastic search and enriched indexes")
python
def add_params(cls, cmdline_parser): parser = cmdline_parser parser.add_argument("-e", "--elastic_url", default="http://127.0.0.1:9200", help="Host with elastic search (default: http://127.0.0.1:9200)") parser.add_argument("--elastic_url-enrich", help="Host with elastic search and enriched indexes")
[ "def", "add_params", "(", "cls", ",", "cmdline_parser", ")", ":", "parser", "=", "cmdline_parser", "parser", ".", "add_argument", "(", "\"-e\"", ",", "\"--elastic_url\"", ",", "default", "=", "\"http://127.0.0.1:9200\"", ",", "help", "=", "\"Host with elastic search...
Shared params in all backends
[ "Shared", "params", "in", "all", "backends" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/raw/elastic.py#L47-L55
19,746
chaoss/grimoirelab-elk
grimoire_elk/raw/elastic.py
ElasticOcean.get_p2o_params_from_url
def get_p2o_params_from_url(cls, url): """ Get the p2o params given a URL for the data source """ # if the url doesn't contain a filter separator, return it if PRJ_JSON_FILTER_SEPARATOR not in url: return {"url": url} # otherwise, add the url to the params params = {'url': url.split(' ', 1)[0]} # tokenize the filter and add them to the param dict tokens = url.split(PRJ_JSON_FILTER_SEPARATOR)[1:] if len(tokens) > 1: cause = "Too many filters defined for %s, only the first one is considered" % url logger.warning(cause) token = tokens[0] filter_tokens = token.split(PRJ_JSON_FILTER_OP_ASSIGNMENT) if len(filter_tokens) != 2: cause = "Too many tokens after splitting for %s in %s" % (token, url) logger.error(cause) raise ELKError(cause=cause) fltr_name = filter_tokens[0].strip() fltr_value = filter_tokens[1].strip() params['filter-' + fltr_name] = fltr_value return params
python
def get_p2o_params_from_url(cls, url): # if the url doesn't contain a filter separator, return it if PRJ_JSON_FILTER_SEPARATOR not in url: return {"url": url} # otherwise, add the url to the params params = {'url': url.split(' ', 1)[0]} # tokenize the filter and add them to the param dict tokens = url.split(PRJ_JSON_FILTER_SEPARATOR)[1:] if len(tokens) > 1: cause = "Too many filters defined for %s, only the first one is considered" % url logger.warning(cause) token = tokens[0] filter_tokens = token.split(PRJ_JSON_FILTER_OP_ASSIGNMENT) if len(filter_tokens) != 2: cause = "Too many tokens after splitting for %s in %s" % (token, url) logger.error(cause) raise ELKError(cause=cause) fltr_name = filter_tokens[0].strip() fltr_value = filter_tokens[1].strip() params['filter-' + fltr_name] = fltr_value return params
[ "def", "get_p2o_params_from_url", "(", "cls", ",", "url", ")", ":", "# if the url doesn't contain a filter separator, return it", "if", "PRJ_JSON_FILTER_SEPARATOR", "not", "in", "url", ":", "return", "{", "\"url\"", ":", "url", "}", "# otherwise, add the url to the params",...
Get the p2o params given a URL for the data source
[ "Get", "the", "p2o", "params", "given", "a", "URL", "for", "the", "data", "source" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/raw/elastic.py#L98-L127
19,747
chaoss/grimoirelab-elk
grimoire_elk/raw/elastic.py
ElasticOcean.feed
def feed(self, from_date=None, from_offset=None, category=None, latest_items=None, arthur_items=None, filter_classified=None): """ Feed data in Elastic from Perceval or Arthur """ if self.fetch_archive: items = self.perceval_backend.fetch_from_archive() self.feed_items(items) return elif arthur_items: items = arthur_items self.feed_items(items) return if from_date and from_offset: raise RuntimeError("Can't not feed using from_date and from_offset.") # We need to filter by repository to support several repositories # in the same raw index filters_ = [get_repository_filter(self.perceval_backend, self.get_connector_name())] # Check if backend supports from_date signature = inspect.signature(self.perceval_backend.fetch) last_update = None if 'from_date' in signature.parameters: if from_date: last_update = from_date else: self.last_update = self.get_last_update_from_es(filters_=filters_) last_update = self.last_update logger.info("Incremental from: %s", last_update) offset = None if 'offset' in signature.parameters: if from_offset: offset = from_offset else: offset = self.elastic.get_last_offset("offset", filters_=filters_) if offset is not None: logger.info("Incremental from: %i offset", offset) else: logger.info("Not incremental") params = {} # category and filter_classified params are shared # by all Perceval backends if category is not None: params['category'] = category if filter_classified is not None: params['filter_classified'] = filter_classified # latest items, from_date and offset cannot be used together, # thus, the params dictionary is filled with the param available # and Perceval is executed if latest_items: params['latest_items'] = latest_items items = self.perceval_backend.fetch(**params) elif last_update: last_update = last_update.replace(tzinfo=None) params['from_date'] = last_update items = self.perceval_backend.fetch(**params) elif offset is not None: params['offset'] = offset items = self.perceval_backend.fetch(**params) else: items = self.perceval_backend.fetch(**params) self.feed_items(items) self.update_items()
python
def feed(self, from_date=None, from_offset=None, category=None, latest_items=None, arthur_items=None, filter_classified=None): if self.fetch_archive: items = self.perceval_backend.fetch_from_archive() self.feed_items(items) return elif arthur_items: items = arthur_items self.feed_items(items) return if from_date and from_offset: raise RuntimeError("Can't not feed using from_date and from_offset.") # We need to filter by repository to support several repositories # in the same raw index filters_ = [get_repository_filter(self.perceval_backend, self.get_connector_name())] # Check if backend supports from_date signature = inspect.signature(self.perceval_backend.fetch) last_update = None if 'from_date' in signature.parameters: if from_date: last_update = from_date else: self.last_update = self.get_last_update_from_es(filters_=filters_) last_update = self.last_update logger.info("Incremental from: %s", last_update) offset = None if 'offset' in signature.parameters: if from_offset: offset = from_offset else: offset = self.elastic.get_last_offset("offset", filters_=filters_) if offset is not None: logger.info("Incremental from: %i offset", offset) else: logger.info("Not incremental") params = {} # category and filter_classified params are shared # by all Perceval backends if category is not None: params['category'] = category if filter_classified is not None: params['filter_classified'] = filter_classified # latest items, from_date and offset cannot be used together, # thus, the params dictionary is filled with the param available # and Perceval is executed if latest_items: params['latest_items'] = latest_items items = self.perceval_backend.fetch(**params) elif last_update: last_update = last_update.replace(tzinfo=None) params['from_date'] = last_update items = self.perceval_backend.fetch(**params) elif offset is not None: params['offset'] = offset items = self.perceval_backend.fetch(**params) else: items = self.perceval_backend.fetch(**params) self.feed_items(items) self.update_items()
[ "def", "feed", "(", "self", ",", "from_date", "=", "None", ",", "from_offset", "=", "None", ",", "category", "=", "None", ",", "latest_items", "=", "None", ",", "arthur_items", "=", "None", ",", "filter_classified", "=", "None", ")", ":", "if", "self", ...
Feed data in Elastic from Perceval or Arthur
[ "Feed", "data", "in", "Elastic", "from", "Perceval", "or", "Arthur" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/raw/elastic.py#L155-L226
19,748
chaoss/grimoirelab-elk
grimoire_elk/enriched/git.py
GitEnrich.get_identities
def get_identities(self, item): """ Return the identities from an item. If the repo is in GitHub, get the usernames from GitHub. """ def add_sh_github_identity(user, user_field, rol): """ Add a new github identity to SH if it does not exists """ github_repo = None if GITHUB in item['origin']: github_repo = item['origin'].replace(GITHUB, '') github_repo = re.sub('.git$', '', github_repo) if not github_repo: return # Try to get the identity from SH user_data = item['data'][user_field] sh_identity = SortingHat.get_github_commit_username(self.sh_db, user, SH_GIT_COMMIT) if not sh_identity: # Get the usename from GitHub gh_username = self.get_github_login(user_data, rol, commit_hash, github_repo) # Create a new SH identity with name, email from git and username from github logger.debug("Adding new identity %s to SH %s: %s", gh_username, SH_GIT_COMMIT, user) user = self.get_sh_identity(user_data) user['username'] = gh_username SortingHat.add_identity(self.sh_db, user, SH_GIT_COMMIT) else: if user_data not in self.github_logins: self.github_logins[user_data] = sh_identity['username'] logger.debug("GitHub-commit exists. username:%s user:%s", sh_identity['username'], user_data) commit_hash = item['data']['commit'] if item['data']['Author']: # Check multi authors commits m = self.AUTHOR_P2P_REGEX.match(item['data']["Author"]) n = self.AUTHOR_P2P_NEW_REGEX.match(item['data']["Author"]) if (m or n) and self.pair_programming: authors = self.__get_authors(item['data']["Author"]) for author in authors: user = self.get_sh_identity(author) yield user else: user = self.get_sh_identity(item['data']["Author"]) yield user if self.github_token: add_sh_github_identity(user, 'Author', 'author') if item['data']['Commit']: m = self.AUTHOR_P2P_REGEX.match(item['data']["Commit"]) n = self.AUTHOR_P2P_NEW_REGEX.match(item['data']["Author"]) if (m or n) and self.pair_programming: committers = self.__get_authors(item['data']['Commit']) for committer in committers: user = self.get_sh_identity(committer) yield user else: user = self.get_sh_identity(item['data']['Commit']) yield user if self.github_token: add_sh_github_identity(user, 'Commit', 'committer') if 'Signed-off-by' in item['data'] and self.pair_programming: signers = item['data']["Signed-off-by"] for signer in signers: user = self.get_sh_identity(signer) yield user
python
def get_identities(self, item): def add_sh_github_identity(user, user_field, rol): """ Add a new github identity to SH if it does not exists """ github_repo = None if GITHUB in item['origin']: github_repo = item['origin'].replace(GITHUB, '') github_repo = re.sub('.git$', '', github_repo) if not github_repo: return # Try to get the identity from SH user_data = item['data'][user_field] sh_identity = SortingHat.get_github_commit_username(self.sh_db, user, SH_GIT_COMMIT) if not sh_identity: # Get the usename from GitHub gh_username = self.get_github_login(user_data, rol, commit_hash, github_repo) # Create a new SH identity with name, email from git and username from github logger.debug("Adding new identity %s to SH %s: %s", gh_username, SH_GIT_COMMIT, user) user = self.get_sh_identity(user_data) user['username'] = gh_username SortingHat.add_identity(self.sh_db, user, SH_GIT_COMMIT) else: if user_data not in self.github_logins: self.github_logins[user_data] = sh_identity['username'] logger.debug("GitHub-commit exists. username:%s user:%s", sh_identity['username'], user_data) commit_hash = item['data']['commit'] if item['data']['Author']: # Check multi authors commits m = self.AUTHOR_P2P_REGEX.match(item['data']["Author"]) n = self.AUTHOR_P2P_NEW_REGEX.match(item['data']["Author"]) if (m or n) and self.pair_programming: authors = self.__get_authors(item['data']["Author"]) for author in authors: user = self.get_sh_identity(author) yield user else: user = self.get_sh_identity(item['data']["Author"]) yield user if self.github_token: add_sh_github_identity(user, 'Author', 'author') if item['data']['Commit']: m = self.AUTHOR_P2P_REGEX.match(item['data']["Commit"]) n = self.AUTHOR_P2P_NEW_REGEX.match(item['data']["Author"]) if (m or n) and self.pair_programming: committers = self.__get_authors(item['data']['Commit']) for committer in committers: user = self.get_sh_identity(committer) yield user else: user = self.get_sh_identity(item['data']['Commit']) yield user if self.github_token: add_sh_github_identity(user, 'Commit', 'committer') if 'Signed-off-by' in item['data'] and self.pair_programming: signers = item['data']["Signed-off-by"] for signer in signers: user = self.get_sh_identity(signer) yield user
[ "def", "get_identities", "(", "self", ",", "item", ")", ":", "def", "add_sh_github_identity", "(", "user", ",", "user_field", ",", "rol", ")", ":", "\"\"\" Add a new github identity to SH if it does not exists \"\"\"", "github_repo", "=", "None", "if", "GITHUB", "in",...
Return the identities from an item. If the repo is in GitHub, get the usernames from GitHub.
[ "Return", "the", "identities", "from", "an", "item", ".", "If", "the", "repo", "is", "in", "GitHub", "get", "the", "usernames", "from", "GitHub", "." ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/git.py#L148-L211
19,749
chaoss/grimoirelab-elk
grimoire_elk/enriched/git.py
GitEnrich.__fix_field_date
def __fix_field_date(self, item, attribute): """Fix possible errors in the field date""" field_date = str_to_datetime(item[attribute]) try: _ = int(field_date.strftime("%z")[0:3]) except ValueError: logger.warning("%s in commit %s has a wrong format", attribute, item['commit']) item[attribute] = field_date.replace(tzinfo=None).isoformat()
python
def __fix_field_date(self, item, attribute): field_date = str_to_datetime(item[attribute]) try: _ = int(field_date.strftime("%z")[0:3]) except ValueError: logger.warning("%s in commit %s has a wrong format", attribute, item['commit']) item[attribute] = field_date.replace(tzinfo=None).isoformat()
[ "def", "__fix_field_date", "(", "self", ",", "item", ",", "attribute", ")", ":", "field_date", "=", "str_to_datetime", "(", "item", "[", "attribute", "]", ")", "try", ":", "_", "=", "int", "(", "field_date", ".", "strftime", "(", "\"%z\"", ")", "[", "0...
Fix possible errors in the field date
[ "Fix", "possible", "errors", "in", "the", "field", "date" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/git.py#L425-L434
19,750
chaoss/grimoirelab-elk
grimoire_elk/enriched/git.py
GitEnrich.update_items
def update_items(self, ocean_backend, enrich_backend): """Retrieve the commits not present in the original repository and delete the corresponding documents from the raw and enriched indexes""" fltr = { 'name': 'origin', 'value': [self.perceval_backend.origin] } logger.debug("[update-items] Checking commits for %s.", self.perceval_backend.origin) git_repo = GitRepository(self.perceval_backend.uri, self.perceval_backend.gitpath) try: current_hashes = set([commit for commit in git_repo.rev_list()]) except Exception as e: logger.error("Skip updating branch info for repo %s, git rev-list command failed: %s", git_repo.uri, e) return raw_hashes = set([item['data']['commit'] for item in ocean_backend.fetch(ignore_incremental=True, _filter=fltr)]) hashes_to_delete = list(raw_hashes.difference(current_hashes)) to_process = [] for _hash in hashes_to_delete: to_process.append(_hash) if len(to_process) != MAX_BULK_UPDATE_SIZE: continue # delete documents from the raw index self.remove_commits(to_process, ocean_backend.elastic.index_url, 'data.commit', self.perceval_backend.origin) # delete documents from the enriched index self.remove_commits(to_process, enrich_backend.elastic.index_url, 'hash', self.perceval_backend.origin) to_process = [] if to_process: # delete documents from the raw index self.remove_commits(to_process, ocean_backend.elastic.index_url, 'data.commit', self.perceval_backend.origin) # delete documents from the enriched index self.remove_commits(to_process, enrich_backend.elastic.index_url, 'hash', self.perceval_backend.origin) logger.debug("[update-items] %s commits deleted from %s with origin %s.", len(hashes_to_delete), ocean_backend.elastic.anonymize_url(ocean_backend.elastic.index_url), self.perceval_backend.origin) logger.debug("[update-items] %s commits deleted from %s with origin %s.", len(hashes_to_delete), enrich_backend.elastic.anonymize_url(enrich_backend.elastic.index_url), self.perceval_backend.origin) # update branch info self.delete_commit_branches(enrich_backend) self.add_commit_branches(git_repo, enrich_backend)
python
def update_items(self, ocean_backend, enrich_backend): fltr = { 'name': 'origin', 'value': [self.perceval_backend.origin] } logger.debug("[update-items] Checking commits for %s.", self.perceval_backend.origin) git_repo = GitRepository(self.perceval_backend.uri, self.perceval_backend.gitpath) try: current_hashes = set([commit for commit in git_repo.rev_list()]) except Exception as e: logger.error("Skip updating branch info for repo %s, git rev-list command failed: %s", git_repo.uri, e) return raw_hashes = set([item['data']['commit'] for item in ocean_backend.fetch(ignore_incremental=True, _filter=fltr)]) hashes_to_delete = list(raw_hashes.difference(current_hashes)) to_process = [] for _hash in hashes_to_delete: to_process.append(_hash) if len(to_process) != MAX_BULK_UPDATE_SIZE: continue # delete documents from the raw index self.remove_commits(to_process, ocean_backend.elastic.index_url, 'data.commit', self.perceval_backend.origin) # delete documents from the enriched index self.remove_commits(to_process, enrich_backend.elastic.index_url, 'hash', self.perceval_backend.origin) to_process = [] if to_process: # delete documents from the raw index self.remove_commits(to_process, ocean_backend.elastic.index_url, 'data.commit', self.perceval_backend.origin) # delete documents from the enriched index self.remove_commits(to_process, enrich_backend.elastic.index_url, 'hash', self.perceval_backend.origin) logger.debug("[update-items] %s commits deleted from %s with origin %s.", len(hashes_to_delete), ocean_backend.elastic.anonymize_url(ocean_backend.elastic.index_url), self.perceval_backend.origin) logger.debug("[update-items] %s commits deleted from %s with origin %s.", len(hashes_to_delete), enrich_backend.elastic.anonymize_url(enrich_backend.elastic.index_url), self.perceval_backend.origin) # update branch info self.delete_commit_branches(enrich_backend) self.add_commit_branches(git_repo, enrich_backend)
[ "def", "update_items", "(", "self", ",", "ocean_backend", ",", "enrich_backend", ")", ":", "fltr", "=", "{", "'name'", ":", "'origin'", ",", "'value'", ":", "[", "self", ".", "perceval_backend", ".", "origin", "]", "}", "logger", ".", "debug", "(", "\"[u...
Retrieve the commits not present in the original repository and delete the corresponding documents from the raw and enriched indexes
[ "Retrieve", "the", "commits", "not", "present", "in", "the", "original", "repository", "and", "delete", "the", "corresponding", "documents", "from", "the", "raw", "and", "enriched", "indexes" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/git.py#L668-L725
19,751
chaoss/grimoirelab-elk
grimoire_elk/enriched/git.py
GitEnrich.add_commit_branches
def add_commit_branches(self, git_repo, enrich_backend): """Add the information about branches to the documents representing commits in the enriched index. Branches are obtained using the command `git ls-remote`, then for each branch, the list of commits is retrieved via the command `git rev-list branch-name` and used to update the corresponding items in the enriched index. :param git_repo: GitRepository object :param enrich_backend: the enrich backend """ to_process = [] for hash, refname in git_repo._discover_refs(remote=True): if not refname.startswith('refs/heads/'): continue commit_count = 0 branch_name = refname.replace('refs/heads/', '') try: commits = git_repo.rev_list([branch_name]) for commit in commits: to_process.append(commit) commit_count += 1 if commit_count == MAX_BULK_UPDATE_SIZE: self.__process_commits_in_branch(enrich_backend, branch_name, to_process) # reset the counter to_process = [] commit_count = 0 if commit_count: self.__process_commits_in_branch(enrich_backend, branch_name, to_process) except Exception as e: logger.error("Skip adding branch info for repo %s due to %s", git_repo.uri, e) return
python
def add_commit_branches(self, git_repo, enrich_backend): to_process = [] for hash, refname in git_repo._discover_refs(remote=True): if not refname.startswith('refs/heads/'): continue commit_count = 0 branch_name = refname.replace('refs/heads/', '') try: commits = git_repo.rev_list([branch_name]) for commit in commits: to_process.append(commit) commit_count += 1 if commit_count == MAX_BULK_UPDATE_SIZE: self.__process_commits_in_branch(enrich_backend, branch_name, to_process) # reset the counter to_process = [] commit_count = 0 if commit_count: self.__process_commits_in_branch(enrich_backend, branch_name, to_process) except Exception as e: logger.error("Skip adding branch info for repo %s due to %s", git_repo.uri, e) return
[ "def", "add_commit_branches", "(", "self", ",", "git_repo", ",", "enrich_backend", ")", ":", "to_process", "=", "[", "]", "for", "hash", ",", "refname", "in", "git_repo", ".", "_discover_refs", "(", "remote", "=", "True", ")", ":", "if", "not", "refname", ...
Add the information about branches to the documents representing commits in the enriched index. Branches are obtained using the command `git ls-remote`, then for each branch, the list of commits is retrieved via the command `git rev-list branch-name` and used to update the corresponding items in the enriched index. :param git_repo: GitRepository object :param enrich_backend: the enrich backend
[ "Add", "the", "information", "about", "branches", "to", "the", "documents", "representing", "commits", "in", "the", "enriched", "index", ".", "Branches", "are", "obtained", "using", "the", "command", "git", "ls", "-", "remote", "then", "for", "each", "branch",...
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/git.py#L770-L807
19,752
chaoss/grimoirelab-elk
utils/gelk_mapping.py
find_ds_mapping
def find_ds_mapping(data_source, es_major_version): """ Find the mapping given a perceval data source :param data_source: name of the perceval data source :param es_major_version: string with the major version for Elasticsearch :return: a dict with the mappings (raw and enriched) """ mappings = {"raw": None, "enriched": None} # Backend connectors connectors = get_connectors() try: raw_klass = connectors[data_source][1] enrich_klass = connectors[data_source][2] except KeyError: print("Data source not found", data_source) sys.exit(1) # Mapping for raw index backend = raw_klass(None) if backend: mapping = json.loads(backend.mapping.get_elastic_mappings(es_major_version)['items']) mappings['raw'] = [mapping, find_general_mappings(es_major_version)] # Mapping for enriched index backend = enrich_klass(None) if backend: mapping = json.loads(backend.mapping.get_elastic_mappings(es_major_version)['items']) mappings['enriched'] = [mapping, find_general_mappings(es_major_version)] return mappings
python
def find_ds_mapping(data_source, es_major_version): mappings = {"raw": None, "enriched": None} # Backend connectors connectors = get_connectors() try: raw_klass = connectors[data_source][1] enrich_klass = connectors[data_source][2] except KeyError: print("Data source not found", data_source) sys.exit(1) # Mapping for raw index backend = raw_klass(None) if backend: mapping = json.loads(backend.mapping.get_elastic_mappings(es_major_version)['items']) mappings['raw'] = [mapping, find_general_mappings(es_major_version)] # Mapping for enriched index backend = enrich_klass(None) if backend: mapping = json.loads(backend.mapping.get_elastic_mappings(es_major_version)['items']) mappings['enriched'] = [mapping, find_general_mappings(es_major_version)] return mappings
[ "def", "find_ds_mapping", "(", "data_source", ",", "es_major_version", ")", ":", "mappings", "=", "{", "\"raw\"", ":", "None", ",", "\"enriched\"", ":", "None", "}", "# Backend connectors", "connectors", "=", "get_connectors", "(", ")", "try", ":", "raw_klass", ...
Find the mapping given a perceval data source :param data_source: name of the perceval data source :param es_major_version: string with the major version for Elasticsearch :return: a dict with the mappings (raw and enriched)
[ "Find", "the", "mapping", "given", "a", "perceval", "data", "source" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/utils/gelk_mapping.py#L95-L128
19,753
chaoss/grimoirelab-elk
grimoire_elk/enriched/study_ceres_aoc.py
areas_of_code
def areas_of_code(git_enrich, in_conn, out_conn, block_size=100): """Build and index for areas of code from a given Perceval RAW index. :param block_size: size of items block. :param git_enrich: GitEnrich object to deal with SortingHat affiliations. :param in_conn: ESPandasConnector to read from. :param out_conn: ESPandasConnector to write to. :return: number of documents written in ElasticSearch enriched index. """ aoc = AreasOfCode(in_connector=in_conn, out_connector=out_conn, block_size=block_size, git_enrich=git_enrich) ndocs = aoc.analyze() return ndocs
python
def areas_of_code(git_enrich, in_conn, out_conn, block_size=100): aoc = AreasOfCode(in_connector=in_conn, out_connector=out_conn, block_size=block_size, git_enrich=git_enrich) ndocs = aoc.analyze() return ndocs
[ "def", "areas_of_code", "(", "git_enrich", ",", "in_conn", ",", "out_conn", ",", "block_size", "=", "100", ")", ":", "aoc", "=", "AreasOfCode", "(", "in_connector", "=", "in_conn", ",", "out_connector", "=", "out_conn", ",", "block_size", "=", "block_size", ...
Build and index for areas of code from a given Perceval RAW index. :param block_size: size of items block. :param git_enrich: GitEnrich object to deal with SortingHat affiliations. :param in_conn: ESPandasConnector to read from. :param out_conn: ESPandasConnector to write to. :return: number of documents written in ElasticSearch enriched index.
[ "Build", "and", "index", "for", "areas", "of", "code", "from", "a", "given", "Perceval", "RAW", "index", "." ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/study_ceres_aoc.py#L214-L226
19,754
chaoss/grimoirelab-elk
grimoire_elk/enriched/study_ceres_aoc.py
AreasOfCode.process
def process(self, items_block): """Process items to add file related information. Eventize items creating one new item per each file found in the commit (excluding files with no actions performed on them). For each event, file path, file name, path parts, file type and file extension are added as fields. :param items_block: items to be processed. Expects to find ElasticSearch hits _source part only. """ logger.info(self.__log_prefix + " New commits: " + str(len(items_block))) # Create events from commits git_events = Git(items_block, self._git_enrich) events_df = git_events.eventize(2) logger.info(self.__log_prefix + " New events: " + str(len(events_df))) if len(events_df) > 0: # Filter information data_filtered = FilterRows(events_df) events_df = data_filtered.filter_(["filepath"], "-") logger.info(self.__log_prefix + " New events filtered: " + str(len(events_df))) events_df['message'] = events_df['message'].str.slice(stop=AreasOfCode.MESSAGE_MAX_SIZE) logger.info(self.__log_prefix + " Remove message content") # Add filetype info enriched_filetype = FileType(events_df) events_df = enriched_filetype.enrich('filepath') logger.info(self.__log_prefix + " New Filetype events: " + str(len(events_df))) # Split filepath info enriched_filepath = FilePath(events_df) events_df = enriched_filepath.enrich('filepath') logger.info(self.__log_prefix + " New Filepath events: " + str(len(events_df))) # Deal with surrogates convert = ToUTF8(events_df) events_df = convert.enrich(["owner"]) logger.info(self.__log_prefix + " Final new events: " + str(len(events_df))) return self.ProcessResults(processed=len(events_df), out_items=events_df)
python
def process(self, items_block): logger.info(self.__log_prefix + " New commits: " + str(len(items_block))) # Create events from commits git_events = Git(items_block, self._git_enrich) events_df = git_events.eventize(2) logger.info(self.__log_prefix + " New events: " + str(len(events_df))) if len(events_df) > 0: # Filter information data_filtered = FilterRows(events_df) events_df = data_filtered.filter_(["filepath"], "-") logger.info(self.__log_prefix + " New events filtered: " + str(len(events_df))) events_df['message'] = events_df['message'].str.slice(stop=AreasOfCode.MESSAGE_MAX_SIZE) logger.info(self.__log_prefix + " Remove message content") # Add filetype info enriched_filetype = FileType(events_df) events_df = enriched_filetype.enrich('filepath') logger.info(self.__log_prefix + " New Filetype events: " + str(len(events_df))) # Split filepath info enriched_filepath = FilePath(events_df) events_df = enriched_filepath.enrich('filepath') logger.info(self.__log_prefix + " New Filepath events: " + str(len(events_df))) # Deal with surrogates convert = ToUTF8(events_df) events_df = convert.enrich(["owner"]) logger.info(self.__log_prefix + " Final new events: " + str(len(events_df))) return self.ProcessResults(processed=len(events_df), out_items=events_df)
[ "def", "process", "(", "self", ",", "items_block", ")", ":", "logger", ".", "info", "(", "self", ".", "__log_prefix", "+", "\" New commits: \"", "+", "str", "(", "len", "(", "items_block", ")", ")", ")", "# Create events from commits", "git_events", "=", "Gi...
Process items to add file related information. Eventize items creating one new item per each file found in the commit (excluding files with no actions performed on them). For each event, file path, file name, path parts, file type and file extension are added as fields. :param items_block: items to be processed. Expects to find ElasticSearch hits _source part only.
[ "Process", "items", "to", "add", "file", "related", "information", "." ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/study_ceres_aoc.py#L165-L211
19,755
chaoss/grimoirelab-elk
grimoire_elk/enriched/utils.py
get_time_diff_days
def get_time_diff_days(start, end): ''' Number of days between two dates in UTC format ''' if start is None or end is None: return None if type(start) is not datetime.datetime: start = parser.parse(start).replace(tzinfo=None) if type(end) is not datetime.datetime: end = parser.parse(end).replace(tzinfo=None) seconds_day = float(60 * 60 * 24) diff_days = (end - start).total_seconds() / seconds_day diff_days = float('%.2f' % diff_days) return diff_days
python
def get_time_diff_days(start, end): ''' Number of days between two dates in UTC format ''' if start is None or end is None: return None if type(start) is not datetime.datetime: start = parser.parse(start).replace(tzinfo=None) if type(end) is not datetime.datetime: end = parser.parse(end).replace(tzinfo=None) seconds_day = float(60 * 60 * 24) diff_days = (end - start).total_seconds() / seconds_day diff_days = float('%.2f' % diff_days) return diff_days
[ "def", "get_time_diff_days", "(", "start", ",", "end", ")", ":", "if", "start", "is", "None", "or", "end", "is", "None", ":", "return", "None", "if", "type", "(", "start", ")", "is", "not", "datetime", ".", "datetime", ":", "start", "=", "parser", "....
Number of days between two dates in UTC format
[ "Number", "of", "days", "between", "two", "dates", "in", "UTC", "format" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/utils.py#L91-L106
19,756
chaoss/grimoirelab-elk
grimoire_elk/enriched/phabricator.py
PhabricatorEnrich.__fill_phab_ids
def __fill_phab_ids(self, item): """ Get mappings between phab ids and names """ for p in item['projects']: if p and 'name' in p and 'phid' in p: self.phab_ids_names[p['phid']] = p['name'] if 'authorData' not in item['fields'] or not item['fields']['authorData']: return self.phab_ids_names[item['fields']['authorData']['phid']] = item['fields']['authorData']['userName'] if 'ownerData' in item['fields'] and item['fields']['ownerData']: self.phab_ids_names[item['fields']['ownerData']['phid']] = item['fields']['ownerData']['userName'] if 'priority' in item['fields']: val = item['fields']['priority']['value'] self.phab_ids_names[str(val)] = item['fields']['priority']['name'] for t in item['transactions']: if 'authorData' in t and t['authorData'] and 'userName' in t['authorData']: self.phab_ids_names[t['authorData']['phid']] = t['authorData']['userName'] elif t['authorData'] and 'name' in t['authorData']: # Herald self.phab_ids_names[t['authorData']['phid']] = t['authorData']['name']
python
def __fill_phab_ids(self, item): for p in item['projects']: if p and 'name' in p and 'phid' in p: self.phab_ids_names[p['phid']] = p['name'] if 'authorData' not in item['fields'] or not item['fields']['authorData']: return self.phab_ids_names[item['fields']['authorData']['phid']] = item['fields']['authorData']['userName'] if 'ownerData' in item['fields'] and item['fields']['ownerData']: self.phab_ids_names[item['fields']['ownerData']['phid']] = item['fields']['ownerData']['userName'] if 'priority' in item['fields']: val = item['fields']['priority']['value'] self.phab_ids_names[str(val)] = item['fields']['priority']['name'] for t in item['transactions']: if 'authorData' in t and t['authorData'] and 'userName' in t['authorData']: self.phab_ids_names[t['authorData']['phid']] = t['authorData']['userName'] elif t['authorData'] and 'name' in t['authorData']: # Herald self.phab_ids_names[t['authorData']['phid']] = t['authorData']['name']
[ "def", "__fill_phab_ids", "(", "self", ",", "item", ")", ":", "for", "p", "in", "item", "[", "'projects'", "]", ":", "if", "p", "and", "'name'", "in", "p", "and", "'phid'", "in", "p", ":", "self", ".", "phab_ids_names", "[", "p", "[", "'phid'", "]"...
Get mappings between phab ids and names
[ "Get", "mappings", "between", "phab", "ids", "and", "names" ]
64e08b324b36d9f6909bf705145d6451c8d34e65
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/phabricator.py#L229-L247
19,757
robdmc/crontabs
crontabs/crontabs.py
Tab.starting_at
def starting_at(self, datetime_or_str): """ Set the starting time for the cron job. If not specified, the starting time will always be the beginning of the interval that is current when the cron is started. :param datetime_or_str: a datetime object or a string that dateutil.parser can understand :return: self """ if isinstance(datetime_or_str, str): self._starting_at = parse(datetime_or_str) elif isinstance(datetime_or_str, datetime.datetime): self._starting_at = datetime_or_str else: raise ValueError('.starting_at() method can only take strings or datetime objects') return self
python
def starting_at(self, datetime_or_str): if isinstance(datetime_or_str, str): self._starting_at = parse(datetime_or_str) elif isinstance(datetime_or_str, datetime.datetime): self._starting_at = datetime_or_str else: raise ValueError('.starting_at() method can only take strings or datetime objects') return self
[ "def", "starting_at", "(", "self", ",", "datetime_or_str", ")", ":", "if", "isinstance", "(", "datetime_or_str", ",", "str", ")", ":", "self", ".", "_starting_at", "=", "parse", "(", "datetime_or_str", ")", "elif", "isinstance", "(", "datetime_or_str", ",", ...
Set the starting time for the cron job. If not specified, the starting time will always be the beginning of the interval that is current when the cron is started. :param datetime_or_str: a datetime object or a string that dateutil.parser can understand :return: self
[ "Set", "the", "starting", "time", "for", "the", "cron", "job", ".", "If", "not", "specified", "the", "starting", "time", "will", "always", "be", "the", "beginning", "of", "the", "interval", "that", "is", "current", "when", "the", "cron", "is", "started", ...
3a347f9309eb1b4c7c222363ede338a158f5072c
https://github.com/robdmc/crontabs/blob/3a347f9309eb1b4c7c222363ede338a158f5072c/crontabs/crontabs.py#L61-L75
19,758
robdmc/crontabs
crontabs/crontabs.py
Tab.run
def run(self, func, *func_args, **func__kwargs): """ Specify the function to run at the scheduled times :param func: a callable :param func_args: the args to the callable :param func__kwargs: the kwargs to the callable :return: """ self._func = func self._func_args = func_args self._func_kwargs = func__kwargs return self
python
def run(self, func, *func_args, **func__kwargs): self._func = func self._func_args = func_args self._func_kwargs = func__kwargs return self
[ "def", "run", "(", "self", ",", "func", ",", "*", "func_args", ",", "*", "*", "func__kwargs", ")", ":", "self", ".", "_func", "=", "func", "self", ".", "_func_args", "=", "func_args", "self", ".", "_func_kwargs", "=", "func__kwargs", "return", "self" ]
Specify the function to run at the scheduled times :param func: a callable :param func_args: the args to the callable :param func__kwargs: the kwargs to the callable :return:
[ "Specify", "the", "function", "to", "run", "at", "the", "scheduled", "times" ]
3a347f9309eb1b4c7c222363ede338a158f5072c
https://github.com/robdmc/crontabs/blob/3a347f9309eb1b4c7c222363ede338a158f5072c/crontabs/crontabs.py#L93-L105
19,759
robdmc/crontabs
crontabs/crontabs.py
Tab._get_target
def _get_target(self): """ returns a callable with no arguments designed to be the target of a Subprocess """ if None in [self._func, self._func_kwargs, self._func_kwargs, self._every_kwargs]: raise ValueError('You must call the .every() and .run() methods on every tab.') return self._loop
python
def _get_target(self): if None in [self._func, self._func_kwargs, self._func_kwargs, self._every_kwargs]: raise ValueError('You must call the .every() and .run() methods on every tab.') return self._loop
[ "def", "_get_target", "(", "self", ")", ":", "if", "None", "in", "[", "self", ".", "_func", ",", "self", ".", "_func_kwargs", ",", "self", ".", "_func_kwargs", ",", "self", ".", "_every_kwargs", "]", ":", "raise", "ValueError", "(", "'You must call the .ev...
returns a callable with no arguments designed to be the target of a Subprocess
[ "returns", "a", "callable", "with", "no", "arguments", "designed", "to", "be", "the", "target", "of", "a", "Subprocess" ]
3a347f9309eb1b4c7c222363ede338a158f5072c
https://github.com/robdmc/crontabs/blob/3a347f9309eb1b4c7c222363ede338a158f5072c/crontabs/crontabs.py#L197-L204
19,760
robdmc/crontabs
crontabs/processes.py
wrapped_target
def wrapped_target(target, q_stdout, q_stderr, q_error, robust, name, *args, **kwargs): # pragma: no cover """ Wraps a target with queues replacing stdout and stderr """ import sys sys.stdout = IOQueue(q_stdout) sys.stderr = IOQueue(q_stderr) try: target(*args, **kwargs) except: if not robust: s = 'Error in tab\n' + traceback.format_exc() logger = daiquiri.getLogger(name) logger.error(s) else: raise if not robust: q_error.put(name) raise
python
def wrapped_target(target, q_stdout, q_stderr, q_error, robust, name, *args, **kwargs): # pragma: no cover import sys sys.stdout = IOQueue(q_stdout) sys.stderr = IOQueue(q_stderr) try: target(*args, **kwargs) except: if not robust: s = 'Error in tab\n' + traceback.format_exc() logger = daiquiri.getLogger(name) logger.error(s) else: raise if not robust: q_error.put(name) raise
[ "def", "wrapped_target", "(", "target", ",", "q_stdout", ",", "q_stderr", ",", "q_error", ",", "robust", ",", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# pragma: no cover", "import", "sys", "sys", ".", "stdout", "=", "IOQueue", "(", ...
Wraps a target with queues replacing stdout and stderr
[ "Wraps", "a", "target", "with", "queues", "replacing", "stdout", "and", "stderr" ]
3a347f9309eb1b4c7c222363ede338a158f5072c
https://github.com/robdmc/crontabs/blob/3a347f9309eb1b4c7c222363ede338a158f5072c/crontabs/processes.py#L85-L107
19,761
robdmc/crontabs
crontabs/processes.py
ProcessMonitor.loop
def loop(self, max_seconds=None): """ Main loop for the process. This will run continuously until maxiter """ loop_started = datetime.datetime.now() self._is_running = True while self._is_running: self.process_error_queue(self.q_error) if max_seconds is not None: if (datetime.datetime.now() - loop_started).total_seconds() > max_seconds: break for subprocess in self._subprocesses: if not subprocess.is_alive(): subprocess.start() self.process_io_queue(self.q_stdout, sys.stdout) self.process_io_queue(self.q_stderr, sys.stderr)
python
def loop(self, max_seconds=None): loop_started = datetime.datetime.now() self._is_running = True while self._is_running: self.process_error_queue(self.q_error) if max_seconds is not None: if (datetime.datetime.now() - loop_started).total_seconds() > max_seconds: break for subprocess in self._subprocesses: if not subprocess.is_alive(): subprocess.start() self.process_io_queue(self.q_stdout, sys.stdout) self.process_io_queue(self.q_stderr, sys.stderr)
[ "def", "loop", "(", "self", ",", "max_seconds", "=", "None", ")", ":", "loop_started", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "self", ".", "_is_running", "=", "True", "while", "self", ".", "_is_running", ":", "self", ".", "process_error_...
Main loop for the process. This will run continuously until maxiter
[ "Main", "loop", "for", "the", "process", ".", "This", "will", "run", "continuously", "until", "maxiter" ]
3a347f9309eb1b4c7c222363ede338a158f5072c
https://github.com/robdmc/crontabs/blob/3a347f9309eb1b4c7c222363ede338a158f5072c/crontabs/processes.py#L156-L174
19,762
gusutabopb/aioinflux
aioinflux/serialization/common.py
escape
def escape(string, escape_pattern): """Assistant function for string escaping""" try: return string.translate(escape_pattern) except AttributeError: warnings.warn("Non-string-like data passed. " "Attempting to convert to 'str'.") return str(string).translate(tag_escape)
python
def escape(string, escape_pattern): try: return string.translate(escape_pattern) except AttributeError: warnings.warn("Non-string-like data passed. " "Attempting to convert to 'str'.") return str(string).translate(tag_escape)
[ "def", "escape", "(", "string", ",", "escape_pattern", ")", ":", "try", ":", "return", "string", ".", "translate", "(", "escape_pattern", ")", "except", "AttributeError", ":", "warnings", ".", "warn", "(", "\"Non-string-like data passed. \"", "\"Attempting to conver...
Assistant function for string escaping
[ "Assistant", "function", "for", "string", "escaping" ]
2e4b7b3e13604e7618c686d89a0673f0bc70b24e
https://github.com/gusutabopb/aioinflux/blob/2e4b7b3e13604e7618c686d89a0673f0bc70b24e/aioinflux/serialization/common.py#L13-L20
19,763
gusutabopb/aioinflux
aioinflux/serialization/usertype.py
_make_serializer
def _make_serializer(meas, schema, rm_none, extra_tags, placeholder): # noqa: C901 """Factory of line protocol parsers""" _validate_schema(schema, placeholder) tags = [] fields = [] ts = None meas = meas for k, t in schema.items(): if t is MEASUREMENT: meas = f"{{i.{k}}}" elif t is TIMEINT: ts = f"{{i.{k}}}" elif t is TIMESTR: if pd: ts = f"{{pd.Timestamp(i.{k} or 0).value}}" else: ts = f"{{dt_to_int(str_to_dt(i.{k}))}}" elif t is TIMEDT: if pd: ts = f"{{pd.Timestamp(i.{k} or 0).value}}" else: ts = f"{{dt_to_int(i.{k})}}" elif t is TAG: tags.append(f"{k}={{str(i.{k}).translate(tag_escape)}}") elif t is TAGENUM: tags.append(f"{k}={{getattr(i.{k}, 'name', i.{k} or None)}}") elif t in (FLOAT, BOOL): fields.append(f"{k}={{i.{k}}}") elif t is INT: fields.append(f"{k}={{i.{k}}}i") elif t is STR: fields.append(f"{k}=\\\"{{str(i.{k}).translate(str_escape)}}\\\"") elif t is ENUM: fields.append(f"{k}=\\\"{{getattr(i.{k}, 'name', i.{k} or None)}}\\\"") else: raise SchemaError(f"Invalid attribute type {k!r}: {t!r}") extra_tags = extra_tags or {} for k, v in extra_tags.items(): tags.append(f"{k}={v}") if placeholder: fields.insert(0, f"_=true") sep = ',' if tags else '' ts = f' {ts}' if ts else '' fmt = f"{meas}{sep}{','.join(tags)} {','.join(fields)}{ts}" if rm_none: # Has substantial runtime impact. Best avoided if performance is critical. # First field can't be removed. pat = r',\w+="?None"?i?' f = eval('lambda i: re.sub(r\'{}\', "", f"{}").encode()'.format(pat, fmt)) else: f = eval('lambda i: f"{}".encode()'.format(fmt)) f.__doc__ = "Returns InfluxDB line protocol representation of user-defined class" f._args = dict(meas=meas, schema=schema, rm_none=rm_none, extra_tags=extra_tags, placeholder=placeholder) return f
python
def _make_serializer(meas, schema, rm_none, extra_tags, placeholder): # noqa: C901 _validate_schema(schema, placeholder) tags = [] fields = [] ts = None meas = meas for k, t in schema.items(): if t is MEASUREMENT: meas = f"{{i.{k}}}" elif t is TIMEINT: ts = f"{{i.{k}}}" elif t is TIMESTR: if pd: ts = f"{{pd.Timestamp(i.{k} or 0).value}}" else: ts = f"{{dt_to_int(str_to_dt(i.{k}))}}" elif t is TIMEDT: if pd: ts = f"{{pd.Timestamp(i.{k} or 0).value}}" else: ts = f"{{dt_to_int(i.{k})}}" elif t is TAG: tags.append(f"{k}={{str(i.{k}).translate(tag_escape)}}") elif t is TAGENUM: tags.append(f"{k}={{getattr(i.{k}, 'name', i.{k} or None)}}") elif t in (FLOAT, BOOL): fields.append(f"{k}={{i.{k}}}") elif t is INT: fields.append(f"{k}={{i.{k}}}i") elif t is STR: fields.append(f"{k}=\\\"{{str(i.{k}).translate(str_escape)}}\\\"") elif t is ENUM: fields.append(f"{k}=\\\"{{getattr(i.{k}, 'name', i.{k} or None)}}\\\"") else: raise SchemaError(f"Invalid attribute type {k!r}: {t!r}") extra_tags = extra_tags or {} for k, v in extra_tags.items(): tags.append(f"{k}={v}") if placeholder: fields.insert(0, f"_=true") sep = ',' if tags else '' ts = f' {ts}' if ts else '' fmt = f"{meas}{sep}{','.join(tags)} {','.join(fields)}{ts}" if rm_none: # Has substantial runtime impact. Best avoided if performance is critical. # First field can't be removed. pat = r',\w+="?None"?i?' f = eval('lambda i: re.sub(r\'{}\', "", f"{}").encode()'.format(pat, fmt)) else: f = eval('lambda i: f"{}".encode()'.format(fmt)) f.__doc__ = "Returns InfluxDB line protocol representation of user-defined class" f._args = dict(meas=meas, schema=schema, rm_none=rm_none, extra_tags=extra_tags, placeholder=placeholder) return f
[ "def", "_make_serializer", "(", "meas", ",", "schema", ",", "rm_none", ",", "extra_tags", ",", "placeholder", ")", ":", "# noqa: C901", "_validate_schema", "(", "schema", ",", "placeholder", ")", "tags", "=", "[", "]", "fields", "=", "[", "]", "ts", "=", ...
Factory of line protocol parsers
[ "Factory", "of", "line", "protocol", "parsers" ]
2e4b7b3e13604e7618c686d89a0673f0bc70b24e
https://github.com/gusutabopb/aioinflux/blob/2e4b7b3e13604e7618c686d89a0673f0bc70b24e/aioinflux/serialization/usertype.py#L67-L122
19,764
gusutabopb/aioinflux
aioinflux/serialization/usertype.py
lineprotocol
def lineprotocol( cls=None, *, schema: Optional[Mapping[str, type]] = None, rm_none: bool = False, extra_tags: Optional[Mapping[str, str]] = None, placeholder: bool = False ): """Adds ``to_lineprotocol`` method to arbitrary user-defined classes :param cls: Class to monkey-patch :param schema: Schema dictionary (attr/type pairs). :param rm_none: Whether apply a regex to remove ``None`` values. If ``False``, passing ``None`` values to boolean, integer or float or time fields will result in write errors. Setting to ``True`` is "safer" but impacts performance. :param extra_tags: Hard coded tags to be added to every point generated. :param placeholder: If no field attributes are present, add a placeholder attribute (``_``) which is always equal to ``True``. This is a workaround for creating field-less points (which is not supported natively by InfluxDB) """ def _lineprotocol(cls): _schema = schema or getattr(cls, '__annotations__', {}) f = _make_serializer(cls.__name__, _schema, rm_none, extra_tags, placeholder) cls.to_lineprotocol = f return cls return _lineprotocol(cls) if cls else _lineprotocol
python
def lineprotocol( cls=None, *, schema: Optional[Mapping[str, type]] = None, rm_none: bool = False, extra_tags: Optional[Mapping[str, str]] = None, placeholder: bool = False ): def _lineprotocol(cls): _schema = schema or getattr(cls, '__annotations__', {}) f = _make_serializer(cls.__name__, _schema, rm_none, extra_tags, placeholder) cls.to_lineprotocol = f return cls return _lineprotocol(cls) if cls else _lineprotocol
[ "def", "lineprotocol", "(", "cls", "=", "None", ",", "*", ",", "schema", ":", "Optional", "[", "Mapping", "[", "str", ",", "type", "]", "]", "=", "None", ",", "rm_none", ":", "bool", "=", "False", ",", "extra_tags", ":", "Optional", "[", "Mapping", ...
Adds ``to_lineprotocol`` method to arbitrary user-defined classes :param cls: Class to monkey-patch :param schema: Schema dictionary (attr/type pairs). :param rm_none: Whether apply a regex to remove ``None`` values. If ``False``, passing ``None`` values to boolean, integer or float or time fields will result in write errors. Setting to ``True`` is "safer" but impacts performance. :param extra_tags: Hard coded tags to be added to every point generated. :param placeholder: If no field attributes are present, add a placeholder attribute (``_``) which is always equal to ``True``. This is a workaround for creating field-less points (which is not supported natively by InfluxDB)
[ "Adds", "to_lineprotocol", "method", "to", "arbitrary", "user", "-", "defined", "classes" ]
2e4b7b3e13604e7618c686d89a0673f0bc70b24e
https://github.com/gusutabopb/aioinflux/blob/2e4b7b3e13604e7618c686d89a0673f0bc70b24e/aioinflux/serialization/usertype.py#L125-L152
19,765
gusutabopb/aioinflux
aioinflux/serialization/mapping.py
_serialize_fields
def _serialize_fields(point): """Field values can be floats, integers, strings, or Booleans.""" output = [] for k, v in point['fields'].items(): k = escape(k, key_escape) if isinstance(v, bool): output.append(f'{k}={v}') elif isinstance(v, int): output.append(f'{k}={v}i') elif isinstance(v, str): output.append(f'{k}="{v.translate(str_escape)}"') elif v is None: # Empty values continue else: # Floats output.append(f'{k}={v}') return ','.join(output)
python
def _serialize_fields(point): output = [] for k, v in point['fields'].items(): k = escape(k, key_escape) if isinstance(v, bool): output.append(f'{k}={v}') elif isinstance(v, int): output.append(f'{k}={v}i') elif isinstance(v, str): output.append(f'{k}="{v.translate(str_escape)}"') elif v is None: # Empty values continue else: # Floats output.append(f'{k}={v}') return ','.join(output)
[ "def", "_serialize_fields", "(", "point", ")", ":", "output", "=", "[", "]", "for", "k", ",", "v", "in", "point", "[", "'fields'", "]", ".", "items", "(", ")", ":", "k", "=", "escape", "(", "k", ",", "key_escape", ")", "if", "isinstance", "(", "v...
Field values can be floats, integers, strings, or Booleans.
[ "Field", "values", "can", "be", "floats", "integers", "strings", "or", "Booleans", "." ]
2e4b7b3e13604e7618c686d89a0673f0bc70b24e
https://github.com/gusutabopb/aioinflux/blob/2e4b7b3e13604e7618c686d89a0673f0bc70b24e/aioinflux/serialization/mapping.py#L57-L74
19,766
gusutabopb/aioinflux
aioinflux/serialization/__init__.py
serialize
def serialize(data, measurement=None, tag_columns=None, **extra_tags): """Converts input data into line protocol format""" if isinstance(data, bytes): return data elif isinstance(data, str): return data.encode('utf-8') elif hasattr(data, 'to_lineprotocol'): return data.to_lineprotocol() elif pd is not None and isinstance(data, pd.DataFrame): return dataframe.serialize(data, measurement, tag_columns, **extra_tags) elif isinstance(data, dict): return mapping.serialize(data, measurement, **extra_tags) elif hasattr(data, '__iter__'): return b'\n'.join([serialize(i, measurement, tag_columns, **extra_tags) for i in data]) else: raise ValueError('Invalid input', data)
python
def serialize(data, measurement=None, tag_columns=None, **extra_tags): if isinstance(data, bytes): return data elif isinstance(data, str): return data.encode('utf-8') elif hasattr(data, 'to_lineprotocol'): return data.to_lineprotocol() elif pd is not None and isinstance(data, pd.DataFrame): return dataframe.serialize(data, measurement, tag_columns, **extra_tags) elif isinstance(data, dict): return mapping.serialize(data, measurement, **extra_tags) elif hasattr(data, '__iter__'): return b'\n'.join([serialize(i, measurement, tag_columns, **extra_tags) for i in data]) else: raise ValueError('Invalid input', data)
[ "def", "serialize", "(", "data", ",", "measurement", "=", "None", ",", "tag_columns", "=", "None", ",", "*", "*", "extra_tags", ")", ":", "if", "isinstance", "(", "data", ",", "bytes", ")", ":", "return", "data", "elif", "isinstance", "(", "data", ",",...
Converts input data into line protocol format
[ "Converts", "input", "data", "into", "line", "protocol", "format" ]
2e4b7b3e13604e7618c686d89a0673f0bc70b24e
https://github.com/gusutabopb/aioinflux/blob/2e4b7b3e13604e7618c686d89a0673f0bc70b24e/aioinflux/serialization/__init__.py#L9-L24
19,767
gusutabopb/aioinflux
aioinflux/iterutils.py
iterpoints
def iterpoints(resp: dict, parser: Optional[Callable] = None) -> Iterator[Any]: """Iterates a response JSON yielding data point by point. Can be used with both regular and chunked responses. By default, returns just a plain list of values representing each point, without column names, or other metadata. In case a specific format is needed, an optional ``parser`` argument can be passed. ``parser`` is a function/callable that takes data point values and, optionally, a ``meta`` parameter containing which takes a dictionary containing all or a subset of the following: ``{'columns', 'name', 'tags', 'statement_id'}``. Sample parser functions: .. code:: python # Function optional meta argument def parser(*x, meta): return dict(zip(meta['columns'], x)) # Namedtuple (callable) from collections import namedtuple parser = namedtuple('MyPoint', ['col1', 'col2', 'col3']) :param resp: Dictionary containing parsed JSON (output from InfluxDBClient.query) :param parser: Optional parser function/callable :return: Generator object """ for statement in resp['results']: if 'series' not in statement: continue for series in statement['series']: if parser is None: return (x for x in series['values']) elif 'meta' in inspect.signature(parser).parameters: meta = {k: series[k] for k in series if k != 'values'} meta['statement_id'] = statement['statement_id'] return (parser(*x, meta=meta) for x in series['values']) else: return (parser(*x) for x in series['values']) return iter([])
python
def iterpoints(resp: dict, parser: Optional[Callable] = None) -> Iterator[Any]: for statement in resp['results']: if 'series' not in statement: continue for series in statement['series']: if parser is None: return (x for x in series['values']) elif 'meta' in inspect.signature(parser).parameters: meta = {k: series[k] for k in series if k != 'values'} meta['statement_id'] = statement['statement_id'] return (parser(*x, meta=meta) for x in series['values']) else: return (parser(*x) for x in series['values']) return iter([])
[ "def", "iterpoints", "(", "resp", ":", "dict", ",", "parser", ":", "Optional", "[", "Callable", "]", "=", "None", ")", "->", "Iterator", "[", "Any", "]", ":", "for", "statement", "in", "resp", "[", "'results'", "]", ":", "if", "'series'", "not", "in"...
Iterates a response JSON yielding data point by point. Can be used with both regular and chunked responses. By default, returns just a plain list of values representing each point, without column names, or other metadata. In case a specific format is needed, an optional ``parser`` argument can be passed. ``parser`` is a function/callable that takes data point values and, optionally, a ``meta`` parameter containing which takes a dictionary containing all or a subset of the following: ``{'columns', 'name', 'tags', 'statement_id'}``. Sample parser functions: .. code:: python # Function optional meta argument def parser(*x, meta): return dict(zip(meta['columns'], x)) # Namedtuple (callable) from collections import namedtuple parser = namedtuple('MyPoint', ['col1', 'col2', 'col3']) :param resp: Dictionary containing parsed JSON (output from InfluxDBClient.query) :param parser: Optional parser function/callable :return: Generator object
[ "Iterates", "a", "response", "JSON", "yielding", "data", "point", "by", "point", "." ]
2e4b7b3e13604e7618c686d89a0673f0bc70b24e
https://github.com/gusutabopb/aioinflux/blob/2e4b7b3e13604e7618c686d89a0673f0bc70b24e/aioinflux/iterutils.py#L6-L48
19,768
gusutabopb/aioinflux
aioinflux/serialization/dataframe.py
parse
def parse(resp) -> DataFrameType: """Makes a dictionary of DataFrames from a response object""" statements = [] for statement in resp['results']: series = {} for s in statement.get('series', []): series[_get_name(s)] = _drop_zero_index(_serializer(s)) statements.append(series) if len(statements) == 1: series: dict = statements[0] if len(series) == 1: return list(series.values())[0] # DataFrame else: return series # dict return statements
python
def parse(resp) -> DataFrameType: statements = [] for statement in resp['results']: series = {} for s in statement.get('series', []): series[_get_name(s)] = _drop_zero_index(_serializer(s)) statements.append(series) if len(statements) == 1: series: dict = statements[0] if len(series) == 1: return list(series.values())[0] # DataFrame else: return series # dict return statements
[ "def", "parse", "(", "resp", ")", "->", "DataFrameType", ":", "statements", "=", "[", "]", "for", "statement", "in", "resp", "[", "'results'", "]", ":", "series", "=", "{", "}", "for", "s", "in", "statement", ".", "get", "(", "'series'", ",", "[", ...
Makes a dictionary of DataFrames from a response object
[ "Makes", "a", "dictionary", "of", "DataFrames", "from", "a", "response", "object" ]
2e4b7b3e13604e7618c686d89a0673f0bc70b24e
https://github.com/gusutabopb/aioinflux/blob/2e4b7b3e13604e7618c686d89a0673f0bc70b24e/aioinflux/serialization/dataframe.py#L44-L59
19,769
gusutabopb/aioinflux
aioinflux/serialization/dataframe.py
_itertuples
def _itertuples(df): """Custom implementation of ``DataFrame.itertuples`` that returns plain tuples instead of namedtuples. About 50% faster. """ cols = [df.iloc[:, k] for k in range(len(df.columns))] return zip(df.index, *cols)
python
def _itertuples(df): cols = [df.iloc[:, k] for k in range(len(df.columns))] return zip(df.index, *cols)
[ "def", "_itertuples", "(", "df", ")", ":", "cols", "=", "[", "df", ".", "iloc", "[", ":", ",", "k", "]", "for", "k", "in", "range", "(", "len", "(", "df", ".", "columns", ")", ")", "]", "return", "zip", "(", "df", ".", "index", ",", "*", "c...
Custom implementation of ``DataFrame.itertuples`` that returns plain tuples instead of namedtuples. About 50% faster.
[ "Custom", "implementation", "of", "DataFrame", ".", "itertuples", "that", "returns", "plain", "tuples", "instead", "of", "namedtuples", ".", "About", "50%", "faster", "." ]
2e4b7b3e13604e7618c686d89a0673f0bc70b24e
https://github.com/gusutabopb/aioinflux/blob/2e4b7b3e13604e7618c686d89a0673f0bc70b24e/aioinflux/serialization/dataframe.py#L65-L70
19,770
gusutabopb/aioinflux
aioinflux/serialization/dataframe.py
serialize
def serialize(df, measurement, tag_columns=None, **extra_tags) -> bytes: """Converts a Pandas DataFrame into line protocol format""" # Pre-processing if measurement is None: raise ValueError("Missing 'measurement'") if not isinstance(df.index, pd.DatetimeIndex): raise ValueError('DataFrame index is not DatetimeIndex') tag_columns = set(tag_columns or []) isnull = df.isnull().any(axis=1) # Make parser function tags = [] fields = [] for k, v in extra_tags.items(): tags.append(f"{k}={escape(v, key_escape)}") for i, (k, v) in enumerate(df.dtypes.items()): k = k.translate(key_escape) if k in tag_columns: tags.append(f"{k}={{p[{i+1}]}}") elif issubclass(v.type, np.integer): fields.append(f"{k}={{p[{i+1}]}}i") elif issubclass(v.type, (np.float, np.bool_)): fields.append(f"{k}={{p[{i+1}]}}") else: # String escaping is skipped for performance reasons # Strings containing double-quotes can cause strange write errors # and should be sanitized by the user. # e.g., df[k] = df[k].astype('str').str.translate(str_escape) fields.append(f"{k}=\"{{p[{i+1}]}}\"") fmt = (f'{measurement}', f'{"," if tags else ""}', ','.join(tags), ' ', ','.join(fields), ' {p[0].value}') f = eval("lambda p: f'{}'".format(''.join(fmt))) # Map/concat if isnull.any(): lp = map(f, _itertuples(df[~isnull])) rep = _replace(df) lp_nan = (reduce(lambda a, b: re.sub(*b, a), rep, f(p)) for p in _itertuples(df[isnull])) return '\n'.join(chain(lp, lp_nan)).encode('utf-8') else: return '\n'.join(map(f, _itertuples(df))).encode('utf-8')
python
def serialize(df, measurement, tag_columns=None, **extra_tags) -> bytes: # Pre-processing if measurement is None: raise ValueError("Missing 'measurement'") if not isinstance(df.index, pd.DatetimeIndex): raise ValueError('DataFrame index is not DatetimeIndex') tag_columns = set(tag_columns or []) isnull = df.isnull().any(axis=1) # Make parser function tags = [] fields = [] for k, v in extra_tags.items(): tags.append(f"{k}={escape(v, key_escape)}") for i, (k, v) in enumerate(df.dtypes.items()): k = k.translate(key_escape) if k in tag_columns: tags.append(f"{k}={{p[{i+1}]}}") elif issubclass(v.type, np.integer): fields.append(f"{k}={{p[{i+1}]}}i") elif issubclass(v.type, (np.float, np.bool_)): fields.append(f"{k}={{p[{i+1}]}}") else: # String escaping is skipped for performance reasons # Strings containing double-quotes can cause strange write errors # and should be sanitized by the user. # e.g., df[k] = df[k].astype('str').str.translate(str_escape) fields.append(f"{k}=\"{{p[{i+1}]}}\"") fmt = (f'{measurement}', f'{"," if tags else ""}', ','.join(tags), ' ', ','.join(fields), ' {p[0].value}') f = eval("lambda p: f'{}'".format(''.join(fmt))) # Map/concat if isnull.any(): lp = map(f, _itertuples(df[~isnull])) rep = _replace(df) lp_nan = (reduce(lambda a, b: re.sub(*b, a), rep, f(p)) for p in _itertuples(df[isnull])) return '\n'.join(chain(lp, lp_nan)).encode('utf-8') else: return '\n'.join(map(f, _itertuples(df))).encode('utf-8')
[ "def", "serialize", "(", "df", ",", "measurement", ",", "tag_columns", "=", "None", ",", "*", "*", "extra_tags", ")", "->", "bytes", ":", "# Pre-processing", "if", "measurement", "is", "None", ":", "raise", "ValueError", "(", "\"Missing 'measurement'\"", ")", ...
Converts a Pandas DataFrame into line protocol format
[ "Converts", "a", "Pandas", "DataFrame", "into", "line", "protocol", "format" ]
2e4b7b3e13604e7618c686d89a0673f0bc70b24e
https://github.com/gusutabopb/aioinflux/blob/2e4b7b3e13604e7618c686d89a0673f0bc70b24e/aioinflux/serialization/dataframe.py#L86-L127
19,771
gusutabopb/aioinflux
aioinflux/client.py
runner
def runner(coro): """Function execution decorator.""" @wraps(coro) def inner(self, *args, **kwargs): if self.mode == 'async': return coro(self, *args, **kwargs) return self._loop.run_until_complete(coro(self, *args, **kwargs)) return inner
python
def runner(coro): @wraps(coro) def inner(self, *args, **kwargs): if self.mode == 'async': return coro(self, *args, **kwargs) return self._loop.run_until_complete(coro(self, *args, **kwargs)) return inner
[ "def", "runner", "(", "coro", ")", ":", "@", "wraps", "(", "coro", ")", "def", "inner", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "mode", "==", "'async'", ":", "return", "coro", "(", "self", ",", "*", ...
Function execution decorator.
[ "Function", "execution", "decorator", "." ]
2e4b7b3e13604e7618c686d89a0673f0bc70b24e
https://github.com/gusutabopb/aioinflux/blob/2e4b7b3e13604e7618c686d89a0673f0bc70b24e/aioinflux/client.py#L25-L34
19,772
gusutabopb/aioinflux
aioinflux/client.py
InfluxDBClient._check_error
def _check_error(response): """Checks for JSON error messages and raises Python exception""" if 'error' in response: raise InfluxDBError(response['error']) elif 'results' in response: for statement in response['results']: if 'error' in statement: msg = '{d[error]} (statement {d[statement_id]})' raise InfluxDBError(msg.format(d=statement))
python
def _check_error(response): if 'error' in response: raise InfluxDBError(response['error']) elif 'results' in response: for statement in response['results']: if 'error' in statement: msg = '{d[error]} (statement {d[statement_id]})' raise InfluxDBError(msg.format(d=statement))
[ "def", "_check_error", "(", "response", ")", ":", "if", "'error'", "in", "response", ":", "raise", "InfluxDBError", "(", "response", "[", "'error'", "]", ")", "elif", "'results'", "in", "response", ":", "for", "statement", "in", "response", "[", "'results'",...
Checks for JSON error messages and raises Python exception
[ "Checks", "for", "JSON", "error", "messages", "and", "raises", "Python", "exception" ]
2e4b7b3e13604e7618c686d89a0673f0bc70b24e
https://github.com/gusutabopb/aioinflux/blob/2e4b7b3e13604e7618c686d89a0673f0bc70b24e/aioinflux/client.py#L384-L392
19,773
remcohaszing/pywakeonlan
wakeonlan.py
create_magic_packet
def create_magic_packet(macaddress): """ Create a magic packet. A magic packet is a packet that can be used with the for wake on lan protocol to wake up a computer. The packet is constructed from the mac address given as a parameter. Args: macaddress (str): the mac address that should be parsed into a magic packet. """ if len(macaddress) == 12: pass elif len(macaddress) == 17: sep = macaddress[2] macaddress = macaddress.replace(sep, '') else: raise ValueError('Incorrect MAC address format') # Pad the synchronization stream data = b'FFFFFFFFFFFF' + (macaddress * 16).encode() send_data = b'' # Split up the hex values in pack for i in range(0, len(data), 2): send_data += struct.pack(b'B', int(data[i: i + 2], 16)) return send_data
python
def create_magic_packet(macaddress): if len(macaddress) == 12: pass elif len(macaddress) == 17: sep = macaddress[2] macaddress = macaddress.replace(sep, '') else: raise ValueError('Incorrect MAC address format') # Pad the synchronization stream data = b'FFFFFFFFFFFF' + (macaddress * 16).encode() send_data = b'' # Split up the hex values in pack for i in range(0, len(data), 2): send_data += struct.pack(b'B', int(data[i: i + 2], 16)) return send_data
[ "def", "create_magic_packet", "(", "macaddress", ")", ":", "if", "len", "(", "macaddress", ")", "==", "12", ":", "pass", "elif", "len", "(", "macaddress", ")", "==", "17", ":", "sep", "=", "macaddress", "[", "2", "]", "macaddress", "=", "macaddress", "...
Create a magic packet. A magic packet is a packet that can be used with the for wake on lan protocol to wake up a computer. The packet is constructed from the mac address given as a parameter. Args: macaddress (str): the mac address that should be parsed into a magic packet.
[ "Create", "a", "magic", "packet", "." ]
d30b66172c483c4baadb426f493c3de30fecc19b
https://github.com/remcohaszing/pywakeonlan/blob/d30b66172c483c4baadb426f493c3de30fecc19b/wakeonlan.py#L19-L47
19,774
remcohaszing/pywakeonlan
wakeonlan.py
send_magic_packet
def send_magic_packet(*macs, **kwargs): """ Wake up computers having any of the given mac addresses. Wake on lan must be enabled on the host device. Args: macs (str): One or more macaddresses of machines to wake. Keyword Args: ip_address (str): the ip address of the host to send the magic packet to (default "255.255.255.255") port (int): the port of the host to send the magic packet to (default 9) """ packets = [] ip = kwargs.pop('ip_address', BROADCAST_IP) port = kwargs.pop('port', DEFAULT_PORT) for k in kwargs: raise TypeError('send_magic_packet() got an unexpected keyword ' 'argument {!r}'.format(k)) for mac in macs: packet = create_magic_packet(mac) packets.append(packet) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) sock.connect((ip, port)) for packet in packets: sock.send(packet) sock.close()
python
def send_magic_packet(*macs, **kwargs): packets = [] ip = kwargs.pop('ip_address', BROADCAST_IP) port = kwargs.pop('port', DEFAULT_PORT) for k in kwargs: raise TypeError('send_magic_packet() got an unexpected keyword ' 'argument {!r}'.format(k)) for mac in macs: packet = create_magic_packet(mac) packets.append(packet) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) sock.connect((ip, port)) for packet in packets: sock.send(packet) sock.close()
[ "def", "send_magic_packet", "(", "*", "macs", ",", "*", "*", "kwargs", ")", ":", "packets", "=", "[", "]", "ip", "=", "kwargs", ".", "pop", "(", "'ip_address'", ",", "BROADCAST_IP", ")", "port", "=", "kwargs", ".", "pop", "(", "'port'", ",", "DEFAULT...
Wake up computers having any of the given mac addresses. Wake on lan must be enabled on the host device. Args: macs (str): One or more macaddresses of machines to wake. Keyword Args: ip_address (str): the ip address of the host to send the magic packet to (default "255.255.255.255") port (int): the port of the host to send the magic packet to (default 9)
[ "Wake", "up", "computers", "having", "any", "of", "the", "given", "mac", "addresses", "." ]
d30b66172c483c4baadb426f493c3de30fecc19b
https://github.com/remcohaszing/pywakeonlan/blob/d30b66172c483c4baadb426f493c3de30fecc19b/wakeonlan.py#L50-L82
19,775
remcohaszing/pywakeonlan
wakeonlan.py
main
def main(argv=None): """ Run wake on lan as a CLI application. """ parser = argparse.ArgumentParser( description='Wake one or more computers using the wake on lan' ' protocol.') parser.add_argument( 'macs', metavar='mac address', nargs='+', help='The mac addresses or of the computers you are trying to wake.') parser.add_argument( '-i', metavar='ip', default=BROADCAST_IP, help='The ip address of the host to send the magic packet to.' ' (default {})'.format(BROADCAST_IP)) parser.add_argument( '-p', metavar='port', type=int, default=DEFAULT_PORT, help='The port of the host to send the magic packet to (default 9)') args = parser.parse_args(argv) send_magic_packet(*args.macs, ip_address=args.i, port=args.p)
python
def main(argv=None): parser = argparse.ArgumentParser( description='Wake one or more computers using the wake on lan' ' protocol.') parser.add_argument( 'macs', metavar='mac address', nargs='+', help='The mac addresses or of the computers you are trying to wake.') parser.add_argument( '-i', metavar='ip', default=BROADCAST_IP, help='The ip address of the host to send the magic packet to.' ' (default {})'.format(BROADCAST_IP)) parser.add_argument( '-p', metavar='port', type=int, default=DEFAULT_PORT, help='The port of the host to send the magic packet to (default 9)') args = parser.parse_args(argv) send_magic_packet(*args.macs, ip_address=args.i, port=args.p)
[ "def", "main", "(", "argv", "=", "None", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Wake one or more computers using the wake on lan'", "' protocol.'", ")", "parser", ".", "add_argument", "(", "'macs'", ",", "metavar", "...
Run wake on lan as a CLI application.
[ "Run", "wake", "on", "lan", "as", "a", "CLI", "application", "." ]
d30b66172c483c4baadb426f493c3de30fecc19b
https://github.com/remcohaszing/pywakeonlan/blob/d30b66172c483c4baadb426f493c3de30fecc19b/wakeonlan.py#L85-L111
19,776
liminspace/django-mjml
mjml/templatetags/mjml.py
mjml
def mjml(parser, token): """ Compile MJML template after render django template. Usage: {% mjml %} .. MJML template code .. {% endmjml %} """ nodelist = parser.parse(('endmjml',)) parser.delete_first_token() tokens = token.split_contents() if len(tokens) != 1: raise template.TemplateSyntaxError("'%r' tag doesn't receive any arguments." % tokens[0]) return MJMLRenderNode(nodelist)
python
def mjml(parser, token): nodelist = parser.parse(('endmjml',)) parser.delete_first_token() tokens = token.split_contents() if len(tokens) != 1: raise template.TemplateSyntaxError("'%r' tag doesn't receive any arguments." % tokens[0]) return MJMLRenderNode(nodelist)
[ "def", "mjml", "(", "parser", ",", "token", ")", ":", "nodelist", "=", "parser", ".", "parse", "(", "(", "'endmjml'", ",", ")", ")", "parser", ".", "delete_first_token", "(", ")", "tokens", "=", "token", ".", "split_contents", "(", ")", "if", "len", ...
Compile MJML template after render django template. Usage: {% mjml %} .. MJML template code .. {% endmjml %}
[ "Compile", "MJML", "template", "after", "render", "django", "template", "." ]
6f3e5959ccd35d1b2bcebc6f892a9400294736fb
https://github.com/liminspace/django-mjml/blob/6f3e5959ccd35d1b2bcebc6f892a9400294736fb/mjml/templatetags/mjml.py#L18-L32
19,777
moonso/vcf_parser
vcf_parser/header_parser.py
HeaderParser.parse_header_line
def parse_header_line(self, line): """docstring for parse_header_line""" self.header = line[1:].rstrip().split('\t') if len(self.header) < 9: self.header = line[1:].rstrip().split() self.individuals = self.header[9:]
python
def parse_header_line(self, line): self.header = line[1:].rstrip().split('\t') if len(self.header) < 9: self.header = line[1:].rstrip().split() self.individuals = self.header[9:]
[ "def", "parse_header_line", "(", "self", ",", "line", ")", ":", "self", ".", "header", "=", "line", "[", "1", ":", "]", ".", "rstrip", "(", ")", ".", "split", "(", "'\\t'", ")", "if", "len", "(", "self", ".", "header", ")", "<", "9", ":", "self...
docstring for parse_header_line
[ "docstring", "for", "parse_header_line" ]
8e2b6724e31995e0d43af501f25974310c6b843b
https://github.com/moonso/vcf_parser/blob/8e2b6724e31995e0d43af501f25974310c6b843b/vcf_parser/header_parser.py#L178-L183
19,778
moonso/vcf_parser
vcf_parser/header_parser.py
HeaderParser.print_header
def print_header(self): """Returns a list with the header lines if proper format""" lines_to_print = [] lines_to_print.append('##fileformat='+self.fileformat) if self.filedate: lines_to_print.append('##fileformat='+self.fileformat) for filt in self.filter_dict: lines_to_print.append(self.filter_dict[filt]) for form in self.format_dict: lines_to_print.append(self.format_dict[form]) for info in self.info_dict: lines_to_print.append(self.info_dict[info]) for contig in self.contig_dict: lines_to_print.append(self.contig_dict[contig]) for alt in self.alt_dict: lines_to_print.append(self.alt_dict[alt]) for other in self.other_dict: lines_to_print.append(self.other_dict[other]) lines_to_print.append('#'+ '\t'.join(self.header)) return lines_to_print
python
def print_header(self): lines_to_print = [] lines_to_print.append('##fileformat='+self.fileformat) if self.filedate: lines_to_print.append('##fileformat='+self.fileformat) for filt in self.filter_dict: lines_to_print.append(self.filter_dict[filt]) for form in self.format_dict: lines_to_print.append(self.format_dict[form]) for info in self.info_dict: lines_to_print.append(self.info_dict[info]) for contig in self.contig_dict: lines_to_print.append(self.contig_dict[contig]) for alt in self.alt_dict: lines_to_print.append(self.alt_dict[alt]) for other in self.other_dict: lines_to_print.append(self.other_dict[other]) lines_to_print.append('#'+ '\t'.join(self.header)) return lines_to_print
[ "def", "print_header", "(", "self", ")", ":", "lines_to_print", "=", "[", "]", "lines_to_print", ".", "append", "(", "'##fileformat='", "+", "self", ".", "fileformat", ")", "if", "self", ".", "filedate", ":", "lines_to_print", ".", "append", "(", "'##filefor...
Returns a list with the header lines if proper format
[ "Returns", "a", "list", "with", "the", "header", "lines", "if", "proper", "format" ]
8e2b6724e31995e0d43af501f25974310c6b843b
https://github.com/moonso/vcf_parser/blob/8e2b6724e31995e0d43af501f25974310c6b843b/vcf_parser/header_parser.py#L185-L205
19,779
moonso/vcf_parser
vcf_parser/parser.py
VCFParser.add_variant
def add_variant(self, chrom, pos, rs_id, ref, alt, qual, filt, info, form=None, genotypes=[]): """ Add a variant to the parser. This function is for building a vcf. It takes the relevant parameters and make a vcf variant in the proper format. """ variant_info = [chrom, pos, rs_id, ref, alt, qual, filt, info] if form: variant_info.append(form) for individual in genotypes: variant_info.append(individual) variant_line = '\t'.join(variant_info) variant = format_variant( line = variant_line, header_parser = self.metadata, check_info = self.check_info ) if not (self.split_variants and len(variant['ALT'].split(',')) > 1): self.variants.append(variant) # If multiple alternative and split_variants we must split the variant else: for splitted_variant in split_variants( variant_dict=variant, header_parser=self.metadata, allele_symbol=self.allele_symbol): self.variants.append(splitted_variant)
python
def add_variant(self, chrom, pos, rs_id, ref, alt, qual, filt, info, form=None, genotypes=[]): variant_info = [chrom, pos, rs_id, ref, alt, qual, filt, info] if form: variant_info.append(form) for individual in genotypes: variant_info.append(individual) variant_line = '\t'.join(variant_info) variant = format_variant( line = variant_line, header_parser = self.metadata, check_info = self.check_info ) if not (self.split_variants and len(variant['ALT'].split(',')) > 1): self.variants.append(variant) # If multiple alternative and split_variants we must split the variant else: for splitted_variant in split_variants( variant_dict=variant, header_parser=self.metadata, allele_symbol=self.allele_symbol): self.variants.append(splitted_variant)
[ "def", "add_variant", "(", "self", ",", "chrom", ",", "pos", ",", "rs_id", ",", "ref", ",", "alt", ",", "qual", ",", "filt", ",", "info", ",", "form", "=", "None", ",", "genotypes", "=", "[", "]", ")", ":", "variant_info", "=", "[", "chrom", ",",...
Add a variant to the parser. This function is for building a vcf. It takes the relevant parameters and make a vcf variant in the proper format.
[ "Add", "a", "variant", "to", "the", "parser", ".", "This", "function", "is", "for", "building", "a", "vcf", ".", "It", "takes", "the", "relevant", "parameters", "and", "make", "a", "vcf", "variant", "in", "the", "proper", "format", "." ]
8e2b6724e31995e0d43af501f25974310c6b843b
https://github.com/moonso/vcf_parser/blob/8e2b6724e31995e0d43af501f25974310c6b843b/vcf_parser/parser.py#L173-L202
19,780
hfaran/piazza-api
piazza_api/rpc.py
PiazzaRPC.content_get
def content_get(self, cid, nid=None): """Get data from post `cid` in network `nid` :type nid: str :param nid: This is the ID of the network (or class) from which to query posts. This is optional and only to override the existing `network_id` entered when created the class :type cid: str|int :param cid: This is the post ID which we grab :returns: Python object containing returned data """ r = self.request( method="content.get", data={"cid": cid}, nid=nid ) return self._handle_error(r, "Could not get post {}.".format(cid))
python
def content_get(self, cid, nid=None): r = self.request( method="content.get", data={"cid": cid}, nid=nid ) return self._handle_error(r, "Could not get post {}.".format(cid))
[ "def", "content_get", "(", "self", ",", "cid", ",", "nid", "=", "None", ")", ":", "r", "=", "self", ".", "request", "(", "method", "=", "\"content.get\"", ",", "data", "=", "{", "\"cid\"", ":", "cid", "}", ",", "nid", "=", "nid", ")", "return", "...
Get data from post `cid` in network `nid` :type nid: str :param nid: This is the ID of the network (or class) from which to query posts. This is optional and only to override the existing `network_id` entered when created the class :type cid: str|int :param cid: This is the post ID which we grab :returns: Python object containing returned data
[ "Get", "data", "from", "post", "cid", "in", "network", "nid" ]
26201d06e26bada9a838f6765c1bccedad05bd39
https://github.com/hfaran/piazza-api/blob/26201d06e26bada9a838f6765c1bccedad05bd39/piazza_api/rpc.py#L82-L98
19,781
hfaran/piazza-api
piazza_api/rpc.py
PiazzaRPC.content_create
def content_create(self, params): """Create a post or followup. :type params: dict :param params: A dict of options to pass to the endpoint. Depends on the specific type of content being created. :returns: Python object containing returned data """ r = self.request( method="content.create", data=params ) return self._handle_error( r, "Could not create object {}.".format(repr(params)) )
python
def content_create(self, params): r = self.request( method="content.create", data=params ) return self._handle_error( r, "Could not create object {}.".format(repr(params)) )
[ "def", "content_create", "(", "self", ",", "params", ")", ":", "r", "=", "self", ".", "request", "(", "method", "=", "\"content.create\"", ",", "data", "=", "params", ")", "return", "self", ".", "_handle_error", "(", "r", ",", "\"Could not create object {}.\...
Create a post or followup. :type params: dict :param params: A dict of options to pass to the endpoint. Depends on the specific type of content being created. :returns: Python object containing returned data
[ "Create", "a", "post", "or", "followup", "." ]
26201d06e26bada9a838f6765c1bccedad05bd39
https://github.com/hfaran/piazza-api/blob/26201d06e26bada9a838f6765c1bccedad05bd39/piazza_api/rpc.py#L100-L115
19,782
hfaran/piazza-api
piazza_api/rpc.py
PiazzaRPC.add_students
def add_students(self, student_emails, nid=None): """Enroll students in a network `nid`. Piazza will email these students with instructions to activate their account. :type student_emails: list of str :param student_emails: A listing of email addresses to enroll in the network (or class). This can be a list of length one. :type nid: str :param nid: This is the ID of the network to add students to. This is optional and only to override the existing `network_id` entered when created the class :returns: Python object containing returned data, a list of dicts of user data of all of the users in the network including the ones that were just added. """ r = self.request( method="network.update", data={ "from": "ClassSettingsPage", "add_students": student_emails }, nid=nid, nid_key="id" ) return self._handle_error(r, "Could not add users.")
python
def add_students(self, student_emails, nid=None): r = self.request( method="network.update", data={ "from": "ClassSettingsPage", "add_students": student_emails }, nid=nid, nid_key="id" ) return self._handle_error(r, "Could not add users.")
[ "def", "add_students", "(", "self", ",", "student_emails", ",", "nid", "=", "None", ")", ":", "r", "=", "self", ".", "request", "(", "method", "=", "\"network.update\"", ",", "data", "=", "{", "\"from\"", ":", "\"ClassSettingsPage\"", ",", "\"add_students\""...
Enroll students in a network `nid`. Piazza will email these students with instructions to activate their account. :type student_emails: list of str :param student_emails: A listing of email addresses to enroll in the network (or class). This can be a list of length one. :type nid: str :param nid: This is the ID of the network to add students to. This is optional and only to override the existing `network_id` entered when created the class :returns: Python object containing returned data, a list of dicts of user data of all of the users in the network including the ones that were just added.
[ "Enroll", "students", "in", "a", "network", "nid", "." ]
26201d06e26bada9a838f6765c1bccedad05bd39
https://github.com/hfaran/piazza-api/blob/26201d06e26bada9a838f6765c1bccedad05bd39/piazza_api/rpc.py#L185-L211
19,783
hfaran/piazza-api
piazza_api/rpc.py
PiazzaRPC.get_all_users
def get_all_users(self, nid=None): """Get a listing of data for each user in a network `nid` :type nid: str :param nid: This is the ID of the network to get users from. This is optional and only to override the existing `network_id` entered when created the class :returns: Python object containing returned data, a list of dicts containing user data. """ r = self.request( method="network.get_all_users", nid=nid ) return self._handle_error(r, "Could not get users.")
python
def get_all_users(self, nid=None): r = self.request( method="network.get_all_users", nid=nid ) return self._handle_error(r, "Could not get users.")
[ "def", "get_all_users", "(", "self", ",", "nid", "=", "None", ")", ":", "r", "=", "self", ".", "request", "(", "method", "=", "\"network.get_all_users\"", ",", "nid", "=", "nid", ")", "return", "self", ".", "_handle_error", "(", "r", ",", "\"Could not ge...
Get a listing of data for each user in a network `nid` :type nid: str :param nid: This is the ID of the network to get users from. This is optional and only to override the existing `network_id` entered when created the class :returns: Python object containing returned data, a list of dicts containing user data.
[ "Get", "a", "listing", "of", "data", "for", "each", "user", "in", "a", "network", "nid" ]
26201d06e26bada9a838f6765c1bccedad05bd39
https://github.com/hfaran/piazza-api/blob/26201d06e26bada9a838f6765c1bccedad05bd39/piazza_api/rpc.py#L213-L227
19,784
hfaran/piazza-api
piazza_api/rpc.py
PiazzaRPC.get_users
def get_users(self, user_ids, nid=None): """Get a listing of data for specific users `user_ids` in a network `nid` :type user_ids: list of str :param user_ids: a list of user ids. These are the same ids that are returned by get_all_users. :type nid: str :param nid: This is the ID of the network to get students from. This is optional and only to override the existing `network_id` entered when created the class :returns: Python object containing returned data, a list of dicts containing user data. """ r = self.request( method="network.get_users", data={"ids": user_ids}, nid=nid ) return self._handle_error(r, "Could not get users.")
python
def get_users(self, user_ids, nid=None): r = self.request( method="network.get_users", data={"ids": user_ids}, nid=nid ) return self._handle_error(r, "Could not get users.")
[ "def", "get_users", "(", "self", ",", "user_ids", ",", "nid", "=", "None", ")", ":", "r", "=", "self", ".", "request", "(", "method", "=", "\"network.get_users\"", ",", "data", "=", "{", "\"ids\"", ":", "user_ids", "}", ",", "nid", "=", "nid", ")", ...
Get a listing of data for specific users `user_ids` in a network `nid` :type user_ids: list of str :param user_ids: a list of user ids. These are the same ids that are returned by get_all_users. :type nid: str :param nid: This is the ID of the network to get students from. This is optional and only to override the existing `network_id` entered when created the class :returns: Python object containing returned data, a list of dicts containing user data.
[ "Get", "a", "listing", "of", "data", "for", "specific", "users", "user_ids", "in", "a", "network", "nid" ]
26201d06e26bada9a838f6765c1bccedad05bd39
https://github.com/hfaran/piazza-api/blob/26201d06e26bada9a838f6765c1bccedad05bd39/piazza_api/rpc.py#L229-L248
19,785
hfaran/piazza-api
piazza_api/rpc.py
PiazzaRPC.remove_users
def remove_users(self, user_ids, nid=None): """Remove users from a network `nid` :type user_ids: list of str :param user_ids: a list of user ids. These are the same ids that are returned by get_all_users. :type nid: str :param nid: This is the ID of the network to remove students from. This is optional and only to override the existing `network_id` entered when created the class :returns: Python object containing returned data, a list of dicts of user data of all of the users remaining in the network after users are removed. """ r = self.request( method="network.update", data={"remove_users": user_ids}, nid=nid, nid_key="id" ) return self._handle_error(r, "Could not remove users.")
python
def remove_users(self, user_ids, nid=None): r = self.request( method="network.update", data={"remove_users": user_ids}, nid=nid, nid_key="id" ) return self._handle_error(r, "Could not remove users.")
[ "def", "remove_users", "(", "self", ",", "user_ids", ",", "nid", "=", "None", ")", ":", "r", "=", "self", ".", "request", "(", "method", "=", "\"network.update\"", ",", "data", "=", "{", "\"remove_users\"", ":", "user_ids", "}", ",", "nid", "=", "nid",...
Remove users from a network `nid` :type user_ids: list of str :param user_ids: a list of user ids. These are the same ids that are returned by get_all_users. :type nid: str :param nid: This is the ID of the network to remove students from. This is optional and only to override the existing `network_id` entered when created the class :returns: Python object containing returned data, a list of dicts of user data of all of the users remaining in the network after users are removed.
[ "Remove", "users", "from", "a", "network", "nid" ]
26201d06e26bada9a838f6765c1bccedad05bd39
https://github.com/hfaran/piazza-api/blob/26201d06e26bada9a838f6765c1bccedad05bd39/piazza_api/rpc.py#L250-L270
19,786
hfaran/piazza-api
piazza_api/rpc.py
PiazzaRPC.get_my_feed
def get_my_feed(self, limit=150, offset=20, sort="updated", nid=None): """Get my feed :type limit: int :param limit: Number of posts from feed to get, starting from ``offset`` :type offset: int :param offset: Offset starting from bottom of feed :type sort: str :param sort: How to sort feed that will be retrieved; only current known value is "updated" :type nid: str :param nid: This is the ID of the network to get the feed from. This is optional and only to override the existing `network_id` entered when created the class """ r = self.request( method="network.get_my_feed", nid=nid, data=dict( limit=limit, offset=offset, sort=sort ) ) return self._handle_error(r, "Could not retrieve your feed.")
python
def get_my_feed(self, limit=150, offset=20, sort="updated", nid=None): r = self.request( method="network.get_my_feed", nid=nid, data=dict( limit=limit, offset=offset, sort=sort ) ) return self._handle_error(r, "Could not retrieve your feed.")
[ "def", "get_my_feed", "(", "self", ",", "limit", "=", "150", ",", "offset", "=", "20", ",", "sort", "=", "\"updated\"", ",", "nid", "=", "None", ")", ":", "r", "=", "self", ".", "request", "(", "method", "=", "\"network.get_my_feed\"", ",", "nid", "=...
Get my feed :type limit: int :param limit: Number of posts from feed to get, starting from ``offset`` :type offset: int :param offset: Offset starting from bottom of feed :type sort: str :param sort: How to sort feed that will be retrieved; only current known value is "updated" :type nid: str :param nid: This is the ID of the network to get the feed from. This is optional and only to override the existing `network_id` entered when created the class
[ "Get", "my", "feed" ]
26201d06e26bada9a838f6765c1bccedad05bd39
https://github.com/hfaran/piazza-api/blob/26201d06e26bada9a838f6765c1bccedad05bd39/piazza_api/rpc.py#L272-L296
19,787
hfaran/piazza-api
piazza_api/rpc.py
PiazzaRPC.filter_feed
def filter_feed(self, updated=False, following=False, folder=False, filter_folder="", sort="updated", nid=None): """Get filtered feed Only one filter type (updated, following, folder) is possible. :type nid: str :param nid: This is the ID of the network to get the feed from. This is optional and only to override the existing `network_id` entered when created the class :type sort: str :param sort: How to sort feed that will be retrieved; only current known value is "updated" :type updated: bool :param updated: Set to filter through only posts which have been updated since you last read them :type following: bool :param following: Set to filter through only posts which you are following :type folder: bool :param folder: Set to filter through only posts which are in the provided ``filter_folder`` :type filter_folder: str :param filter_folder: Name of folder to show posts from; required only if ``folder`` is set """ assert sum([updated, following, folder]) == 1 if folder: assert filter_folder if updated: filter_type = dict(updated=1) elif following: filter_type = dict(following=1) else: filter_type = dict(folder=1, filter_folder=filter_folder) r = self.request( nid=nid, method="network.filter_feed", data=dict( sort=sort, **filter_type ) ) return self._handle_error(r, "Could not retrieve filtered feed.")
python
def filter_feed(self, updated=False, following=False, folder=False, filter_folder="", sort="updated", nid=None): assert sum([updated, following, folder]) == 1 if folder: assert filter_folder if updated: filter_type = dict(updated=1) elif following: filter_type = dict(following=1) else: filter_type = dict(folder=1, filter_folder=filter_folder) r = self.request( nid=nid, method="network.filter_feed", data=dict( sort=sort, **filter_type ) ) return self._handle_error(r, "Could not retrieve filtered feed.")
[ "def", "filter_feed", "(", "self", ",", "updated", "=", "False", ",", "following", "=", "False", ",", "folder", "=", "False", ",", "filter_folder", "=", "\"\"", ",", "sort", "=", "\"updated\"", ",", "nid", "=", "None", ")", ":", "assert", "sum", "(", ...
Get filtered feed Only one filter type (updated, following, folder) is possible. :type nid: str :param nid: This is the ID of the network to get the feed from. This is optional and only to override the existing `network_id` entered when created the class :type sort: str :param sort: How to sort feed that will be retrieved; only current known value is "updated" :type updated: bool :param updated: Set to filter through only posts which have been updated since you last read them :type following: bool :param following: Set to filter through only posts which you are following :type folder: bool :param folder: Set to filter through only posts which are in the provided ``filter_folder`` :type filter_folder: str :param filter_folder: Name of folder to show posts from; required only if ``folder`` is set
[ "Get", "filtered", "feed" ]
26201d06e26bada9a838f6765c1bccedad05bd39
https://github.com/hfaran/piazza-api/blob/26201d06e26bada9a838f6765c1bccedad05bd39/piazza_api/rpc.py#L298-L343
19,788
hfaran/piazza-api
piazza_api/rpc.py
PiazzaRPC.search
def search(self, query, nid=None): """Search for posts with ``query`` :type nid: str :param nid: This is the ID of the network to get the feed from. This is optional and only to override the existing `network_id` entered when created the class :type query: str :param query: The search query; should just be keywords for posts that you are looking for """ r = self.request( method="network.search", nid=nid, data=dict(query=query) ) return self._handle_error(r, "Search with query '{}' failed." .format(query))
python
def search(self, query, nid=None): r = self.request( method="network.search", nid=nid, data=dict(query=query) ) return self._handle_error(r, "Search with query '{}' failed." .format(query))
[ "def", "search", "(", "self", ",", "query", ",", "nid", "=", "None", ")", ":", "r", "=", "self", ".", "request", "(", "method", "=", "\"network.search\"", ",", "nid", "=", "nid", ",", "data", "=", "dict", "(", "query", "=", "query", ")", ")", "re...
Search for posts with ``query`` :type nid: str :param nid: This is the ID of the network to get the feed from. This is optional and only to override the existing `network_id` entered when created the class :type query: str :param query: The search query; should just be keywords for posts that you are looking for
[ "Search", "for", "posts", "with", "query" ]
26201d06e26bada9a838f6765c1bccedad05bd39
https://github.com/hfaran/piazza-api/blob/26201d06e26bada9a838f6765c1bccedad05bd39/piazza_api/rpc.py#L345-L362
19,789
hfaran/piazza-api
piazza_api/rpc.py
PiazzaRPC.get_stats
def get_stats(self, nid=None): """Get statistics for class :type nid: str :param nid: This is the ID of the network to get stats from. This is optional and only to override the existing `network_id` entered when created the class """ r = self.request( api_type="main", method="network.get_stats", nid=nid, ) return self._handle_error(r, "Could not retrieve stats for class.")
python
def get_stats(self, nid=None): r = self.request( api_type="main", method="network.get_stats", nid=nid, ) return self._handle_error(r, "Could not retrieve stats for class.")
[ "def", "get_stats", "(", "self", ",", "nid", "=", "None", ")", ":", "r", "=", "self", ".", "request", "(", "api_type", "=", "\"main\"", ",", "method", "=", "\"network.get_stats\"", ",", "nid", "=", "nid", ",", ")", "return", "self", ".", "_handle_error...
Get statistics for class :type nid: str :param nid: This is the ID of the network to get stats from. This is optional and only to override the existing `network_id` entered when created the class
[ "Get", "statistics", "for", "class" ]
26201d06e26bada9a838f6765c1bccedad05bd39
https://github.com/hfaran/piazza-api/blob/26201d06e26bada9a838f6765c1bccedad05bd39/piazza_api/rpc.py#L364-L377
19,790
hfaran/piazza-api
piazza_api/rpc.py
PiazzaRPC.request
def request(self, method, data=None, nid=None, nid_key='nid', api_type="logic", return_response=False): """Get data from arbitrary Piazza API endpoint `method` in network `nid` :type method: str :param method: An internal Piazza API method name like `content.get` or `network.get_users` :type data: dict :param data: Key-value data to pass to Piazza in the request :type nid: str :param nid: This is the ID of the network to which the request should be made. This is optional and only to override the existing `network_id` entered when creating the class :type nid_key: str :param nid_key: Name expected by Piazza for `nid` when making request. (Usually and by default "nid", but sometimes "id" is expected) :returns: Python object containing returned data :type return_response: bool :param return_response: If set, returns whole :class:`requests.Response` object rather than just the response body """ self._check_authenticated() nid = nid if nid else self._nid if data is None: data = {} headers = {} if "session_id" in self.session.cookies: headers["CSRF-Token"] = self.session.cookies["session_id"] # Adding a nonce to the request endpoint = self.base_api_urls[api_type] if api_type == "logic": endpoint += "?method={}&aid={}".format( method, _piazza_nonce() ) response = self.session.post( endpoint, data=json.dumps({ "method": method, "params": dict({nid_key: nid}, **data) }), headers=headers ) return response if return_response else response.json()
python
def request(self, method, data=None, nid=None, nid_key='nid', api_type="logic", return_response=False): self._check_authenticated() nid = nid if nid else self._nid if data is None: data = {} headers = {} if "session_id" in self.session.cookies: headers["CSRF-Token"] = self.session.cookies["session_id"] # Adding a nonce to the request endpoint = self.base_api_urls[api_type] if api_type == "logic": endpoint += "?method={}&aid={}".format( method, _piazza_nonce() ) response = self.session.post( endpoint, data=json.dumps({ "method": method, "params": dict({nid_key: nid}, **data) }), headers=headers ) return response if return_response else response.json()
[ "def", "request", "(", "self", ",", "method", ",", "data", "=", "None", ",", "nid", "=", "None", ",", "nid_key", "=", "'nid'", ",", "api_type", "=", "\"logic\"", ",", "return_response", "=", "False", ")", ":", "self", ".", "_check_authenticated", "(", ...
Get data from arbitrary Piazza API endpoint `method` in network `nid` :type method: str :param method: An internal Piazza API method name like `content.get` or `network.get_users` :type data: dict :param data: Key-value data to pass to Piazza in the request :type nid: str :param nid: This is the ID of the network to which the request should be made. This is optional and only to override the existing `network_id` entered when creating the class :type nid_key: str :param nid_key: Name expected by Piazza for `nid` when making request. (Usually and by default "nid", but sometimes "id" is expected) :returns: Python object containing returned data :type return_response: bool :param return_response: If set, returns whole :class:`requests.Response` object rather than just the response body
[ "Get", "data", "from", "arbitrary", "Piazza", "API", "endpoint", "method", "in", "network", "nid" ]
26201d06e26bada9a838f6765c1bccedad05bd39
https://github.com/hfaran/piazza-api/blob/26201d06e26bada9a838f6765c1bccedad05bd39/piazza_api/rpc.py#L392-L439
19,791
hfaran/piazza-api
piazza_api/rpc.py
PiazzaRPC._handle_error
def _handle_error(self, result, err_msg): """Check result for error :type result: dict :param result: response body :type err_msg: str :param err_msg: The message given to the :class:`RequestError` instance raised :returns: Actual result from result :raises RequestError: If result has error """ if result.get(u'error'): raise RequestError("{}\nResponse: {}".format( err_msg, json.dumps(result, indent=2) )) else: return result.get(u'result')
python
def _handle_error(self, result, err_msg): if result.get(u'error'): raise RequestError("{}\nResponse: {}".format( err_msg, json.dumps(result, indent=2) )) else: return result.get(u'result')
[ "def", "_handle_error", "(", "self", ",", "result", ",", "err_msg", ")", ":", "if", "result", ".", "get", "(", "u'error'", ")", ":", "raise", "RequestError", "(", "\"{}\\nResponse: {}\"", ".", "format", "(", "err_msg", ",", "json", ".", "dumps", "(", "re...
Check result for error :type result: dict :param result: response body :type err_msg: str :param err_msg: The message given to the :class:`RequestError` instance raised :returns: Actual result from result :raises RequestError: If result has error
[ "Check", "result", "for", "error" ]
26201d06e26bada9a838f6765c1bccedad05bd39
https://github.com/hfaran/piazza-api/blob/26201d06e26bada9a838f6765c1bccedad05bd39/piazza_api/rpc.py#L454-L471
19,792
hfaran/piazza-api
piazza_api/piazza.py
Piazza.get_user_classes
def get_user_classes(self): """Get list of the current user's classes. This is a subset of the information returned by the call to ``get_user_status``. :returns: Classes of currently authenticated user :rtype: list """ # Previously getting classes from profile (such a list is incomplete) # raw_classes = self.get_user_profile().get('all_classes').values() # Get classes from the user status (includes all classes) status = self.get_user_status() uid = status['id'] raw_classes = status.get('networks', []) classes = [] for rawc in raw_classes: c = {k: rawc[k] for k in ['name', 'term']} c['num'] = rawc.get('course_number', '') c['nid'] = rawc['id'] c['is_ta'] = uid in rawc['prof_hash'] classes.append(c) return classes
python
def get_user_classes(self): # Previously getting classes from profile (such a list is incomplete) # raw_classes = self.get_user_profile().get('all_classes').values() # Get classes from the user status (includes all classes) status = self.get_user_status() uid = status['id'] raw_classes = status.get('networks', []) classes = [] for rawc in raw_classes: c = {k: rawc[k] for k in ['name', 'term']} c['num'] = rawc.get('course_number', '') c['nid'] = rawc['id'] c['is_ta'] = uid in rawc['prof_hash'] classes.append(c) return classes
[ "def", "get_user_classes", "(", "self", ")", ":", "# Previously getting classes from profile (such a list is incomplete)", "# raw_classes = self.get_user_profile().get('all_classes').values()", "# Get classes from the user status (includes all classes)", "status", "=", "self", ".", "get_us...
Get list of the current user's classes. This is a subset of the information returned by the call to ``get_user_status``. :returns: Classes of currently authenticated user :rtype: list
[ "Get", "list", "of", "the", "current", "user", "s", "classes", ".", "This", "is", "a", "subset", "of", "the", "information", "returned", "by", "the", "call", "to", "get_user_status", "." ]
26201d06e26bada9a838f6765c1bccedad05bd39
https://github.com/hfaran/piazza-api/blob/26201d06e26bada9a838f6765c1bccedad05bd39/piazza_api/piazza.py#L66-L89
19,793
hfaran/piazza-api
piazza_api/nonce.py
nonce
def nonce(): """ Returns a new nonce to be used with the Piazza API. """ nonce_part1 = _int2base(int(_time()*1000), 36) nonce_part2 = _int2base(round(_random()*1679616), 36) return "{}{}".format(nonce_part1, nonce_part2)
python
def nonce(): nonce_part1 = _int2base(int(_time()*1000), 36) nonce_part2 = _int2base(round(_random()*1679616), 36) return "{}{}".format(nonce_part1, nonce_part2)
[ "def", "nonce", "(", ")", ":", "nonce_part1", "=", "_int2base", "(", "int", "(", "_time", "(", ")", "*", "1000", ")", ",", "36", ")", "nonce_part2", "=", "_int2base", "(", "round", "(", "_random", "(", ")", "*", "1679616", ")", ",", "36", ")", "r...
Returns a new nonce to be used with the Piazza API.
[ "Returns", "a", "new", "nonce", "to", "be", "used", "with", "the", "Piazza", "API", "." ]
26201d06e26bada9a838f6765c1bccedad05bd39
https://github.com/hfaran/piazza-api/blob/26201d06e26bada9a838f6765c1bccedad05bd39/piazza_api/nonce.py#L7-L13
19,794
hfaran/piazza-api
piazza_api/network.py
Network.iter_all_posts
def iter_all_posts(self, limit=None): """Get all posts visible to the current user This grabs you current feed and ids of all posts from it; each post is then individually fetched. This method does not go against a bulk endpoint; it retrieves each post individually, so a caution to the user when using this. :type limit: int|None :param limit: If given, will limit the number of posts to fetch before the generator is exhausted and raises StopIteration. No special consideration is given to `0`; provide `None` to retrieve all posts. :returns: An iterator which yields all posts which the current user can view :rtype: generator """ feed = self.get_feed(limit=999999, offset=0) cids = [post['id'] for post in feed["feed"]] if limit is not None: cids = cids[:limit] for cid in cids: yield self.get_post(cid)
python
def iter_all_posts(self, limit=None): feed = self.get_feed(limit=999999, offset=0) cids = [post['id'] for post in feed["feed"]] if limit is not None: cids = cids[:limit] for cid in cids: yield self.get_post(cid)
[ "def", "iter_all_posts", "(", "self", ",", "limit", "=", "None", ")", ":", "feed", "=", "self", ".", "get_feed", "(", "limit", "=", "999999", ",", "offset", "=", "0", ")", "cids", "=", "[", "post", "[", "'id'", "]", "for", "post", "in", "feed", "...
Get all posts visible to the current user This grabs you current feed and ids of all posts from it; each post is then individually fetched. This method does not go against a bulk endpoint; it retrieves each post individually, so a caution to the user when using this. :type limit: int|None :param limit: If given, will limit the number of posts to fetch before the generator is exhausted and raises StopIteration. No special consideration is given to `0`; provide `None` to retrieve all posts. :returns: An iterator which yields all posts which the current user can view :rtype: generator
[ "Get", "all", "posts", "visible", "to", "the", "current", "user" ]
26201d06e26bada9a838f6765c1bccedad05bd39
https://github.com/hfaran/piazza-api/blob/26201d06e26bada9a838f6765c1bccedad05bd39/piazza_api/network.py#L85-L107
19,795
hfaran/piazza-api
piazza_api/network.py
Network.create_post
def create_post(self, post_type, post_folders, post_subject, post_content, is_announcement=0, bypass_email=0, anonymous=False): """Create a post It seems like if the post has `<p>` tags, then it's treated as HTML, but is treated as text otherwise. You'll want to provide `content` accordingly. :type post_type: str :param post_type: 'note', 'question' :type post_folders: str :param post_folders: Folder to put post into :type post_subject: str :param post_subject: Subject string :type post_content: str :param post_content: Content string :type is_announcement: bool :param is_announcement: :type bypass_email: bool :param bypass_email: :type anonymous: bool :param anonymous: :rtype: dict :returns: Dictionary with information about the created post. """ params = { "anonymous": "yes" if anonymous else "no", "subject": post_subject, "content": post_content, "folders": post_folders, "type": post_type, "config": { "bypass_email": bypass_email, "is_announcement": is_announcement } } return self._rpc.content_create(params)
python
def create_post(self, post_type, post_folders, post_subject, post_content, is_announcement=0, bypass_email=0, anonymous=False): params = { "anonymous": "yes" if anonymous else "no", "subject": post_subject, "content": post_content, "folders": post_folders, "type": post_type, "config": { "bypass_email": bypass_email, "is_announcement": is_announcement } } return self._rpc.content_create(params)
[ "def", "create_post", "(", "self", ",", "post_type", ",", "post_folders", ",", "post_subject", ",", "post_content", ",", "is_announcement", "=", "0", ",", "bypass_email", "=", "0", ",", "anonymous", "=", "False", ")", ":", "params", "=", "{", "\"anonymous\""...
Create a post It seems like if the post has `<p>` tags, then it's treated as HTML, but is treated as text otherwise. You'll want to provide `content` accordingly. :type post_type: str :param post_type: 'note', 'question' :type post_folders: str :param post_folders: Folder to put post into :type post_subject: str :param post_subject: Subject string :type post_content: str :param post_content: Content string :type is_announcement: bool :param is_announcement: :type bypass_email: bool :param bypass_email: :type anonymous: bool :param anonymous: :rtype: dict :returns: Dictionary with information about the created post.
[ "Create", "a", "post" ]
26201d06e26bada9a838f6765c1bccedad05bd39
https://github.com/hfaran/piazza-api/blob/26201d06e26bada9a838f6765c1bccedad05bd39/piazza_api/network.py#L109-L145
19,796
hfaran/piazza-api
piazza_api/network.py
Network.create_followup
def create_followup(self, post, content, anonymous=False): """Create a follow-up on a post `post`. It seems like if the post has `<p>` tags, then it's treated as HTML, but is treated as text otherwise. You'll want to provide `content` accordingly. :type post: dict|str|int :param post: Either the post dict returned by another API method, or the `cid` field of that post. :type content: str :param content: The content of the followup. :type anonymous: bool :param anonymous: Whether or not to post anonymously. :rtype: dict :returns: Dictionary with information about the created follow-up. """ try: cid = post["id"] except KeyError: cid = post params = { "cid": cid, "type": "followup", # For followups, the content is actually put into the subject. "subject": content, "content": "", "anonymous": "yes" if anonymous else "no", } return self._rpc.content_create(params)
python
def create_followup(self, post, content, anonymous=False): try: cid = post["id"] except KeyError: cid = post params = { "cid": cid, "type": "followup", # For followups, the content is actually put into the subject. "subject": content, "content": "", "anonymous": "yes" if anonymous else "no", } return self._rpc.content_create(params)
[ "def", "create_followup", "(", "self", ",", "post", ",", "content", ",", "anonymous", "=", "False", ")", ":", "try", ":", "cid", "=", "post", "[", "\"id\"", "]", "except", "KeyError", ":", "cid", "=", "post", "params", "=", "{", "\"cid\"", ":", "cid"...
Create a follow-up on a post `post`. It seems like if the post has `<p>` tags, then it's treated as HTML, but is treated as text otherwise. You'll want to provide `content` accordingly. :type post: dict|str|int :param post: Either the post dict returned by another API method, or the `cid` field of that post. :type content: str :param content: The content of the followup. :type anonymous: bool :param anonymous: Whether or not to post anonymously. :rtype: dict :returns: Dictionary with information about the created follow-up.
[ "Create", "a", "follow", "-", "up", "on", "a", "post", "post", "." ]
26201d06e26bada9a838f6765c1bccedad05bd39
https://github.com/hfaran/piazza-api/blob/26201d06e26bada9a838f6765c1bccedad05bd39/piazza_api/network.py#L147-L179
19,797
hfaran/piazza-api
piazza_api/network.py
Network.create_instructor_answer
def create_instructor_answer(self, post, content, revision, anonymous=False): """Create an instructor's answer to a post `post`. It seems like if the post has `<p>` tags, then it's treated as HTML, but is treated as text otherwise. You'll want to provide `content` accordingly. :type post: dict|str|int :param post: Either the post dict returned by another API method, or the `cid` field of that post. :type content: str :param content: The content of the answer. :type revision: int :param revision: The number of revisions the answer has gone through. The first responder should out 0, the first editor 1, etc. :type anonymous: bool :param anonymous: Whether or not to post anonymously. :rtype: dict :returns: Dictionary with information about the created answer. """ try: cid = post["id"] except KeyError: cid = post params = { "cid": cid, "type": "i_answer", "content": content, "revision": revision, "anonymous": "yes" if anonymous else "no", } return self._rpc.content_instructor_answer(params)
python
def create_instructor_answer(self, post, content, revision, anonymous=False): try: cid = post["id"] except KeyError: cid = post params = { "cid": cid, "type": "i_answer", "content": content, "revision": revision, "anonymous": "yes" if anonymous else "no", } return self._rpc.content_instructor_answer(params)
[ "def", "create_instructor_answer", "(", "self", ",", "post", ",", "content", ",", "revision", ",", "anonymous", "=", "False", ")", ":", "try", ":", "cid", "=", "post", "[", "\"id\"", "]", "except", "KeyError", ":", "cid", "=", "post", "params", "=", "{...
Create an instructor's answer to a post `post`. It seems like if the post has `<p>` tags, then it's treated as HTML, but is treated as text otherwise. You'll want to provide `content` accordingly. :type post: dict|str|int :param post: Either the post dict returned by another API method, or the `cid` field of that post. :type content: str :param content: The content of the answer. :type revision: int :param revision: The number of revisions the answer has gone through. The first responder should out 0, the first editor 1, etc. :type anonymous: bool :param anonymous: Whether or not to post anonymously. :rtype: dict :returns: Dictionary with information about the created answer.
[ "Create", "an", "instructor", "s", "answer", "to", "a", "post", "post", "." ]
26201d06e26bada9a838f6765c1bccedad05bd39
https://github.com/hfaran/piazza-api/blob/26201d06e26bada9a838f6765c1bccedad05bd39/piazza_api/network.py#L181-L213
19,798
hfaran/piazza-api
piazza_api/network.py
Network.mark_as_duplicate
def mark_as_duplicate(self, duplicated_cid, master_cid, msg=''): """Mark the post at ``duplicated_cid`` as a duplicate of ``master_cid`` :type duplicated_cid: int :param duplicated_cid: The numeric id of the duplicated post :type master_cid: int :param master_cid: The numeric id of an older post. This will be the post that gets kept and ``duplicated_cid`` post will be concatinated as a follow up to ``master_cid`` post. :type msg: string :param msg: the optional message (or reason for marking as duplicate) :returns: True if it is successful. False otherwise """ content_id_from = self.get_post(duplicated_cid)["id"] content_id_to = self.get_post(master_cid)["id"] params = { "cid_dupe": content_id_from, "cid_to": content_id_to, "msg": msg } return self._rpc.content_mark_duplicate(params)
python
def mark_as_duplicate(self, duplicated_cid, master_cid, msg=''): content_id_from = self.get_post(duplicated_cid)["id"] content_id_to = self.get_post(master_cid)["id"] params = { "cid_dupe": content_id_from, "cid_to": content_id_to, "msg": msg } return self._rpc.content_mark_duplicate(params)
[ "def", "mark_as_duplicate", "(", "self", ",", "duplicated_cid", ",", "master_cid", ",", "msg", "=", "''", ")", ":", "content_id_from", "=", "self", ".", "get_post", "(", "duplicated_cid", ")", "[", "\"id\"", "]", "content_id_to", "=", "self", ".", "get_post"...
Mark the post at ``duplicated_cid`` as a duplicate of ``master_cid`` :type duplicated_cid: int :param duplicated_cid: The numeric id of the duplicated post :type master_cid: int :param master_cid: The numeric id of an older post. This will be the post that gets kept and ``duplicated_cid`` post will be concatinated as a follow up to ``master_cid`` post. :type msg: string :param msg: the optional message (or reason for marking as duplicate) :returns: True if it is successful. False otherwise
[ "Mark", "the", "post", "at", "duplicated_cid", "as", "a", "duplicate", "of", "master_cid" ]
26201d06e26bada9a838f6765c1bccedad05bd39
https://github.com/hfaran/piazza-api/blob/26201d06e26bada9a838f6765c1bccedad05bd39/piazza_api/network.py#L248-L268
19,799
hfaran/piazza-api
piazza_api/network.py
Network.resolve_post
def resolve_post(self, post): """Mark post as resolved :type post: dict|str|int :param post: Either the post dict returned by another API method, or the `cid` field of that post. :returns: True if it is successful. False otherwise """ try: cid = post["id"] except KeyError: cid = post params = { "cid": cid, "resolved": "true" } return self._rpc.content_mark_resolved(params)
python
def resolve_post(self, post): try: cid = post["id"] except KeyError: cid = post params = { "cid": cid, "resolved": "true" } return self._rpc.content_mark_resolved(params)
[ "def", "resolve_post", "(", "self", ",", "post", ")", ":", "try", ":", "cid", "=", "post", "[", "\"id\"", "]", "except", "KeyError", ":", "cid", "=", "post", "params", "=", "{", "\"cid\"", ":", "cid", ",", "\"resolved\"", ":", "\"true\"", "}", "retur...
Mark post as resolved :type post: dict|str|int :param post: Either the post dict returned by another API method, or the `cid` field of that post. :returns: True if it is successful. False otherwise
[ "Mark", "post", "as", "resolved" ]
26201d06e26bada9a838f6765c1bccedad05bd39
https://github.com/hfaran/piazza-api/blob/26201d06e26bada9a838f6765c1bccedad05bd39/piazza_api/network.py#L270-L288