idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
18,200 | 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 | 44 | 8 |
18,201 | 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 | Build an ElasticSearch search query to retrieve items for read methods . | 162 | 13 |
18,202 | 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" ) | Shared params in all backends | 108 | 7 |
18,203 | 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 | Get the p2o params given a URL for the data source | 285 | 13 |
18,204 | 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 ( ) | Feed data in Elastic from Perceval or Arthur | 591 | 10 |
18,205 | 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 | Return the identities from an item . If the repo is in GitHub get the usernames from GitHub . | 831 | 21 |
18,206 | 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 ( ) | Fix possible errors in the field date | 105 | 7 |
18,207 | 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 ) | Retrieve the commits not present in the original repository and delete the corresponding documents from the raw and enriched indexes | 633 | 21 |
18,208 | 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 | 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 . | 252 | 58 |
18,209 | 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 | Find the mapping given a perceval data source | 251 | 9 |
18,210 | 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 . | 82 | 16 |
18,211 | 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 ) | Process items to add file related information . | 434 | 8 |
18,212 | 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 ( 60 * 60 * 24 ) diff_days = ( end - start ) . total_seconds ( ) / seconds_day diff_days = float ( '%.2f' % diff_days ) return diff_days | Number of days between two dates in UTC format | 136 | 9 |
18,213 | 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' ] | Get mappings between phab ids and names | 411 | 10 |
18,214 | 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 | 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 . | 101 | 34 |
18,215 | 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 | 50 | 10 |
18,216 | 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 | returns a callable with no arguments designed to be the target of a Subprocess | 70 | 17 |
18,217 | 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 | Wraps a target with queues replacing stdout and stderr | 143 | 13 |
18,218 | 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 ) | Main loop for the process . This will run continuously until maxiter | 162 | 13 |
18,219 | 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 ) | Assistant function for string escaping | 62 | 5 |
18,220 | 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 | Factory of line protocol parsers | 708 | 6 |
18,221 | 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 | Adds to_lineprotocol method to arbitrary user - defined classes | 150 | 13 |
18,222 | 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 ) | Field values can be floats integers strings or Booleans . | 157 | 11 |
18,223 | 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 ) | Converts input data into line protocol format | 211 | 8 |
18,224 | 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 ( [ ] ) | Iterates a response JSON yielding data point by point . | 170 | 11 |
18,225 | 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 | Makes a dictionary of DataFrames from a response object | 121 | 11 |
18,226 | def _itertuples ( df ) : cols = [ df . iloc [ : , k ] for k in range ( len ( df . columns ) ) ] return zip ( df . index , * cols ) | Custom implementation of DataFrame . itertuples that returns plain tuples instead of namedtuples . About 50% faster . | 47 | 26 |
18,227 | 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' ) | Converts a Pandas DataFrame into line protocol format | 605 | 11 |
18,228 | 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 | Function execution decorator . | 82 | 5 |
18,229 | 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 ) ) | Checks for JSON error messages and raises Python exception | 88 | 10 |
18,230 | 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 | Create a magic packet . | 149 | 5 |
18,231 | 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 ( ) | Wake up computers having any of the given mac addresses . | 192 | 12 |
18,232 | 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 ) | Run wake on lan as a CLI application . | 225 | 9 |
18,233 | 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 ) | Compile MJML template after render django template . | 88 | 11 |
18,234 | 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 : ] | docstring for parse_header_line | 73 | 8 |
18,235 | 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 | Returns a list with the header lines if proper format | 252 | 10 |
18,236 | 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 ) | 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 . | 237 | 32 |
18,237 | 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 ) ) | Get data from post cid in network nid | 72 | 10 |
18,238 | 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 ) ) ) | Create a post or followup . | 54 | 7 |
18,239 | 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." ) | Enroll students in a network nid . | 91 | 9 |
18,240 | 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." ) | Get a listing of data for each user in a network nid | 56 | 13 |
18,241 | 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." ) | Get a listing of data for specific users user_ids in a network nid | 68 | 16 |
18,242 | 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." ) | Remove users from a network nid | 77 | 7 |
18,243 | 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." ) | Get my feed | 88 | 3 |
18,244 | 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." ) | Get filtered feed | 159 | 3 |
18,245 | 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 ) ) | Search for posts with query | 68 | 5 |
18,246 | 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." ) | Get statistics for class | 63 | 4 |
18,247 | 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 ( ) | Get data from arbitrary Piazza API endpoint method in network nid | 234 | 14 |
18,248 | 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' ) | Check result for error | 69 | 4 |
18,249 | 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 | Get list of the current user s classes . This is a subset of the information returned by the call to get_user_status . | 191 | 27 |
18,250 | def nonce ( ) : nonce_part1 = _int2base ( int ( _time ( ) * 1000 ) , 36 ) nonce_part2 = _int2base ( round ( _random ( ) * 1679616 ) , 36 ) return "{}{}" . format ( nonce_part1 , nonce_part2 ) | Returns a new nonce to be used with the Piazza API . | 73 | 15 |
18,251 | 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 ) | Get all posts visible to the current user | 83 | 8 |
18,252 | 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 ) | Create a post | 139 | 3 |
18,253 | 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 ) | Create a follow - up on a post post . | 111 | 10 |
18,254 | 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 ) | Create an instructor s answer to a post post . | 108 | 10 |
18,255 | 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 ) | Mark the post at duplicated_cid as a duplicate of master_cid | 125 | 17 |
18,256 | 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 ) | Mark post as resolved | 65 | 4 |
18,257 | def delete_post ( self , post ) : try : cid = post [ 'id' ] except KeyError : cid = post except TypeError : post = self . get_post ( post ) cid = post [ 'id' ] params = { "cid" : cid , } return self . _rpc . content_delete ( params ) | Deletes post by cid | 77 | 6 |
18,258 | def get_feed ( self , limit = 100 , offset = 0 ) : return self . _rpc . get_my_feed ( limit = limit , offset = offset ) | Get your feed for this network | 37 | 6 |
18,259 | def get_filtered_feed ( self , feed_filter ) : assert isinstance ( feed_filter , ( UnreadFilter , FollowingFilter , FolderFilter ) ) return self . _rpc . filter_feed ( * * feed_filter . to_kwargs ( ) ) | Get your feed containing only posts filtered by feed_filter | 59 | 11 |
18,260 | def get_dataset ( self , dataset ) : # If the dataset is present, no need to download anything. success = True dataset_path = self . base_dataset_path + dataset if not isdir ( dataset_path ) : # Try 5 times to download. The download page is unreliable, so we need a few tries. was_error = False for iteration in range ( 5 ) : # Guard against trying again if successful if iteration == 0 or was_error is True : zip_path = dataset_path + ".zip" # Download zip files if they're not there if not isfile ( zip_path ) : try : with DLProgress ( unit = 'B' , unit_scale = True , miniters = 1 , desc = dataset ) as pbar : urlretrieve ( self . datasets [ dataset ] [ "url" ] , zip_path , pbar . hook ) except Exception as ex : print ( "Error downloading %s: %s" % ( dataset , ex ) ) was_error = True # Unzip the data files if not isdir ( dataset_path ) : try : with zipfile . ZipFile ( zip_path ) as zip_archive : zip_archive . extractall ( path = dataset_path ) zip_archive . close ( ) except Exception as ex : print ( "Error unzipping %s: %s" % ( zip_path , ex ) ) # Usually the error is caused by a bad zip file. # Delete it so the program will try to download it again. try : remove ( zip_path ) except FileNotFoundError : pass was_error = True if was_error : print ( "\nThis recognizer is trained by the CASIA handwriting database." ) print ( "If the download doesn't work, you can get the files at %s" % self . datasets [ dataset ] [ "url" ] ) print ( "If you have download problems, " "wget may be effective at downloading because of download resuming." ) success = False return success | Checks to see if the dataset is present . If not it downloads and unzips it . | 429 | 20 |
18,261 | def first_plugin_context ( self ) : # Note, because registrations are stored in a set, its not _really_ # the first one, but whichever one it sees first in the set. first_spf_reg = next ( iter ( self . registrations ) ) return self . get_context_from_spf ( first_spf_reg ) | Returns the context is associated with the first app this plugin was registered on | 76 | 14 |
18,262 | async def route_wrapper ( self , route , request , context , request_args , request_kw , * decorator_args , with_context = None , * * decorator_kw ) : # by default, do nothing, just run the wrapped function if with_context : resp = route ( request , context , * request_args , * * request_kw ) else : resp = route ( request , * request_args , * * request_kw ) if isawaitable ( resp ) : resp = await resp return resp | This is the function that is called when a route is decorated with your plugin decorator . Context will normally be None but the user can pass use_context = True so the route will get the plugin context | 113 | 41 |
18,263 | def check_credentials ( client ) : pid , uid , gid = get_peercred ( client ) euid = os . geteuid ( ) client_name = "PID:%s UID:%s GID:%s" % ( pid , uid , gid ) if uid not in ( 0 , euid ) : raise SuspiciousClient ( "Can't accept client with %s. It doesn't match the current EUID:%s or ROOT." % ( client_name , euid ) ) _LOG ( "Accepted connection on fd:%s from %s" % ( client . fileno ( ) , client_name ) ) return pid , uid , gid | Checks credentials for given socket . | 156 | 7 |
18,264 | def handle_connection_exec ( client ) : class ExitExecLoop ( Exception ) : pass def exit ( ) : raise ExitExecLoop ( ) client . settimeout ( None ) fh = os . fdopen ( client . detach ( ) if hasattr ( client , 'detach' ) else client . fileno ( ) ) with closing ( client ) : with closing ( fh ) : try : payload = fh . readline ( ) while payload : _LOG ( "Running: %r." % payload ) eval ( compile ( payload , '<manhole>' , 'exec' ) , { 'exit' : exit } , _MANHOLE . locals ) payload = fh . readline ( ) except ExitExecLoop : _LOG ( "Exiting exec loop." ) | Alternate connection handler . No output redirection . | 166 | 10 |
18,265 | def handle_connection_repl ( client ) : client . settimeout ( None ) # # disable this till we have evidence that it's needed # client.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 0) # # Note: setting SO_RCVBUF on UDS has no effect, see: http://man7.org/linux/man-pages/man7/unix.7.html backup = [ ] old_interval = getinterval ( ) patches = [ ( 'r' , ( 'stdin' , '__stdin__' ) ) , ( 'w' , ( 'stdout' , '__stdout__' ) ) ] if _MANHOLE . redirect_stderr : patches . append ( ( 'w' , ( 'stderr' , '__stderr__' ) ) ) try : client_fd = client . fileno ( ) for mode , names in patches : for name in names : backup . append ( ( name , getattr ( sys , name ) ) ) setattr ( sys , name , _ORIGINAL_FDOPEN ( client_fd , mode , 1 if PY3 else 0 ) ) try : handle_repl ( _MANHOLE . locals ) except Exception as exc : _LOG ( "REPL failed with %r." % exc ) _LOG ( "DONE." ) finally : try : # Change the switch/check interval to something ridiculous. We don't want to have other thread try # to write to the redirected sys.__std*/sys.std* - it would fail horribly. setinterval ( 2147483647 ) try : client . close ( ) # close before it's too late. it may already be dead except IOError : pass junk = [ ] # keep the old file objects alive for a bit for name , fh in backup : junk . append ( getattr ( sys , name ) ) setattr ( sys , name , fh ) del backup for fh in junk : try : if hasattr ( fh , 'detach' ) : fh . detach ( ) else : fh . close ( ) except IOError : pass del fh del junk finally : setinterval ( old_interval ) _LOG ( "Cleaned up." ) | Handles connection . | 495 | 4 |
18,266 | def install ( verbose = True , verbose_destination = sys . __stderr__ . fileno ( ) if hasattr ( sys . __stderr__ , 'fileno' ) else sys . __stderr__ , strict = True , * * kwargs ) : # pylint: disable=W0603 global _MANHOLE with _LOCK : if _MANHOLE is None : _MANHOLE = Manhole ( ) else : if strict : raise AlreadyInstalled ( "Manhole already installed!" ) else : _LOG . release ( ) _MANHOLE . release ( ) # Threads might be started here _LOG . configure ( verbose , verbose_destination ) _MANHOLE . configure ( * * kwargs ) # Threads might be started here return _MANHOLE | Installs the manhole . | 178 | 6 |
18,267 | def dump_stacktraces ( ) : lines = [ ] for thread_id , stack in sys . _current_frames ( ) . items ( ) : # pylint: disable=W0212 lines . append ( "\n######### ProcessID=%s, ThreadID=%s #########" % ( os . getpid ( ) , thread_id ) ) for filename , lineno , name , line in traceback . extract_stack ( stack ) : lines . append ( 'File: "%s", line %d, in %s' % ( filename , lineno , name ) ) if line : lines . append ( " %s" % ( line . strip ( ) ) ) lines . append ( "#############################################\n\n" ) print ( '\n' . join ( lines ) , file = sys . stderr if _MANHOLE . redirect_stderr else sys . stdout ) | Dumps thread ids and tracebacks to stdout . | 198 | 12 |
18,268 | def clone ( self , * * kwargs ) : return ManholeThread ( self . get_socket , self . sigmask , self . start_timeout , connection_handler = self . connection_handler , daemon_connection = self . daemon_connection , * * kwargs ) | Make a fresh thread with the same options . This is usually used on dead threads . | 61 | 17 |
18,269 | def reinstall ( self ) : with _LOCK : if not ( self . thread . is_alive ( ) and self . thread in _ORIGINAL__ACTIVE ) : self . thread = self . thread . clone ( bind_delay = self . reinstall_delay ) if self . should_restart : self . thread . start ( ) | Reinstalls the manhole . Checks if the thread is running . If not it starts it again . | 74 | 21 |
18,270 | def patched_forkpty ( self ) : pid , master_fd = self . original_os_forkpty ( ) if not pid : _LOG ( 'Fork detected. Reinstalling Manhole.' ) self . reinstall ( ) return pid , master_fd | Fork a new process with a new pseudo - terminal as controlling tty . | 56 | 16 |
18,271 | def create ( self , policy_id , name , threshold_type , query , since_value , terms , expected_groups = None , value_function = None , runbook_url = None , ignore_overlap = None , enabled = True ) : data = { 'nrql_condition' : { 'type' : threshold_type , 'name' : name , 'enabled' : enabled , 'terms' : terms , 'nrql' : { 'query' : query , 'since_value' : since_value } } } if runbook_url is not None : data [ 'nrql_condition' ] [ 'runbook_url' ] = runbook_url if expected_groups is not None : data [ 'nrql_condition' ] [ 'expected_groups' ] = expected_groups if ignore_overlap is not None : data [ 'nrql_condition' ] [ 'ignore_overlap' ] = ignore_overlap if value_function is not None : data [ 'nrql_condition' ] [ 'value_function' ] = value_function if data [ 'nrql_condition' ] [ 'type' ] == 'static' : if 'value_function' not in data [ 'nrql_condition' ] : raise ConfigurationException ( 'Alert is set as static but no value_function config specified' ) data [ 'nrql_condition' ] . pop ( 'expected_groups' , None ) data [ 'nrql_condition' ] . pop ( 'ignore_overlap' , None ) elif data [ 'nrql_condition' ] [ 'type' ] == 'outlier' : if 'expected_groups' not in data [ 'nrql_condition' ] : raise ConfigurationException ( 'Alert is set as outlier but expected_groups config is not specified' ) if 'ignore_overlap' not in data [ 'nrql_condition' ] : raise ConfigurationException ( 'Alert is set as outlier but ignore_overlap config is not specified' ) data [ 'nrql_condition' ] . pop ( 'value_function' , None ) return self . _post ( url = '{0}alerts_nrql_conditions/policies/{1}.json' . format ( self . URL , policy_id ) , headers = self . headers , data = data ) | Creates an alert condition nrql | 505 | 8 |
18,272 | def delete ( self , alert_condition_nrql_id ) : return self . _delete ( url = '{0}alerts_nrql_conditions/{1}.json' . format ( self . URL , alert_condition_nrql_id ) , headers = self . headers ) | This API endpoint allows you to delete an alert condition nrql | 64 | 13 |
18,273 | def list ( self , filter_name = None , filter_ids = None , filter_labels = None , page = None ) : label_param = '' if filter_labels : label_param = ';' . join ( [ '{}:{}' . format ( label , value ) for label , value in filter_labels . items ( ) ] ) filters = [ 'filter[name]={0}' . format ( filter_name ) if filter_name else None , 'filter[ids]={0}' . format ( ',' . join ( [ str ( app_id ) for app_id in filter_ids ] ) ) if filter_ids else None , 'filter[labels]={0}' . format ( label_param ) if filter_labels else None , 'page={0}' . format ( page ) if page else None ] return self . _get ( url = '{0}servers.json' . format ( self . URL ) , headers = self . headers , params = self . build_param_string ( filters ) ) | This API endpoint returns a paginated list of the Servers associated with your New Relic account . Servers can be filtered by their name or by a list of server IDs . | 232 | 35 |
18,274 | def update ( self , id , name = None ) : nr_data = self . show ( id ) [ 'server' ] data = { 'server' : { 'name' : name or nr_data [ 'name' ] , } } return self . _put ( url = '{0}servers/{1}.json' . format ( self . URL , id ) , headers = self . headers , data = data ) | Updates any of the optional parameters of the server | 94 | 10 |
18,275 | def create ( self , name , incident_preference ) : data = { "policy" : { "name" : name , "incident_preference" : incident_preference } } return self . _post ( url = '{0}alerts_policies.json' . format ( self . URL ) , headers = self . headers , data = data ) | This API endpoint allows you to create an alert policy | 80 | 10 |
18,276 | def update ( self , id , name , incident_preference ) : data = { "policy" : { "name" : name , "incident_preference" : incident_preference } } return self . _put ( url = '{0}alerts_policies/{1}.json' . format ( self . URL , id ) , headers = self . headers , data = data ) | This API endpoint allows you to update an alert policy | 87 | 10 |
18,277 | def delete ( self , id ) : return self . _delete ( url = '{0}alerts_policies/{1}.json' . format ( self . URL , id ) , headers = self . headers ) | This API endpoint allows you to delete an alert policy | 48 | 10 |
18,278 | def associate_with_notification_channel ( self , id , channel_id ) : return self . _put ( url = '{0}alerts_policy_channels.json?policy_id={1}&channel_ids={2}' . format ( self . URL , id , channel_id ) , headers = self . headers ) | This API endpoint allows you to associate an alert policy with an notification channel | 75 | 14 |
18,279 | def dissociate_from_notification_channel ( self , id , channel_id ) : return self . _delete ( url = '{0}alerts_policy_channels.json?policy_id={1}&channel_id={2}' . format ( self . URL , id , channel_id ) , headers = self . headers ) | This API endpoint allows you to dissociate an alert policy from an notification channel | 76 | 15 |
18,280 | def list ( self , policy_id , page = None ) : filters = [ 'policy_id={0}' . format ( policy_id ) , 'page={0}' . format ( page ) if page else None ] return self . _get ( url = '{0}alerts_conditions.json' . format ( self . URL ) , headers = self . headers , params = self . build_param_string ( filters ) ) | This API endpoint returns a paginated list of alert conditions associated with the given policy_id . | 96 | 19 |
18,281 | def update ( self , alert_condition_id , policy_id , type = None , condition_scope = None , name = None , entities = None , metric = None , runbook_url = None , terms = None , user_defined = None , enabled = None ) : conditions_dict = self . list ( policy_id ) target_condition = None for condition in conditions_dict [ 'conditions' ] : if int ( condition [ 'id' ] ) == alert_condition_id : target_condition = condition break if target_condition is None : raise NoEntityException ( 'Target alert condition is not included in that policy.' 'policy_id: {}, alert_condition_id {}' . format ( policy_id , alert_condition_id ) ) data = { 'condition' : { 'type' : type or target_condition [ 'type' ] , 'name' : name or target_condition [ 'name' ] , 'entities' : entities or target_condition [ 'entities' ] , 'condition_scope' : condition_scope or target_condition [ 'condition_scope' ] , 'terms' : terms or target_condition [ 'terms' ] , 'metric' : metric or target_condition [ 'metric' ] , 'runbook_url' : runbook_url or target_condition [ 'runbook_url' ] , } } if enabled is not None : data [ 'condition' ] [ 'enabled' ] = str ( enabled ) . lower ( ) if data [ 'condition' ] [ 'metric' ] == 'user_defined' : if user_defined : data [ 'condition' ] [ 'user_defined' ] = user_defined elif 'user_defined' in target_condition : data [ 'condition' ] [ 'user_defined' ] = target_condition [ 'user_defined' ] else : raise ConfigurationException ( 'Metric is set as user_defined but no user_defined config specified' ) return self . _put ( url = '{0}alerts_conditions/{1}.json' . format ( self . URL , alert_condition_id ) , headers = self . headers , data = data ) | Updates any of the optional parameters of the alert condition | 472 | 11 |
18,282 | def create ( self , policy_id , type , condition_scope , name , entities , metric , terms , runbook_url = None , user_defined = None , enabled = True ) : data = { 'condition' : { 'type' : type , 'name' : name , 'enabled' : enabled , 'entities' : entities , 'condition_scope' : condition_scope , 'terms' : terms , 'metric' : metric , 'runbook_url' : runbook_url , } } if metric == 'user_defined' : if user_defined : data [ 'condition' ] [ 'user_defined' ] = user_defined else : raise ConfigurationException ( 'Metric is set as user_defined but no user_defined config specified' ) return self . _post ( url = '{0}alerts_conditions/policies/{1}.json' . format ( self . URL , policy_id ) , headers = self . headers , data = data ) | Creates an alert condition | 215 | 5 |
18,283 | def delete ( self , alert_condition_id ) : return self . _delete ( url = '{0}alerts_conditions/{1}.json' . format ( self . URL , alert_condition_id ) , headers = self . headers ) | This API endpoint allows you to delete an alert condition | 55 | 10 |
18,284 | def list ( self , policy_id , limit = None , offset = None ) : filters = [ 'policy_id={0}' . format ( policy_id ) , 'limit={0}' . format ( limit ) if limit else '50' , 'offset={0}' . format ( offset ) if offset else '0' ] return self . _get ( url = '{0}alerts/conditions' . format ( self . URL ) , headers = self . headers , params = self . build_param_string ( filters ) ) | This API endpoint returns a paginated list of alert conditions for infrastucture metrics associated with the given policy_id . | 118 | 25 |
18,285 | def show ( self , alert_condition_infra_id ) : return self . _get ( url = '{0}alerts/conditions/{1}' . format ( self . URL , alert_condition_infra_id ) , headers = self . headers , ) | This API endpoint returns an alert condition for infrastucture identified by its ID . | 61 | 17 |
18,286 | def create ( self , policy_id , name , condition_type , alert_condition_configuration , enabled = True ) : data = { "data" : alert_condition_configuration } data [ 'data' ] [ 'type' ] = condition_type data [ 'data' ] [ 'policy_id' ] = policy_id data [ 'data' ] [ 'name' ] = name data [ 'data' ] [ 'enabled' ] = enabled return self . _post ( url = '{0}alerts/conditions' . format ( self . URL ) , headers = self . headers , data = data ) | This API endpoint allows you to create an alert condition for infrastucture | 135 | 15 |
18,287 | def update ( self , alert_condition_infra_id , policy_id , name , condition_type , alert_condition_configuration , enabled = True ) : data = { "data" : alert_condition_configuration } data [ 'data' ] [ 'type' ] = condition_type data [ 'data' ] [ 'policy_id' ] = policy_id data [ 'data' ] [ 'name' ] = name data [ 'data' ] [ 'enabled' ] = enabled return self . _put ( url = '{0}alerts/conditions/{1}' . format ( self . URL , alert_condition_infra_id ) , headers = self . headers , data = data ) | This API endpoint allows you to update an alert condition for infrastucture | 157 | 15 |
18,288 | def delete ( self , alert_condition_infra_id ) : return self . _delete ( url = '{0}alerts/conditions/{1}' . format ( self . URL , alert_condition_infra_id ) , headers = self . headers ) | This API endpoint allows you to delete an alert condition for infrastucture | 60 | 15 |
18,289 | def create ( self , name , category , applications = None , servers = None ) : data = { "label" : { "category" : category , "name" : name , "links" : { "applications" : applications or [ ] , "servers" : servers or [ ] } } } return self . _put ( url = '{0}labels.json' . format ( self . URL ) , headers = self . headers , data = data ) | This API endpoint will create a new label with the provided name and category | 101 | 14 |
18,290 | def delete ( self , key ) : return self . _delete ( url = '{url}labels/labels/{key}.json' . format ( url = self . URL , key = key ) , headers = self . headers , ) | When applications are provided this endpoint will remove those applications from the label . | 52 | 14 |
18,291 | def list ( self , filter_guid = None , filter_ids = None , detailed = None , page = None ) : filters = [ 'filter[guid]={0}' . format ( filter_guid ) if filter_guid else None , 'filter[ids]={0}' . format ( ',' . join ( [ str ( app_id ) for app_id in filter_ids ] ) ) if filter_ids else None , 'detailed={0}' . format ( detailed ) if detailed is not None else None , 'page={0}' . format ( page ) if page else None ] return self . _get ( url = '{0}plugins.json' . format ( self . URL ) , headers = self . headers , params = self . build_param_string ( filters ) ) | This API endpoint returns a paginated list of the plugins associated with your New Relic account . | 177 | 18 |
18,292 | def list ( self , application_id , filter_hostname = None , filter_ids = None , page = None ) : filters = [ 'filter[hostname]={0}' . format ( filter_hostname ) if filter_hostname else None , 'filter[ids]={0}' . format ( ',' . join ( [ str ( app_id ) for app_id in filter_ids ] ) ) if filter_ids else None , 'page={0}' . format ( page ) if page else None ] return self . _get ( url = '{root}applications/{application_id}/instances.json' . format ( root = self . URL , application_id = application_id ) , headers = self . headers , params = self . build_param_string ( filters ) ) | This API endpoint returns a paginated list of instances associated with the given application . | 178 | 16 |
18,293 | def show ( self , application_id , host_id ) : return self . _get ( url = '{root}applications/{application_id}/hosts/{host_id}.json' . format ( root = self . URL , application_id = application_id , host_id = host_id ) , headers = self . headers , ) | This API endpoint returns a single application host identified by its ID . | 79 | 13 |
18,294 | def metric_data ( self , id , names , values = None , from_dt = None , to_dt = None , summarize = False ) : params = [ 'from={0}' . format ( from_dt ) if from_dt else None , 'to={0}' . format ( to_dt ) if to_dt else None , 'summarize=true' if summarize else None ] params += [ 'names[]={0}' . format ( name ) for name in names ] if values : params += [ 'values[]={0}' . format ( value ) for value in values ] return self . _get ( url = '{0}components/{1}/metrics/data.json' . format ( self . URL , id ) , headers = self . headers , params = self . build_param_string ( params ) ) | This API endpoint returns a list of values for each of the requested metrics . The list of available metrics can be returned using the Metric Name API endpoint . | 185 | 31 |
18,295 | def create ( self , dashboard_data ) : return self . _post ( url = '{0}dashboards.json' . format ( self . URL ) , headers = self . headers , data = dashboard_data , ) | This API endpoint creates a dashboard and all defined widgets . | 48 | 11 |
18,296 | def update ( self , id , dashboard_data ) : return self . _put ( url = '{0}dashboards/{1}.json' . format ( self . URL , id ) , headers = self . headers , data = dashboard_data , ) | This API endpoint updates a dashboard and all defined widgets . | 55 | 11 |
18,297 | def operatorPrecedence ( base , operators ) : # The full expression, used to provide sub-expressions expression = Forward ( ) # The initial expression last = base | Suppress ( '(' ) + expression + Suppress ( ')' ) def parse_operator ( expr , arity , association , action = None , extra = None ) : return expr , arity , association , action , extra for op in operators : # Use a function to default action to None expr , arity , association , action , extra = parse_operator ( * op ) # Check that the arity is valid if arity < 1 or arity > 2 : raise Exception ( "Arity must be unary (1) or binary (2)" ) if association not in ( opAssoc . LEFT , opAssoc . RIGHT ) : raise Exception ( "Association must be LEFT or RIGHT" ) # This will contain the expression this = Forward ( ) # Create an expression based on the association and arity if association is opAssoc . LEFT : new_last = ( last | extra ) if extra else last if arity == 1 : operator_expression = new_last + OneOrMore ( expr ) elif arity == 2 : operator_expression = last + OneOrMore ( expr + new_last ) elif association is opAssoc . RIGHT : new_this = ( this | extra ) if extra else this if arity == 1 : operator_expression = expr + new_this # Currently no operator uses this, so marking it nocover for now elif arity == 2 : # nocover operator_expression = last + OneOrMore ( new_this ) # nocover # Set the parse action for the operator if action is not None : operator_expression . setParseAction ( action ) this <<= ( operator_expression | last ) last = this # Set the full expression and return it expression <<= last return expression | This re - implements pyparsing s operatorPrecedence function . | 408 | 15 |
18,298 | def set_parse_attributes ( self , string , location , tokens ) : self . string = string self . location = location self . tokens = tokens return self | Fluent API for setting parsed location | 34 | 7 |
18,299 | def evaluate_object ( obj , cls = None , cache = False , * * kwargs ) : old_obj = obj if isinstance ( obj , Element ) : if cache : obj = obj . evaluate_cached ( * * kwargs ) else : obj = obj . evaluate ( cache = cache , * * kwargs ) if cls is not None and type ( obj ) != cls : obj = cls ( obj ) for attr in ( 'string' , 'location' , 'tokens' ) : if hasattr ( old_obj , attr ) : setattr ( obj , attr , getattr ( old_obj , attr ) ) return obj | Evaluates elements and coerces objects to a class if needed | 148 | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.