idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
18,200 | def find_biclique_embedding ( a , b , m , n = None , t = None , target_edges = None ) : _ , anodes = a _ , bnodes = b m , n , t , target_edges = _chimera_input ( m , n , t , target_edges ) embedding = processor ( target_edges , M = m , N = n , L = t ) . tightestNativeBiClique ( len ( anodes ) , len ( bnodes ) ) if not ... | Find an embedding for a biclique in a Chimera graph . |
18,201 | def find_grid_embedding ( dim , m , n = None , t = 4 ) : m , n , t , target_edges = _chimera_input ( m , n , t , None ) indexer = dnx . generators . chimera . chimera_coordinates ( m , n , t ) dim = list ( dim ) num_dim = len ( dim ) if num_dim == 1 : def _key ( row , col , aisle ) : return row dim . extend ( [ 1 , 1 ]... | Find an embedding for a grid in a Chimera graph . |
18,202 | def sample ( self , bqm , ** parameters ) : child = self . child cutoff = self . _cutoff cutoff_vartype = self . _cutoff_vartype comp = self . _comparison if cutoff_vartype is dimod . SPIN : original = bqm . spin else : original = bqm . binary new = type ( bqm ) ( original . linear , ( ( u , v , bias ) for ( u , v ) , ... | Cutoff and sample from the provided binary quadratic model . |
18,203 | def sample_poly ( self , poly , ** kwargs ) : child = self . child cutoff = self . _cutoff cutoff_vartype = self . _cutoff_vartype comp = self . _comparison if cutoff_vartype is dimod . SPIN : original = poly . to_spin ( copy = False ) else : original = poly . to_binary ( copy = False ) new = type ( poly ) ( ( ( term ,... | Cutoff and sample from the provided binary polynomial . |
18,204 | def diagnose_embedding ( emb , source , target ) : if not hasattr ( source , 'edges' ) : source = nx . Graph ( source ) if not hasattr ( target , 'edges' ) : target = nx . Graph ( target ) label = { } embedded = set ( ) for x in source : try : embx = emb [ x ] missing_chain = len ( embx ) == 0 except KeyError : missing... | A detailed diagnostic for minor embeddings . |
18,205 | def model ( self , name = None , model = None , mask = None , ** kwargs ) : if isinstance ( model , ( flask_marshmallow . Schema , flask_marshmallow . base_fields . FieldABC ) ) : if not name : name = model . __class__ . __name__ api_model = Model ( name , model , mask = mask ) api_model . __apidoc__ = kwargs return se... | Model registration decorator . |
18,206 | def parameters ( self , parameters , locations = None ) : def decorator ( func ) : if locations is None and parameters . many : _locations = ( 'json' , ) else : _locations = locations if _locations is not None : parameters . context [ 'in' ] = _locations return self . doc ( params = parameters ) ( self . response ( cod... | Endpoint parameters registration decorator . |
18,207 | def response ( self , model = None , code = HTTPStatus . OK , description = None , ** kwargs ) : code = HTTPStatus ( code ) if code is HTTPStatus . NO_CONTENT : assert model is None if model is None and code not in { HTTPStatus . ACCEPTED , HTTPStatus . NO_CONTENT } : if code . value not in http_exceptions . default_ex... | Endpoint response OpenAPI documentation decorator . |
18,208 | def _apply_decorator_to_methods ( cls , decorator ) : for method in cls . methods : method_name = method . lower ( ) decorated_method_func = decorator ( getattr ( cls , method_name ) ) setattr ( cls , method_name , decorated_method_func ) | This helper can apply a given decorator to all methods on the current Resource . |
18,209 | def options ( self , * args , ** kwargs ) : method_funcs = [ getattr ( self , m . lower ( ) ) for m in self . methods ] allowed_methods = [ ] request_oauth_backup = getattr ( flask . request , 'oauth' , None ) for method_func in method_funcs : if getattr ( method_func , '_access_restriction_decorators' , None ) : if no... | Check which methods are allowed . |
18,210 | def validate_patch_structure ( self , data ) : if data [ 'op' ] not in self . NO_VALUE_OPERATIONS and 'value' not in data : raise ValidationError ( 'value is required' ) if 'path' not in data : raise ValidationError ( 'Path is required and must always begin with /' ) else : data [ 'field_name' ] = data [ 'path' ] [ 1 :... | Common validation of PATCH structure |
18,211 | def perform_patch ( cls , operations , obj , state = None ) : if state is None : state = { } for operation in operations : if not cls . _process_patch_operation ( operation , obj = obj , state = state ) : log . info ( "%s patching has been stopped because of unknown operation %s" , obj . __class__ . __name__ , operatio... | Performs all necessary operations by calling class methods with corresponding names . |
18,212 | def replace ( cls , obj , field , value , state ) : if not hasattr ( obj , field ) : raise ValidationError ( "Field '%s' does not exist, so it cannot be patched" % field ) setattr ( obj , field , value ) return True | This is method for replace operation . It is separated to provide a possibility to easily override it in your Parameters . |
18,213 | def __related_categories ( self , category_id ) : related = [ ] for cat in self . categories_tree : if category_id in self . categories_tree [ cat ] : related . append ( self . categories [ cat ] ) return related | Get all related categories to a given one |
18,214 | def _create_projects_file ( project_name , data_source , items ) : repositories = [ ] for item in items : if item [ 'origin' ] not in repositories : repositories . append ( item [ 'origin' ] ) projects = { project_name : { data_source : repositories } } projects_file , projects_file_path = tempfile . mkstemp ( prefix =... | Create a projects file from the items origin data |
18,215 | 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 ( ) images_items = { } url = self . elastic . index_url + '/items/_bulk' logger . debug ( "Adding items to %s (in %i packs)" , self . elastic . anon... | A custom enrich items is needed because apart from the enriched events from raw items a image item with the last data for an image must be created |
18,216 | def get_owner_repos_url ( owner , token ) : url_org = GITHUB_API_URL + "/orgs/" + owner + "/repos" url_user = GITHUB_API_URL + "/users/" + owner + "/repos" url_owner = url_org try : r = requests . get ( url_org , params = get_payload ( ) , headers = get_headers ( token ) ) r . raise_for_status ( ) except requests . exc... | The owner could be a org or a user . It waits if need to have rate limit . Also it fixes a djando issue changing - with _ |
18,217 | def get_repositores ( owner_url , token , nrepos ) : all_repos = [ ] url = owner_url while True : logging . debug ( "Getting repos from: %s" % ( url ) ) try : r = requests . get ( url , params = get_payload ( ) , headers = get_headers ( token ) ) r . raise_for_status ( ) all_repos += r . json ( ) logging . debug ( "Rat... | owner could be an org or and user |
18,218 | def publish_twitter ( twitter_contact , owner ) : dashboard_url = CAULDRON_DASH_URL + "/%s" % ( owner ) tweet = "@%s your http://cauldron.io dashboard for #%s at GitHub is ready: %s. Check it out! #oscon" % ( twitter_contact , owner , dashboard_url ) status = quote_plus ( tweet ) oauth = get_oauth ( ) r = requests . po... | Publish in twitter the dashboard |
18,219 | def get_perceval_params_from_url ( cls , urls ) : params = [ ] dparam = cls . get_arthur_params_from_url ( urls ) params . append ( dparam [ "url" ] ) return params | Get the perceval params given the URLs for the data source |
18,220 | def add_identity ( cls , db , identity , backend ) : uuid = None try : uuid = api . add_identity ( db , backend , identity [ 'email' ] , identity [ 'name' ] , identity [ 'username' ] ) logger . debug ( "New sortinghat identity %s %s,%s,%s " , uuid , identity [ 'username' ] , identity [ 'name' ] , identity [ 'email' ] )... | Load and identity list from backend in Sorting Hat |
18,221 | def add_identities ( cls , db , identities , backend ) : logger . info ( "Adding the identities to SortingHat" ) total = 0 for identity in identities : try : cls . add_identity ( db , identity , backend ) total += 1 except Exception as e : logger . error ( "Unexcepted error when adding identities: %s" % e ) continue lo... | Load identities list from backend in Sorting Hat |
18,222 | def remove_identity ( cls , sh_db , ident_id ) : success = False try : api . delete_identity ( sh_db , ident_id ) logger . debug ( "Identity %s deleted" , ident_id ) success = True except Exception as e : logger . debug ( "Identity not deleted due to %s" , str ( e ) ) return success | Delete an identity from SortingHat . |
18,223 | def remove_unique_identity ( cls , sh_db , uuid ) : success = False try : api . delete_unique_identity ( sh_db , uuid ) logger . debug ( "Unique identity %s deleted" , uuid ) success = True except Exception as e : logger . debug ( "Unique identity not deleted due to %s" , str ( e ) ) return success | Delete a unique identity from SortingHat . |
18,224 | def unique_identities ( cls , sh_db ) : try : for unique_identity in api . unique_identities ( sh_db ) : yield unique_identity except Exception as e : logger . debug ( "Unique identities not returned from SortingHat due to %s" , str ( e ) ) | List the unique identities available in SortingHat . |
18,225 | def get_rich_events ( self , item ) : module = item [ 'data' ] if not item [ 'data' ] [ 'releases' ] : return [ ] for release in item [ 'data' ] [ 'releases' ] : event = self . get_rich_item ( item ) event [ "uuid" ] += "_" + release [ 'slug' ] event [ "author_url" ] = 'https://forge.puppet.com/' + release [ 'module' ]... | Get the enriched events related to a module |
18,226 | def _connect ( self ) : try : db = pymysql . connect ( user = self . user , passwd = self . passwd , host = self . host , port = self . port , db = self . shdb , use_unicode = True ) return db , db . cursor ( ) except Exception : logger . error ( "Database connection error" ) raise | Connect to the MySQL database . |
18,227 | 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 except AttributeError : pass new_identities = enrich_backend . get_item_sh_from_... | Refresh identities in enriched index . |
18,228 | 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 = filter_raw ) logger . debug ( "Last enrichment: %s" , last_enrich ) backend =... | Get the ocean backend configured to start from the last enriched date |
18,229 | 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_studies : logger . info ( "Starting stud... | Execute studies related to a given enrich backend . If retention_time is not None the study data is deleted based on the number of minutes declared in retention_time . |
18,230 | 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_IDENTITIES_INDEX , body = { "query" : { "bool" : { "filter" : [ { "terms" : { "sh_uuid" ... | Delete all unique identities which appear in SortingHat but not in the IDENTITIES_INDEX . |
18,231 | 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" : { "last_seen" : { "lte" : before_date } } } } ) sid = page [ '_scroll_id' ] scroll_size = page [ 'hits' ] [ ... | Select the unique identities not seen before before_date and delete them from SortingHat . |
18,232 | 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 = 120 , max_retries = 20 , retry_on_timeo... | Select the unique identities not seen before retention_time and delete them from SortingHat . Furthermore it deletes also the orphan unique identities those ones stored in SortingHat but not in IDENTITIES_INDEX . |
18,233 | 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_args ) backend_cmd . backend = backend_cmd . BACKEND ( ** init_args ) return backend_cmd | Init backend within the backend_cmd |
18,234 | 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 |
18,235 | 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 : version_str = res . json ( ) [ 'version' ] [ 'number' ] version_major = version_str . split ( '.' ) [ 0... | Checks if there is an instance of Elasticsearch in url . |
18,236 | 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 UnicodeEncodeError : logger . error ( "Encondig error ... converting bulk to iso-8859-... | Bulk PUT controlling unicode issues |
18,237 | 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 when retrieving aliases on %s." , self . anonymize_url ( self . index_url... | List all aliases used in ES |
18,238 | def list_aliases ( self ) : r = self . requests . get ( self . index_url + "/_alias" , headers = HEADER_JSON , verify = False ) try : r . raise_for_status ( ) except requests . exceptions . HTTPError as ex : logger . warning ( "Something went wrong when retrieving aliases on %s." , self . anonymize_url ( self . index_u... | List aliases linked to the index |
18,239 | def bulk_upload ( self , items , field_id ) : current = 0 new_items = 0 bulk_json = "" if not items : return new_items url = self . index_url + '/items/_bulk' logger . debug ( "Adding items to %s (in %i packs)" , self . anonymize_url ( url ) , self . max_items_bulk ) task_init = time ( ) for item in items : if current ... | Upload in controlled packs items to ES using bulk API |
18,240 | 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 . index ] [ 'mappings' ] : return properties if 'properties' not in r_json [ self . in... | Get all properties of a given index |
18,241 | def get_kibiter_version ( url ) : config_url = '.kibana/config/_search' if url [ - 1 ] != '/' : url += "/" url += config_url r = requests . get ( url ) r . raise_for_status ( ) if len ( r . json ( ) [ 'hits' ] [ 'hits' ] ) == 0 : logger . error ( "Can not get the Kibiter version" ) return None version = r . json ( ) [ ... | Return kibiter major number version |
18,242 | 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 : print ( "[error] --index <name> param is required when collecting items from raw" ) sys . exit ( 1 ) return args | Get params definition from ElasticOcean and from all the backends |
18,243 | 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 ( end_txt ) seconds_day = float ( 60 * 60 * 24 ) diff_days = ( end - start ) . total_seconds ( ) / seconds_day diff_days = float ( '%.2f' % diff_days ) return ... | Number of days between two days |
18,244 | 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' ]... | Enrich the fields property of an issue . |
18,245 | 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 |
18,246 | def get_github_cache ( self , kind , key_ ) : cache = { } res_size = 100 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 ... | Get cache data for items of _type using key_ as the cache dict key |
18,247 | 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_d... | 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 |
18,248 | 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 | Get the first date at which a review was made on the PR by someone other than the user who created the PR |
18,249 | def get_rich_events ( self , item ) : if "version_downloads_data" not in item [ 'data' ] : return [ ] 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_dat... | 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 . |
18,250 | def get_item_project ( self , eitem ) : project = None eitem_project = { } ds_name = self . get_connector_name ( ) if ds_name not in self . prjs_map : return eitem_project for tag in eitem [ 'hashtags_analyzed' ] : tags2project = CaseInsensitiveDict ( self . prjs_map [ ds_name ] ) if tag in tags2project : project = tag... | Get project mapping enrichment field . |
18,251 | 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 ... | Analyze a Jenkins job name producing a dictionary |
18,252 | 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 . war... | Extracts node name using a regular expression . Node name is expected to be group 1 . |
18,253 | 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 . |
18,254 | def read_block ( self , size = None , from_date = None ) : 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_uniqu... | Read author commits by Quarter Org and Project . |
18,255 | def __quarters ( self , from_date = None ) : s = Search ( using = self . _es_conn , index = self . _es_index ) if from_date : q = Q ( 'range' ) q . __setattr__ ( self . _sort_on_field , { 'gte' : from_date } ) s = s . filter ( q ) s = s [ 0 : 0 ] s . aggs . bucket ( self . TIMEFRAME , 'date_histogram' , field = self . ... | Get a set of quarters with available items from a given index date . |
18,256 | def __list_uniques ( self , date_range , field_name ) : s = Search ( using = self . _es_conn , index = self . _es_index ) s = s . filter ( 'range' , ** date_range ) s = s [ 0 : 0 ] s . aggs . bucket ( 'uniques' , 'terms' , field = field_name , size = 1000 ) response = s . execute ( ) uniques_list = [ ] for item in resp... | Retrieve a list of unique values in a given field within a date range . |
18,257 | 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 ... | Build a DataFrame from a time bucket . |
18,258 | 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 ) df_onion [ 'quart... | Process a DataFrame to compute Onion . |
18,259 | 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 = repos_list_raw = db . execute ( sql ) for repo in repos_list_raw : repo_name = repo [ 0 ] ... | Get the projects list from database |
18,260 | 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 ( ) . isofor... | Add metadata to an item . |
18,261 | 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 } | Return common grimoire fields for all data sources |
18,262 | 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 ... | Add project sub levels extra items |
18,263 | def get_item_metadata ( self , eitem ) : eitem_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 : va... | 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 . |
18,264 | def get_domain ( self , identity ) : domain = None if identity [ 'email' ] : try : domain = identity [ 'email' ] . split ( "@" ) [ 1 ] except IndexError : pass return domain | Get the domain from a SH identity |
18,265 | def get_enrollment ( self , uuid , item_date ) : 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 : en... | Get the enrollment for the uuid when the item was done |
18,266 | def __get_item_sh_fields_empty ( self , rol , undefined = False ) : 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 ,... | Return a SH identity with all fields to empty_field |
18,267 | 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 : sh_ids = self . get_sh_ids ( identity , self . get_connector_name ( ) ) eitem_sh [ rol + "_id" ] = sh_ids . get ( 'id' , '' ) eitem_sh [ rol + "_uuid"... | Get standard SH fields from a SH identity |
18,268 | def get_item_sh ( self , item , roles = None , date_field = None ) : eitem_sh = { } 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_d... | Add sorting hat enrichment fields for different roles |
18,269 | def get_sh_ids ( self , identity , backend_name ) : 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 |
18,270 | 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 |
18,271 | 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 ) | Filter to be used when getting items from Ocean index |
18,272 | 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 . appe... | Bool filter should to be used when getting items from Ocean index |
18,273 | 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 ... | Fetch the items from raw or enriched index . An optional _filter could be provided to filter the data collected |
18,274 | def find_uuid ( es_url , index ) : uid_field = None 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 : uuid_value = res . json ( ) [ 'hits' ] [ 'hits' ] ... | Find the unique identifier field for a given index |
18,275 | 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 | Find the mapping given an index |
18,276 | 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" url += "/_search?scroll=%s&size=%i" % ( max_process_items_pack_time , scroll_size ) if el... | Get the items from the index |
18,277 | 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_... | Fetch the items from raw or enriched index |
18,278 | 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 = searc... | Export items from in_index to out_index using the correct mapping |
18,279 | 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_... | Convert dates so ES detect them |
18,280 | 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' ] = identity [ 'username' ] if 'name' in user_list_data [ 0 ] : identity [ 'name' ] = ... | Return a Sorting Hat identity using bugzilla user data |
18,281 | 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 ... | Populate an enriched index by processing input items in blocks . |
18,282 | 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 | Read items and return them one by one . |
18,283 | 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 :... | Read items and return them in blocks . |
18,284 | def write ( self , items ) : if self . _read_only : raise IOError ( "Cannot write, Connector created as Read Only" ) docs = [ ] for item in items : doc = { "_index" : self . _es_index , "_type" : "item" , "_id" : item [ "_id" ] , "_source" : item [ "_source" ] } docs . append ( doc ) helpers . bulk ( self . _es_conn , ... | Upload items to ElasticSearch . |
18,285 | 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 |
18,286 | 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 |
18,287 | 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 =... | Build an ElasticSearch search query to retrieve items for read methods . |
18,288 | 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 index... | Shared params in all backends |
18,289 | def get_p2o_params_from_url ( cls , url ) : if PRJ_JSON_FILTER_SEPARATOR not in url : return { "url" : url } params = { 'url' : url . split ( ' ' , 1 ) [ 0 ] } 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" %... | Get the p2o params given a URL for the data source |
18,290 | 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_... | Feed data in Elastic from Perceval or Arthur |
18,291 | def get_identities ( self , item ) : def add_sh_github_identity ( user , user_field , rol ) : 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 user_data = item [ 'data' ] [ user... | Return the identities from an item . If the repo is in GitHub get the usernames from GitHub . |
18,292 | 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 ( tzin... | Fix possible errors in the field date |
18,293 | 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 . ... | Retrieve the commits not present in the original repository and delete the corresponding documents from the raw and enriched indexes |
18,294 | 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 ( [ bra... | 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 . |
18,295 | def find_ds_mapping ( data_source , es_major_version ) : mappings = { "raw" : None , "enriched" : None } 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 ) b... | Find the mapping given a perceval data source |
18,296 | 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 | Build and index for areas of code from a given Perceval RAW index . |
18,297 | def process ( self , items_block ) : logger . info ( self . __log_prefix + " New commits: " + str ( len ( items_block ) ) ) 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... | Process items to add file related information . |
18,298 | 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 . parse ( start ) . replace ( tzinfo = None ) if type ( end ) is not datetime . datetime : end = parser . parse ( end ) . replace ( tzinfo = None ) seconds_day = float ( 6... | Number of days between two dates in UTC format |
18,299 | 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... | Get mappings between phab ids and names |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.