Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def feed_backend_arthur(backend_name, backend_params): # Always get pending items from arthur for all data sources feed_arthur() logger.debug("Items available for %s", arthur_items.keys()) # Get only the items for the backend if not get_connector_...
[ " Feed Ocean with backend data collected from arthur redis queue" ]
Please provide a description of the function:def feed_backend(url, clean, fetch_archive, backend_name, backend_params, es_index=None, es_index_enrich=None, project=None, arthur=False, es_aliases=None, projects_json_repo=None): backend = None repo = {'backend_name': backen...
[ " Feed Ocean with backend data " ]
Please provide a description of the function:def get_items_from_uuid(uuid, enrich_backend, ocean_backend): # logger.debug("Getting items for merged uuid %s " % (uuid)) uuid_fields = enrich_backend.get_fields_uuid() terms = "" # all terms with uuids in the enriched item for field in uuid_field...
[ " Get all items that include uuid ", "\n {\"term\": {\n \"%s\": {\n \"value\": \"%s\"\n }\n }}\n ", "\n {\"query\": { \"bool\": { \"should\": [%s] }}}\n " ]
Please provide a description of the function:def refresh_identities(enrich_backend, author_field=None, author_values=None): def update_items(new_filter_author): for eitem in enrich_backend.fetch(new_filter_author): roles = None try: roles = enrich_backend.roles...
[ "Refresh identities in enriched index.\n\n Retrieve items from the enriched index corresponding to enrich_backend,\n and update their identities information, with fresh data from the\n SortingHat database.\n\n Instead of the whole index, only items matching the filter_author\n filter are fitered, if ...
Please provide a description of the function:def get_ocean_backend(backend_cmd, enrich_backend, no_incremental, filter_raw=None, filter_raw_should=None): if no_incremental: last_enrich = None else: last_enrich = get_last_enrich(backend_cmd, enrich_backend, filter_raw=...
[ " Get the ocean backend configured to start from the last enriched date " ]
Please provide a description of the function:def do_studies(ocean_backend, enrich_backend, studies_args, retention_time=None): for study in enrich_backend.studies: selected_studies = [(s['name'], s['params']) for s in studies_args if s['type'] == study.__name__] for (name, params) in selected_...
[ "Execute studies related to a given enrich backend. If `retention_time` is not None, the\n study data is deleted based on the number of minutes declared in `retention_time`.\n\n :param ocean_backend: backend to access raw items\n :param enrich_backend: backend to access enriched items\n :param retention...
Please provide a description of the function:def enrich_backend(url, clean, backend_name, backend_params, cfg_section_name, ocean_index=None, ocean_index_enrich=None, db_projects_map=None, json_projects_map=None, db_sortinghat=None, ...
[ " Enrich Ocean index " ]
Please provide a description of the function:def delete_orphan_unique_identities(es, sortinghat_db, current_data_source, active_data_sources): def get_uuids_in_index(target_uuids): page = es.search( index=IDENTITIES_INDEX, scroll="360m", size=SIZE_SCROLL_IDE...
[ "Delete all unique identities which appear in SortingHat, but not in the IDENTITIES_INDEX.\n\n :param es: ElasticSearchDSL object\n :param sortinghat_db: instance of the SortingHat database\n :param current_data_source: current data source\n :param active_data_sources: list of active data sources\n "...
Please provide a description of the function:def delete_inactive_unique_identities(es, sortinghat_db, before_date): page = es.search( index=IDENTITIES_INDEX, scroll="360m", size=SIZE_SCROLL_IDENTITIES_INDEX, body={ "query": { "range": { ...
[ "Select the unique identities not seen before `before_date` and\n delete them from SortingHat.\n\n :param es: ElasticSearchDSL object\n :param sortinghat_db: instance of the SortingHat database\n :param before_date: datetime str to filter the identities\n " ]
Please provide a description of the function:def retain_identities(retention_time, es_enrichment_url, sortinghat_db, data_source, active_data_sources): before_date = get_diff_current_date(minutes=retention_time) before_date_str = before_date.isoformat() es = Elasticsearch([es_enrichment_url], timeout=...
[ "Select the unique identities not seen before `retention_time` and\n delete them from SortingHat. Furthermore, it deletes also the orphan unique identities,\n those ones stored in SortingHat but not in IDENTITIES_INDEX.\n\n :param retention_time: maximum number of minutes wrt the current date to retain the...
Please provide a description of the function:def init_backend(backend_cmd): try: backend_cmd.backend except AttributeError: parsed_args = vars(backend_cmd.parsed_args) init_args = find_signature_parameters(backend_cmd.BACKEND, parsed_ar...
[ "Init backend within the backend_cmd" ]
Please provide a description of the function:def populate_identities_index(es_enrichment_url, enrich_index): class Mapping(BaseMapping): @staticmethod def get_elastic_mappings(es_major): mapping = return {"items": mapping} # identities index map...
[ "Save the identities currently in use in the index IDENTITIES_INDEX.\n\n :param es_enrichment_url: url of the ElasticSearch with enriched data\n :param enrich_index: name of the enriched index\n ", "Get Elasticsearch mapping.\n\n :param es_major: major version of Elasticsearch, as string\n ...
Please provide a description of the function:def safe_index(cls, unique_id): index = unique_id if unique_id: index = unique_id.replace("/", "_").lower() return index
[ " Return a valid elastic index generated from unique_id " ]
Please provide a description of the function:def _check_instance(url, insecure): res = grimoire_con(insecure).get(url) if res.status_code != 200: logger.error("Didn't get 200 OK from url %s", url) raise ElasticConnectException else: try: ...
[ "Checks if there is an instance of Elasticsearch in url.\n\n Actually, it checks if GET on the url returns a JSON document\n with a field tagline \"You know, for search\",\n and a field version.number.\n\n :value url: url of the instance to check\n :value insecure: don't veri...
Please provide a description of the function:def safe_put_bulk(self, url, bulk_json): headers = {"Content-Type": "application/x-ndjson"} try: res = self.requests.put(url + '?refresh=true', data=bulk_json, headers=headers) res.raise_for_status() except UnicodeEn...
[ " Bulk PUT controlling unicode issues " ]
Please provide a description of the function:def all_es_aliases(self): r = self.requests.get(self.url + "/_aliases", headers=HEADER_JSON, verify=False) try: r.raise_for_status() except requests.exceptions.HTTPError as ex: logger.warning("Something went wrong whe...
[ "List all aliases used in ES" ]
Please provide a description of the function:def list_aliases(self): # check alias doesn't exist r = self.requests.get(self.index_url + "/_alias", headers=HEADER_JSON, verify=False) try: r.raise_for_status() except requests.exceptions.HTTPError as ex: lo...
[ "List aliases linked to the index" ]
Please provide a description of the function:def add_alias(self, alias): aliases = self.list_aliases() if alias in aliases: logger.debug("Alias %s already exists on %s.", alias, self.anonymize_url(self.index_url)) return # add alias alias_data = % (self...
[ "Add an alias to the index set in the elastic obj\n\n :param alias: alias to add\n\n :returns: None\n ", "\n {\n \"actions\": [\n {\n \"add\": {\n \"index\": \"%s\",\n \"alias\": \"%s\"\n ...
Please provide a description of the function:def bulk_upload(self, items, field_id): current = 0 new_items = 0 # total items added with bulk bulk_json = "" if not items: return new_items url = self.index_url + '/items/_bulk' logger.debug("Adding ...
[ "Upload in controlled packs items to ES using bulk API" ]
Please provide a description of the function:def get_last_date(self, field, filters_=[]): ''' :field: field with the data :filters_: additional filters to find the date ''' last_date = self.get_last_item_field(field, filters_=filters_) return last_date
[]
Please provide a description of the function:def get_last_offset(self, field, filters_=[]): ''' :field: field with the data :filters_: additional filters to find the date ''' offset = self.get_last_item_field(field, filters_=filters_, offset=True) return offset
[]
Please provide a description of the function:def get_last_item_field(self, field, filters_=[], offset=False): ''' :field: field with the data :filters_: additional filters to find the date :offset: Return offset field insted of date field ''' last_value = Non...
[]
Please provide a description of the function:def delete_items(self, retention_time, time_field="metadata__updated_on"): if retention_time is None: logger.debug("[items retention] Retention policy disabled, no items will be deleted.") return if retention_time <= 0: ...
[ "Delete documents updated before a given date\n\n :param retention_time: maximum number of minutes wrt the current date to retain the data\n :param time_field: time field to delete the data\n " ]
Please provide a description of the function:def all_properties(self): properties = {} r = self.requests.get(self.index_url + "/_mapping", headers=HEADER_JSON, verify=False) try: r.raise_for_status() r_json = r.json() if 'items' not in r_json[self.i...
[ "Get all properties of a given index" ]
Please provide a description of the function:def get_kibiter_version(url): config_url = '.kibana/config/_search' # Avoid having // in the URL because ES will fail if url[-1] != '/': url += "/" url += config_url r = requests.get(url) r.raise_for_status() if len(r.json()['hits']...
[ "\n Return kibiter major number version\n\n The url must point to the Elasticsearch used by Kibiter\n " ]
Please provide a description of the function:def get_params_parser(): parser = argparse.ArgumentParser(usage=ARTHUR_USAGE_MSG, description=ARTHUR_DESC_MSG, epilog=ARTHUR_EPILOG_MSG, formatter_class=a...
[ "Parse command line arguments" ]
Please provide a description of the function:def get_params(): parser = get_params_parser() args = parser.parse_args() if not args.enrich_only and not args.only_identities and not args.only_studies: if not args.index: # Check that the raw index name is defined print("[...
[ " Get params definition from ElasticOcean and from all the backends " ]
Please provide a description of the function: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_day...
[]
Please provide a description of the function:def get_identities(self, item): item = item['data'] if 'owner' in item: owner = self.get_sh_identity(item['owner']) yield owner if 'user' in item: user = self.get_sh_identity(item['user']) yiel...
[ "Return the identities from an item" ]
Please provide a description of the function:def get_item_sh(self, item, roles=None, date_field=None): eitem_sh = {} created = str_to_datetime(date_field) for rol in roles: identity = self.get_sh_identity(item, rol) eitem_sh.update(self.get_item_sh_fields(ident...
[ "Add sorting hat enrichment fields" ]
Please provide a description of the function:def get_identities(self, item): item = item['data'] for field in ["assignee", "reporter", "creator"]: if field not in item["fields"]: continue if item["fields"][field]: user = self.get_sh_iden...
[ "Return the identities from an item" ]
Please provide a description of the function: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'] == ...
[ "Enrich the fields property of an issue.\n\n Loops through al properties in issue['fields'],\n using those that are relevant to enrich eitem with new properties.\n Those properties are user defined, depending on options\n configured in Jira. For example, if SCRUM is activated,\n w...
Please provide a description of the function:def get_identities(self, item): identities = [] if 'data' not in item: return identities if 'revisions' not in item['data']: return identities revisions = item['data']['revisions'] for revision in re...
[ " Return the identities from an item " ]
Please provide a description of the function: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
[ " Add sorting hat enrichment fields for the author of the revision " ]
Please provide a description of the function:def get_identities(self, item): category = item['category'] item = item['data'] if category == "issue": identity_types = ['user', 'assignee'] elif category == "pull_request": identity_types = ['user', 'merged...
[ "Return the identities from an item" ]
Please provide a description of the function: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 ...
[ " Get cache data for items of _type using key_ as the cache dict key " ]
Please provide a description of the function: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: ...
[ "Get the first date at which a review was made on the PR by someone\n other than the user who created the PR\n " ]
Please provide a description of the function:def get_num_commenters(self, item): commenters = [comment['user']['login'] for comment in item['comments_data']] return len(set(commenters))
[ "Get the number of unique people who commented on the issue/pr" ]
Please provide a description of the function:def enrich_pull_requests(self, ocean_backend, enrich_backend, raw_issues_index="github_issues_raw"): HEADER_JSON = {"Content-Type": "application/json"} # issues raw index from which the data will be extracted github_issues_raw_index = ocean...
[ "\n The purpose of this Study is to add additional fields to the pull_requests only index.\n Basically to calculate some of the metrics from Code Development under GMD metrics:\n https://github.com/chaoss/wg-gmd/blob/master/2_Growth-Maturity-Decline.md#code-development\n\n When data from...
Please provide a description of the function:def get_identities(self, item): field = self.get_field_author() yield self.get_sh_identity(item, field)
[ " Return the identities from an item " ]
Please provide a description of the function:def get_identities(self, item): message = item['data']['message'] identity = self.get_sh_identity(message['from']) yield identity
[ " Return the identities from an item " ]
Please provide a description of the function:def get_params(): parser = argparse.ArgumentParser() parser.add_argument('-g', '--debug', dest='debug', action='store_true') parser.add_argument('-t', '--token', dest='token', help="GitHub token") parser.add_argument('-o', '--owner', dest='owner', help...
[ "Parse command line arguments" ]
Please provide a description of the function:def get_arthur_params_from_url(cls, url): params = {} owner = url.split('/')[-2] repository = url.split('/')[-1] # params.append('--owner') params['owner'] = owner # params.append('--repository') params['repos...
[ " Get the arthur params given a URL for the data source " ]
Please provide a description of the function:def get_identities(self, item): identities = [] field = self.get_field_author() identities.append(self.get_sh_identity(item, field)) return identities
[ " Return the identities from an item " ]
Please provide a description of the function: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_dow...
[ "\n In the events there are some common fields with the crate. The name\n of the field must be the same in the create and in the downloads event\n so we can filer using it in crate and event at the same time.\n\n * Fields that don't change: the field does not change with the events\n ...
Please provide a description of the function:def get_params_parser_create_dash(): parser = argparse.ArgumentParser(usage="usage: e2k.py [options]", description="Create a Kibana dashboard from a template") ElasticOcean.add_params(parser) parser.add_argument("-d", ...
[ "Parse command line arguments" ]
Please provide a description of the function:def get_identities(self, item): item = item['data'] user = self.get_sh_identity(item) yield user
[ " Return the identities from an item " ]
Please provide a description of the function: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...
[ " Get project mapping enrichment field.\n\n Twitter mappings is pretty special so it needs a special\n implementacion.\n " ]
Please provide a description of the function:def set_jenkins_rename_file(self, nodes_rename_file): self.nodes_rename_file = nodes_rename_file self.__load_node_renames() logger.info("Jenkis node rename file active: %s", nodes_rename_file)
[ " File with nodes renaming mapping:\n\n Node,Comment\n arm-build1,remove\n arm-build2,keep\n ericsson-build3,merge into ericsson-build1\n ....\n\n Once set in the next enrichment the rename will be done\n " ]
Please provide a description of the function:def get_fields_from_job_name(self, job_name): extra_fields = { 'category': None, 'installer': None, 'scenario': None, 'testproject': None, 'pod': None, 'loop': None, 'branch...
[ "Analyze a Jenkins job name, producing a dictionary\n\n The produced dictionary will include information about the category\n and subcategory of the job name, and any extra information which\n could be useful.\n\n For each deployment of a Jenkins dashboard, an implementation of\n ...
Please provide a description of the function: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...
[ "Extracts node name using a regular expression. Node name is expected to\n be group 1.\n " ]
Please provide a description of the function:def get_identities(self, item): data = item['data'] identity = self.get_sh_identity(data) if identity['username']: self.add_sh_github_identity(identity['username']) yield identity
[ " Return the identities from an item " ]
Please provide a description of the function: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
[ "Build and index for onion from a given Git index.\n\n :param in_conn: ESPandasConnector to read from.\n :param out_conn: ESPandasConnector to write to.\n :param data_source: name of the date source to generate onion from.\n :return: number of documents written in ElasticSearch enriched index.\n " ]
Please provide a description of the function: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: " + st...
[ "Read author commits by Quarter, Org and Project.\n\n :param from_date: not used here. Incremental mode not supported yet.\n :param size: not used here.\n :return: DataFrame with commit count per author, split by quarter, org and project.\n " ]
Please provide a description of the function:def write(self, items): if self._read_only: raise IOError("Cannot write, Connector created as Read Only") if len(items) == 0: logger.info(self.__log_prefix + " Nothing to write") return # Uploading info t...
[ "Write items into ElasticSearch.\n\n :param items: Pandas DataFrame\n " ]
Please provide a description of the function: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._so...
[ "Get a set of quarters with available items from a given index date.\n\n :param from_date:\n :return: list of `pandas.Period` corresponding to quarters\n " ]
Please provide a description of the function: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.agg...
[ "Retrieve a list of unique values in a given field within a date range.\n\n :param date_range:\n :param field_name:\n :return: list of unique values.\n " ]
Please provide a description of the function: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_st...
[ "Build a DataFrame from a time bucket.\n\n :param timing:\n :param project_name:\n :param org_name:\n :return:\n " ]
Please provide a description of the function: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, ...
[ "Process a DataFrame to compute Onion.\n\n :param items_block: items to be processed. Expects to find a pandas DataFrame.\n " ]
Please provide a description of the function: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 = ...
[ " Get the projects list from database ", "\n SELECT DISTINCT(repository_name)\n FROM project_repositories\n WHERE data_source='scr'\n " ]
Please provide a description of the function: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__._...
[ "Add metadata to an item.\n\n Decorator that adds metadata to a given item such as\n the gelk revision used.\n\n " ]
Please provide a description of the function:def __convert_json_to_projects_map(self, json): ds_repo_to_prj = {} for project in json: for ds in json[project]: if ds == "meta": continue # not a real data source if ds not in ds_rep...
[ " Convert JSON format to the projects map format\n map[ds][repository] = project\n If a repository is in several projects assign to leaf\n Check that all JSON data is in the database\n\n :param json: data with the projects to repositories mapping\n :returns: the repositories to pr...
Please provide a description of the function:def enrich_items(self, ocean_backend, events=False): max_items = self.elastic.max_items_bulk current = 0 total = 0 bulk_json = "" items = ocean_backend.fetch() url = self.elastic.index_url + '/items/_bulk' ...
[ "\n Enrich the items fetched from ocean_backend generator\n generating enriched items/events which are uploaded to the Elasticsearch index for\n this Enricher (self).\n\n :param ocean_backend: Ocean backend object to fetch the items from\n :param events: enrich items or enrich eve...
Please provide a description of the function: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_nam...
[ " Return common grimoire fields for all data sources " ]
Please provide a description of the function: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: ...
[ " Add project sub levels extra items " ]
Please provide a description of the function:def find_item_project(self, eitem): # get the data source name relying on the cfg section name, if null use the connector name ds_name = self.cfg_section_name if self.cfg_section_name else self.get_connector_name() try: # retriev...
[ "\n Find the project for a enriched item\n :param eitem: enriched item for which to find the project\n :return: the project entry (a dictionary)\n " ]
Please provide a description of the function:def get_item_project(self, eitem): eitem_project = {} project = self.find_item_project(eitem) if project is None: project = DEFAULT_PROJECT eitem_project = {"project": project} # Time to add the project levels: e...
[ "\n Get the project name related to the eitem\n :param eitem: enriched item for which to find the project\n :return: a dictionary with the project data\n " ]
Please provide a description of the function: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]: met...
[ "\n In the projects.json file, inside each project, there is a field called \"meta\" which has a\n dictionary with fields to be added to the enriched items for this project.\n\n This fields must be added with the prefix cm_ (custom metadata).\n\n This method fetch the metadata fields for...
Please provide a description of the function: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'])...
[ " Get the domain from a SH identity " ]
Please provide a description of the function: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) ...
[ " Get the enrollment for the uuid when the item was done " ]
Please provide a description of the function: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, ...
[ " Return a SH identity with all fields to empty_field " ]
Please provide a description of the function: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 ...
[ " Get standard SH fields from a SH identity " ]
Please provide a description of the function: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_dat...
[ "\n Add sorting hat enrichment fields for different roles\n\n If there are no roles, just add the author fields.\n\n " ]
Please provide a description of the function: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
[ " Return the Sorting Hat id and uuid for an identity " ]
Please provide a description of the function:def enrich_demography(self, ocean_backend, enrich_backend, date_field="grimoire_creation_date", author_field="author_uuid"): logger.info("[Demography] Starting study %s", self.elastic.anonymize_url(self.elastic.index_url)) ...
[ "\n The goal of the algorithm is to add to all enriched items the first and last date\n (i.e., demography_min_date, demography_max_date) of the author activities.\n\n In order to implement the algorithm first, the min and max dates (based on the date_field attribute)\n are retrieved for ...
Please provide a description of the function:def update_author_min_max_date(min_date, max_date, target_author, author_field="author_uuid"): es_query = ''' { "script": { "source": "ctx._source.demography_min_date = params.min_date;ctx._source.demography_max_dat...
[ "\n Get the query to update demography_min_date and demography_max_date of a given author\n\n :param min_date: new demography_min_date\n :param max_date: new demography_max_date\n :param target_author: target author to be updated\n :param author_field: author field\n\n :ret...
Please provide a description of the function:def get_params_parser(): parser = argparse.ArgumentParser() 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('-g', '--d...
[ "Parse command line arguments" ]
Please provide a description of the function: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_
[ " Returns the filter to be used in queries in a repository items " ]
Please provide a description of the function: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) ...
[ "Filter to be used when getting items from Ocean index" ]
Please provide a description of the function: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: f...
[ "Bool filter should to be used when getting items from Ocean index" ]
Please provide a description of the function: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 p...
[ " Fetch the items from raw or enriched index. An optional _filter\n could be provided to filter the data collected " ]
Please provide a description of the function:def get_elastic_items(self, elastic_scroll_id=None, _filter=None, ignore_incremental=False): headers = {"Content-Type": "application/json"} if not self.elastic: return None url = self.elastic.index_url # 1 minute to proc...
[ " Get the items from the index related to the backend applying and\n optional _filter if provided", " Just continue with the scrolling ", "\n {\n \"query\": {\n \"bool\": {\n \"filter\": [%s]\n }\n } %s\...
Please provide a description of the function: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_it...
[ " Find the unique identifier field for a given index " ]
Please provide a description of the function: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']...
[ " Find the mapping given an index " ]
Please provide a description of the function: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 ...
[ " Get the items from the index ", "\n {\n \"query\": {\n \"bool\": {\n \"must\": []\n }\n }\n }\n " ]
Please provide a description of the function:def get_elastic_items_search(elastic, search_after=None, size=None): if not size: size = DEFAULT_LIMIT url = elastic.index_url + "/_search" search_after_query = '' if search_after: logging.debug("Search after: %s", search_after) ...
[ " Get the items from the index using search after scrolling ", "\n {\n \"size\": %i,\n \"query\": {\n \"bool\": {\n \"must\": []\n }\n },\n \"sort\": [\n {\"metadata__timestamp\": \"asc\"},\n {\"uuid\": \"asc\"}\n ] %...
Please provide a description of the function: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_elast...
[ " Fetch the items from raw or enriched index " ]
Please provide a description of the function: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_a...
[ " Export items from in_index to out_index using the correct mapping " ]
Please provide a description of the function:def get_identities(self, item): item = item['data'] # Changeset owner user = item['owner'] identity = self.get_sh_identity(user) yield identity # Patchset uploader and author if 'patchSets' in item: ...
[ "Return the identities from an item" ]
Please provide a description of the function: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()...
[ "Convert dates so ES detect them" ]
Please provide a description of the function:def get_sh_identity(self, item, identity_field=None): def fill_list_identity(identity, user_list_data): identity['username'] = user_list_data[0]['__text__'] if '@' in identity['username']: identity['email...
[ " Return a Sorting Hat identity using bugzilla user data ", " Fill identity with user data in first item in list " ]
Please provide a description of the function:def get_identities(self, item): for rol in self.roles: if rol in item['data']: user = self.get_sh_identity(item["data"][rol]) yield user if 'activity' in item["data"]: for event in item["data"...
[ "Return the identities from an item" ]
Please provide a description of the function: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_proce...
[ "Populate an enriched index by processing input items in blocks.\n\n :return: total number of out_items written.\n " ]
Please provide a description of the function: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', ...
[ "Read items and return them one by one.\n\n :param from_date: start date for incremental reading.\n :return: next single item when any available.\n :raises ValueError: `metadata__timestamp` field not found in index\n :raises NotFoundError: index not found in ElasticSearch\n " ]
Please provide a description of the function: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',...
[ "Read items and return them in blocks.\n\n :param from_date: start date for incremental reading.\n :param size: block size.\n :return: next block of items when any available.\n :raises ValueError: `metadata__timestamp` field not found in index\n :raises NotFoundError: index not fo...
Please provide a description of the function: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_...
[ "Upload items to ElasticSearch.\n\n :param items: items to be uploaded.\n " ]
Please provide a description of the function:def create_index(self, mappings_file, delete=True): if self._read_only: raise IOError("Cannot write, Connector created as Read Only") if delete: logger.info(self.__log_prefix + " Deleting index " + self._es_index) ...
[ "Create a new index.\n\n :param mappings_file: index mappings to be used.\n :param delete: True to delete current index if exists.\n " ]
Please provide a description of the function: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" ]
Please provide a description of the function: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\n\n :return: True if alias already exist" ]
Please provide a description of the function: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": ...
[ "Build an ElasticSearch search query to retrieve items for read methods.\n\n :param from_date: date to start retrieving items from.\n :return: JSON query in dict format\n " ]