idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
16,700
def _update_failure_type ( self ) : note = JobNote . objects . filter ( job = self . job ) . order_by ( '-created' ) . first ( ) if note : self . job . failure_classification_id = note . failure_classification . id else : self . job . failure_classification_id = FailureClassification . objects . get ( name = 'not class...
Updates the failure type of this Note s Job .
16,701
def _ensure_classification ( self ) : if not self . user : return if self . failure_classification . name not in [ "intermittent" , "intermittent needs filing" ] : return text_log_error = self . job . get_manual_classification_line ( ) if not text_log_error : return existing_bugs = list ( ClassifiedFailure . objects . ...
Ensures a single TextLogError s related bugs have Classifications .
16,702
def create_autoclassify_job_note ( self , job , user = None ) : bug_numbers = set ( ClassifiedFailure . objects . filter ( best_for_errors__text_log_error__step__job = job , best_for_errors__best_is_verified = True ) . exclude ( bug_number = None ) . exclude ( bug_number = 0 ) . values_list ( 'bug_number' , flat = True...
Create a JobNote possibly via auto - classification .
16,703
def unstructured_bugs ( self ) : components = self . _serialized_components ( ) if not components : return [ ] from treeherder . model . error_summary import get_useful_search_results job = Job . objects . get ( guid = self . job_guid ) rv = [ ] ids_seen = set ( ) for item in get_useful_search_results ( job ) : if all ...
Get bugs that match this line in the Bug Suggestions artifact for this job .
16,704
def to_mozlog_format ( self ) : data = { "action" : self . action , "line_number" : self . line , "test" : self . test , "subtest" : self . subtest , "status" : self . status , "expected" : self . expected , "message" : self . message , "signature" : self . signature , "level" : self . level , "stack" : self . stack , ...
Convert a FailureLine into a mozlog formatted dictionary .
16,705
def set_bug ( self , bug_number ) : if bug_number == self . bug_number : return self other = ClassifiedFailure . objects . filter ( bug_number = bug_number ) . first ( ) if not other : self . bug_number = bug_number self . save ( update_fields = [ 'bug_number' ] ) return self self . replace_with ( other ) return other
Set the bug number of this Classified Failure
16,706
def replace_with ( self , other ) : match_ids_to_delete = list ( self . update_matches ( other ) ) TextLogErrorMatch . objects . filter ( id__in = match_ids_to_delete ) . delete ( ) self . best_for_errors . update ( best_classification = other ) self . delete ( )
Replace this instance with the given other .
16,707
def update_matches ( self , other ) : for match in self . error_matches . all ( ) : other_matches = TextLogErrorMatch . objects . filter ( classified_failure = other , text_log_error = match . text_log_error , ) if not other_matches : match . classified_failure = other match . save ( update_fields = [ 'classified_failu...
Update this instance s Matches to point to the given other s Matches .
16,708
def create_match ( self , matcher_name , classification ) : if classification is None : classification = ClassifiedFailure . objects . create ( ) TextLogErrorMatch . objects . create ( text_log_error = self , classified_failure = classification , matcher_name = matcher_name , score = 1 , )
Create a TextLogErrorMatch instance
16,709
def verify_classification ( self , classification ) : if classification not in self . classified_failures . all ( ) : self . create_match ( "ManualDetector" , classification ) if self . metadata is None : TextLogErrorMetadata . objects . create ( text_log_error = self , best_classification = classification , best_is_ve...
Mark the given ClassifiedFailure as verified .
16,710
def create_bug ( self , request ) : if settings . BUGFILER_API_KEY is None : return Response ( { "failure" : "Bugzilla API key not set!" } , status = HTTP_400_BAD_REQUEST ) params = request . data crash_signature = params . get ( "crash_signature" ) if crash_signature and len ( crash_signature ) > 2048 : return Respons...
Create a bugzilla bug with passed params
16,711
def chunked_qs ( qs , chunk_size = 10000 , fields = None ) : min_id = 0 while True : chunk = qs . filter ( id__gt = min_id ) . order_by ( 'id' ) if fields is not None : chunk = chunk . only ( * fields ) rows = list ( chunk [ : chunk_size ] ) total = len ( rows ) if total < 1 : break yield rows min_id = rows [ - 1 ] . i...
Generator to iterate over the given QuerySet chunk_size rows at a time
16,712
def chunked_qs_reverse ( qs , chunk_size = 10000 ) : if not qs : return qs = qs . order_by ( '-id' ) max_id = qs . first ( ) . id while True : chunk = qs . filter ( id__lte = max_id ) rows = chunk [ : chunk_size ] if len ( rows ) < 1 : break yield rows max_id = max_id - chunk_size
Generator to iterate over the given QuerySet in reverse chunk_size rows at a time
16,713
def create ( self , request , project ) : job_id = int ( request . data [ 'job_id' ] ) bug_id = int ( request . data [ 'bug_id' ] ) try : BugJobMap . create ( job_id = job_id , bug_id = bug_id , user = request . user , ) message = "Bug job map saved" except IntegrityError : message = "Bug job map skipped: mapping alrea...
Add a new relation between a job and a bug .
16,714
def destroy ( self , request , project , pk = None ) : job_id , bug_id = map ( int , pk . split ( "-" ) ) job = Job . objects . get ( repository__name = project , id = job_id ) BugJobMap . objects . filter ( job = job , bug_id = bug_id ) . delete ( ) return Response ( { "message" : "Bug job map deleted" } )
Delete bug - job - map entry . pk is a composite key in the form bug_id - job_id
16,715
def retrieve ( self , request , project , pk = None ) : job_id , bug_id = map ( int , pk . split ( "-" ) ) job = Job . objects . get ( repository__name = project , id = job_id ) try : bug_job_map = BugJobMap . objects . get ( job = job , bug_id = bug_id ) serializer = BugJobMapSerializer ( bug_job_map ) return Response...
Retrieve a bug - job - map entry . pk is a composite key in the form bug_id - job_id
16,716
def convert_unicode_character_to_ascii_repr ( match_obj ) : match = match_obj . group ( 0 ) code_point = ord ( match ) hex_repr = hex ( code_point ) hex_code_point = hex_repr [ 2 : ] hex_value = hex_code_point . zfill ( 6 ) . upper ( ) return '<U+{}>' . format ( hex_value )
Converts a matched pattern from a unicode character to an ASCII representation
16,717
def fetch_push_logs ( ) : for repo in Repository . objects . filter ( dvcs_type = 'hg' , active_status = "active" ) : fetch_hg_push_log . apply_async ( args = ( repo . name , repo . url ) , queue = 'pushlog' )
Run several fetch_hg_push_log subtasks one per repository
16,718
def fetch_hg_push_log ( repo_name , repo_url ) : newrelic . agent . add_custom_parameter ( "repo_name" , repo_name ) process = HgPushlogProcess ( ) process . run ( repo_url + '/json-pushes/?full=1&version=2' , repo_name )
Run a HgPushlog etl process
16,719
def store_pulse_jobs ( pulse_job , exchange , routing_key ) : newrelic . agent . add_custom_parameter ( "exchange" , exchange ) newrelic . agent . add_custom_parameter ( "routing_key" , routing_key ) JobLoader ( ) . process_job ( pulse_job )
Fetches the jobs pending from pulse exchanges and loads them .
16,720
def store_pulse_pushes ( body , exchange , routing_key ) : newrelic . agent . add_custom_parameter ( "exchange" , exchange ) newrelic . agent . add_custom_parameter ( "routing_key" , routing_key ) PushLoader ( ) . process ( body , exchange )
Fetches the pushes pending from pulse exchanges and loads them .
16,721
def store_failure_lines ( job_log ) : logger . debug ( 'Running store_failure_lines for job %s' , job_log . job . id ) failureline . store_failure_lines ( job_log )
Store the failure lines from a log corresponding to the structured errorsummary file .
16,722
def retrieve ( self , request , project , pk = None ) : try : serializer = JobNoteSerializer ( JobNote . objects . get ( id = pk ) ) return Response ( serializer . data ) except JobNote . DoesNotExist : return Response ( "No note with id: {0}" . format ( pk ) , status = HTTP_404_NOT_FOUND )
GET method implementation for a note detail
16,723
def create ( self , request , project ) : JobNote . objects . create ( job = Job . objects . get ( repository__name = project , id = int ( request . data [ 'job_id' ] ) ) , failure_classification_id = int ( request . data [ 'failure_classification_id' ] ) , user = request . user , text = request . data . get ( 'text' ,...
POST method implementation
16,724
def destroy ( self , request , project , pk = None ) : try : note = JobNote . objects . get ( id = pk ) note . delete ( ) return Response ( { "message" : "Note deleted" } ) except JobNote . DoesNotExist : return Response ( "No note with id: {0}" . format ( pk ) , status = HTTP_404_NOT_FOUND )
Delete a note entry
16,725
def extract_text_log_artifacts ( job_log ) : artifact_bc = ArtifactBuilderCollection ( job_log . url ) artifact_bc . parse ( ) artifact_list = [ ] for name , artifact in artifact_bc . artifacts . items ( ) : artifact_list . append ( { "job_guid" : job_log . job . guid , "name" : name , "type" : 'json' , "blob" : json ....
Generate a set of artifacts by parsing from the raw text log .
16,726
def post_log_artifacts ( job_log ) : logger . debug ( "Downloading/parsing log for log %s" , job_log . id ) try : artifact_list = extract_text_log_artifacts ( job_log ) except LogSizeException as e : job_log . update_status ( JobLog . SKIPPED_SIZE ) logger . warning ( 'Skipping parsing log for %s: %s' , job_log . id , ...
Post a list of artifacts to a job .
16,727
def get_error_summary ( job ) : cache_key = 'error-summary-{}' . format ( job . id ) cached_error_summary = cache . get ( cache_key ) if cached_error_summary is not None : return cached_error_summary errors = TextLogError . objects . filter ( step__job = job ) if not errors : return [ ] term_cache = { } error_summary =...
Create a list of bug suggestions for a job .
16,728
def get_error_search_term ( error_line ) : if not error_line : return None tokens = error_line . split ( " | " ) search_term = None if len ( tokens ) >= 3 : if len ( tokens ) > 3 and OUTPUT_RE . match ( tokens [ 0 ] ) : tokens = tokens [ 1 : ] test_name_or_path = tokens [ 1 ] message = tokens [ 2 ] match = LEAK_RE . se...
Generate a search term from the given error_line string .
16,729
def get_crash_signature ( error_line ) : search_term = None match = CRASH_RE . match ( error_line ) if match and is_helpful_search_term ( match . group ( 1 ) ) : search_term = match . group ( 1 ) return search_term
Try to get a crash signature from the given error_line string .
16,730
def is_helpful_search_term ( search_term ) : search_term = search_term . strip ( ) blacklist = [ 'automation.py' , 'remoteautomation.py' , 'Shutdown' , 'undefined' , 'Main app process exited normally' , 'Traceback (most recent call last):' , 'Return code: 0' , 'Return code: 1' , 'Return code: 2' , 'Return code: 9' , 'R...
Decide if the given search_term string is helpful or not .
16,731
def get_failures_fixed_by_commit ( ) : failures = defaultdict ( list ) option_collection_map = models . OptionCollection . objects . get_option_collection_map ( ) fixed_by_commit_data_set = models . JobNote . objects . filter ( failure_classification = 2 , created__gt = timezone . now ( ) - timedelta ( days = SETA_FIXE...
Return all job failures annotated with fixed by commit grouped by reason given for annotation .
16,732
def score_matches ( matches , score_multiplier = ( 1 , 1 ) ) : for match in matches : dividend , divisor = score_multiplier score = match . score * dividend / divisor yield ( score , match . classified_failure_id )
Get scores for the given matches .
16,733
def time_boxed ( func , iterable , time_budget , * args ) : time_budget = time_budget / 1000 start = time . time ( ) for thing in iterable : yield func ( thing , * args ) end = time . time ( ) - start if end > time_budget : return
Apply a function to the items of an iterable within a given time budget .
16,734
def job_priority_index ( job_priorities ) : jp_index = { } for jp in job_priorities : key = jp . unique_identifier ( ) if key in jp_index : msg = '"{}" should be a unique job priority and that is unexpected.' . format ( key ) raise DuplicateKeyError ( msg ) jp_index [ key ] = { 'pk' : jp . id , 'build_system_type' : jp...
This structure helps with finding data from the job priorities table
16,735
def transform ( self , pulse_job ) : job_guid = pulse_job [ "taskId" ] x = { "job" : { "job_guid" : job_guid , "name" : pulse_job [ "display" ] . get ( "jobName" , "unknown" ) , "job_symbol" : self . _get_job_symbol ( pulse_job ) , "group_name" : pulse_job [ "display" ] . get ( "groupName" , "unknown" ) , "group_symbol...
Transform a pulse job into a job that can be written to disk . Log References and artifacts will also be transformed and loaded with the job .
16,736
def retrieve ( self , request , project , pk = None ) : try : push = Push . objects . get ( repository__name = project , id = pk ) serializer = PushSerializer ( push ) return Response ( serializer . data ) except Push . DoesNotExist : return Response ( "No push with id: {0}" . format ( pk ) , status = HTTP_404_NOT_FOUN...
GET method implementation for detail view of push
16,737
def status ( self , request , project , pk = None ) : try : push = Push . objects . get ( id = pk ) except Push . DoesNotExist : return Response ( "No push with id: {0}" . format ( pk ) , status = HTTP_404_NOT_FOUND ) return Response ( push . get_status ( ) )
Return a count of the jobs belonging to this push grouped by job status .
16,738
def health ( self , request , project ) : revision = request . query_params . get ( 'revision' ) try : push = Push . objects . get ( revision = revision , repository__name = project ) except Push . DoesNotExist : return Response ( "No push with revision: {0}" . format ( revision ) , status = HTTP_404_NOT_FOUND ) push_h...
Return a calculated assessment of the health of this push .
16,739
def decisiontask ( self , request , project ) : push_ids = request . query_params . getlist ( 'push_ids' ) job_type = JobType . objects . get ( name = 'Gecko Decision Task' ) decision_jobs = Job . objects . filter ( push_id__in = push_ids , job_type = job_type ) . select_related ( 'taskcluster_metadata' ) if decision_j...
Return the decision task ids for the pushes .
16,740
def language_file_exists ( language_code ) : filename = '{0}.js' . format ( language_code ) path = os . path . join ( 'tinymce' , 'js' , 'tinymce' , 'langs' , filename ) return finders . find ( path ) is not None
Check if TinyMCE has a language file for the specified lang code
16,741
def get_language_config ( ) : language_code = convert_language_code ( get_language ( ) or settings . LANGUAGE_CODE ) if not language_file_exists ( language_code ) : language_code = language_code [ : 2 ] if not language_file_exists ( language_code ) : language_code = 'en' config = { 'language' : language_code } if get_l...
Creates a language configuration for TinyMCE4 based on Django project settings
16,742
def get_spellcheck_config ( ) : config = { } if mce_settings . USE_SPELLCHECKER : from enchant import list_languages enchant_languages = list_languages ( ) if settings . DEBUG : logger . info ( 'Enchant languages: {0}' . format ( enchant_languages ) ) lang_names = [ ] for lang , name in settings . LANGUAGES : lang = co...
Create TinyMCE spellchecker config based on Django settings
16,743
def convert_language_code ( django_lang ) : lang_and_country = django_lang . split ( '-' ) try : return '_' . join ( ( lang_and_country [ 0 ] , lang_and_country [ 1 ] . upper ( ) ) ) except IndexError : return lang_and_country [ 0 ]
Converts Django language codes ll - cc into ISO codes ll_CC or ll
16,744
def is_managed ( ) : for item in sys . argv : if re . search ( r'manage.py|django-admin|django' , item ) is not None : return True return False
Check if a Django project is being managed with manage . py or django - admin scripts
16,745
def spell_check ( request ) : data = json . loads ( request . body . decode ( 'utf-8' ) ) output = { 'id' : data [ 'id' ] } error = None status = 200 try : if data [ 'params' ] [ 'lang' ] not in list_languages ( ) : error = 'Missing {0} dictionary!' . format ( data [ 'params' ] [ 'lang' ] ) raise LookupError ( error ) ...
Implements the TinyMCE 4 spellchecker protocol
16,746
def css ( request ) : if 'grappelli' in settings . INSTALLED_APPS : margin_left = 0 elif VERSION [ : 2 ] <= ( 1 , 8 ) : margin_left = 110 else : margin_left = 170 responsive_admin = VERSION [ : 2 ] >= ( 2 , 0 ) return HttpResponse ( render_to_string ( 'tinymce/tinymce4.css' , context = { 'margin_left' : margin_left , '...
Custom CSS for TinyMCE 4 widget
16,747
def filebrowser ( request ) : try : fb_url = reverse ( 'fb_browse' ) except : fb_url = reverse ( 'filebrowser:fb_browse' ) return HttpResponse ( jsmin ( render_to_string ( 'tinymce/filebrowser.js' , context = { 'fb_url' : fb_url } , request = request ) ) , content_type = 'application/javascript; charset=utf-8' )
JavaScript callback function for django - filebrowser _
16,748
def check ( text ) : err = "glaad.offensive_terms" msg = "Offensive term. Remove it or consider the context." list = [ "fag" , "faggot" , "dyke" , "sodomite" , "homosexual agenda" , "gay agenda" , "transvestite" , "homosexual lifestyle" , "gay lifestyle" ] return existence_check ( text , list , err , msg , join = True ...
Flag offensive words based on the GLAAD reference guide .
16,749
def score ( check = None ) : tp = 0 fp = 0 parent_directory = os . path . dirname ( proselint_path ) path_to_corpus = os . path . join ( parent_directory , "corpora" , "0.1.0" ) for root , _ , files in os . walk ( path_to_corpus ) : files = [ f for f in files if f . endswith ( ".md" ) ] for f in files : fullpath = os ....
Compute the linter s score on the corpus .
16,750
def is_broken_link ( url ) : try : request = urllib_request . Request ( url , headers = { 'User-Agent' : 'Mozilla/5.0' } ) urllib_request . urlopen ( request ) . read ( ) return False except urllib_request . URLError : return True except SocketError : return True
Determine whether the link returns a 404 error .
16,751
def check ( text ) : err = "misc.suddenly" msg = u"Suddenly is nondescript, slows the action, and warns your reader." regex = "Suddenly," return existence_check ( text , [ regex ] , err , msg , max_errors = 3 , require_padding = False , offset = - 1 , ignore_case = False )
Advice on sudden vs suddenly .
16,752
def check ( text ) : err = "weasel_words.very" msg = ( "Substitute 'damn' every time you're " "inclined to write 'very'; your editor will delete it " "and the writing will be just as it should be." ) regex = "very" return existence_check ( text , [ regex ] , err , msg , max_errors = 1 )
Avoid very .
16,753
def check_p_equals_zero ( text ) : err = "psychology.p_equals_zero" msg = "Unless p really equals zero, you should use more decimal places." list = [ "p = 0.00" , "p = 0.000" , "p = 0.0000" , ] return existence_check ( text , list , err , msg , join = True )
Check for p = 0 . 000 .
16,754
def rate ( ) : auth = request . authorization if not auth or not check_auth ( auth . username , auth . password ) : return "60/minute" else : return "600/minute"
Set rate limits for authenticated and nonauthenticated users .
16,755
def lint ( ) : if 'text' in request . values : text = unquote ( request . values [ 'text' ] ) job = q . enqueue ( worker_function , text ) return jsonify ( job_id = job . id ) , 202 elif 'job_id' in request . values : job = q . fetch_job ( request . values [ 'job_id' ] ) if not job : return jsonify ( status = "error" ,...
Run linter on the provided text and return the results .
16,756
def check_without_your_collusion ( text ) : err = "misc.illogic.collusion" msg = "It's impossible to defraud yourself. Try 'aquiescence'." regex = "without your collusion" return existence_check ( text , [ regex ] , err , msg , require_padding = False , offset = - 1 )
Check the textself .
16,757
def check_exclamations_ppm ( text ) : err = "leonard.exclamation.30ppm" msg = u"More than 30 ppm of exclamations. Keep them under control." regex = r"\w!" count = len ( re . findall ( regex , text ) ) num_words = len ( text . split ( " " ) ) ppm = ( count * 1.0 / num_words ) * 1e6 if ppm > 30 and count > 1 : loc = re ....
Make sure that the exclamation ppm is under 30 .
16,758
def check ( text ) : err = "glaad.terms" msg = "Possibly offensive term. Consider using '{}' instead of '{}'." list = [ [ "gay man" , [ "homosexual man" ] ] , [ "gay men" , [ "homosexual men" ] ] , [ "lesbian" , [ "homosexual woman" ] ] , [ "lesbians" , [ "homosexual women" ] ] , [ "gay people" , [ "homosexual people" ...
Suggest preferred forms given the reference document .
16,759
def _delete_compiled_python_files ( ) : for path , _ , files in os . walk ( os . getcwd ( ) ) : for fname in [ f for f in files if os . path . splitext ( f ) [ 1 ] == ".pyc" ] : try : os . remove ( os . path . join ( path , fname ) ) except OSError : pass
Remove files with a pyc extension .
16,760
def print_errors ( filename , errors , output_json = False , compact = False ) : if output_json : click . echo ( errors_to_json ( errors ) ) else : for error in errors : ( check , message , line , column , start , end , extent , severity , replacements ) = error if compact : filename = "-" click . echo ( filename + ":"...
Print the errors resulting from lint for filename .
16,761
def proselint ( paths = None , version = None , clean = None , debug = None , output_json = None , time = None , demo = None , compact = None ) : if time : click . echo ( timing_test ( ) ) return if debug or clean : clear_cache ( ) if demo : paths = [ demo_file ] filepaths = extract_files ( list ( paths ) ) num_errors ...
A CLI for proselint a linter for prose .
16,762
def extract_files ( files ) : expanded_files = [ ] legal_extensions = [ ".md" , ".txt" , ".rtf" , ".html" , ".tex" , ".markdown" ] for f in files : if os . path . isdir ( f ) : for dir_ , _ , filenames in os . walk ( f ) : for filename in filenames : fn , file_extension = os . path . splitext ( filename ) if file_exten...
Expand list of paths to include all text files matching the pattern .
16,763
def check_vtech ( text ) : err = "institution.vtech" msg = "Incorrect name. Use '{}' instead of '{}'." institution = [ [ "Virginia Polytechnic Institute and State University" , [ "Virginia Polytechnic and State University" ] ] , ] return preferred_forms_check ( text , institution , err , msg )
Suggest the correct name .
16,764
def check_decade_apostrophes_short ( text ) : err = "dates_times.dates" msg = u"Apostrophes aren't needed for decades." regex = "\d0\'s" return existence_check ( text , [ regex ] , err , msg , excluded_topics = [ "50 Cent" ] )
Check the text for dates of the form X0 s .
16,765
def check_decade_apostrophes_long ( text ) : err = "dates_times.dates" msg = u"Apostrophes aren't needed for decades." regex = "\d\d\d0\'s" return existence_check ( text , [ regex ] , err , msg )
Check the text for dates of the form XXX0 s .
16,766
def close_cache_shelves_after ( f ) : @ functools . wraps ( f ) def wrapped ( * args , ** kwargs ) : f ( * args , ** kwargs ) close_cache_shelves ( ) return wrapped
Decorator that ensures cache shelves are closed after the call .
16,767
def memoize ( f ) : cache_dirname = os . path . join ( _get_xdg_cache_home ( ) , 'proselint' ) legacy_cache_dirname = os . path . join ( os . path . expanduser ( "~" ) , ".proselint" ) if not os . path . isdir ( cache_dirname ) : if os . path . isdir ( legacy_cache_dirname ) : os . rename ( legacy_cache_dirname , cache...
Cache results of computations on disk .
16,768
def get_checks ( options ) : sys . path . append ( proselint_path ) checks = [ ] check_names = [ key for ( key , val ) in list ( options [ "checks" ] . items ( ) ) if val ] for check_name in check_names : module = importlib . import_module ( "checks." + check_name ) for d in dir ( module ) : if re . match ( "check" , d...
Extract the checks .
16,769
def load_options ( ) : possible_defaults = ( '/etc/proselintrc' , os . path . join ( proselint_path , '.proselintrc' ) , ) options = { } has_overrides = False for filename in possible_defaults : try : options = json . load ( open ( filename ) ) break except IOError : pass try : user_options = json . load ( open ( os . ...
Read various proselintrc files allowing user overrides .
16,770
def errors_to_json ( errors ) : out = [ ] for e in errors : out . append ( { "check" : e [ 0 ] , "message" : e [ 1 ] , "line" : 1 + e [ 2 ] , "column" : 1 + e [ 3 ] , "start" : 1 + e [ 4 ] , "end" : 1 + e [ 5 ] , "extent" : e [ 6 ] , "severity" : e [ 7 ] , "replacements" : e [ 8 ] , } ) return json . dumps ( dict ( sta...
Convert the errors to JSON .
16,771
def line_and_column ( text , position ) : position_counter = 0 for idx_line , line in enumerate ( text . splitlines ( True ) ) : if ( position_counter + len ( line . rstrip ( ) ) ) >= position : return ( idx_line , position - position_counter ) else : position_counter += len ( line )
Return the line number and column of a position in a string .
16,772
def lint ( input_file , debug = False ) : options = load_options ( ) if isinstance ( input_file , string_types ) : text = input_file else : text = input_file . read ( ) checks = get_checks ( options ) errors = [ ] for check in checks : result = check ( text ) for error in result : ( start , end , check , message , repl...
Run the linter on the input file .
16,773
def assert_error ( text , check , n = 1 ) : assert_error . description = "No {} error for '{}'" . format ( check , text ) assert ( check in [ error [ 0 ] for error in lint ( text ) ] )
Assert that text has n errors of type check .
16,774
def consistency_check ( text , word_pairs , err , msg , offset = 0 ) : errors = [ ] msg = " " . join ( msg . split ( ) ) for w in word_pairs : matches = [ [ m for m in re . finditer ( w [ 0 ] , text ) ] , [ m for m in re . finditer ( w [ 1 ] , text ) ] ] if len ( matches [ 0 ] ) > 0 and len ( matches [ 1 ] ) > 0 : idx_...
Build a consistency checker for the given word_pairs .
16,775
def preferred_forms_check ( text , list , err , msg , ignore_case = True , offset = 0 , max_errors = float ( "inf" ) ) : if ignore_case : flags = re . IGNORECASE else : flags = 0 msg = " " . join ( msg . split ( ) ) errors = [ ] regex = u"[\W^]{}[\W$]" for p in list : for r in p [ 1 ] : for m in re . finditer ( regex ....
Build a checker that suggests the preferred form .
16,776
def existence_check ( text , list , err , msg , ignore_case = True , str = False , max_errors = float ( "inf" ) , offset = 0 , require_padding = True , dotall = False , excluded_topics = None , join = False ) : flags = 0 msg = " " . join ( msg . split ( ) ) if ignore_case : flags = flags | re . IGNORECASE if str : flag...
Build a checker that blacklists certain words .
16,777
def truncate_to_max ( errors , max_errors ) : if len ( errors ) > max_errors : start1 , end1 , err1 , msg1 , replacements = errors [ 0 ] if len ( errors ) == ( max_errors + 1 ) : msg1 += " Found once elsewhere." else : msg1 += " Found {} times elsewhere." . format ( len ( errors ) ) errors = errors [ 1 : max_errors ] e...
If max_errors was specified truncate the list of errors .
16,778
def detector_50_Cent ( text ) : keywords = [ "50 Cent" , "rap" , "hip hop" , "Curtis James Jackson III" , "Curtis Jackson" , "Eminem" , "Dre" , "Get Rich or Die Tryin'" , "G-Unit" , "Street King Immortal" , "In da Club" , "Interscope" , ] num_keywords = sum ( word in text for word in keywords ) return ( "50 Cent" , flo...
Determine whether 50 Cent is a topic .
16,779
def topics ( text ) : detectors = [ detector_50_Cent ] ts = [ ] for detector in detectors : ts . append ( detector ( text ) ) return [ t [ 0 ] for t in ts if t [ 1 ] > 0.95 ]
Return a list of topics .
16,780
def check_ellipsis ( text ) : err = "typography.symbols.ellipsis" msg = u"'...' is an approximation, use the ellipsis symbol '…'." regex = "\.\.\." return existence_check ( text , [ regex ] , err , msg , max_errors = 3 , require_padding = False , offset = 0 )
Use an ellipsis instead of three dots .
16,781
def check_sentence_spacing ( text ) : err = "typography.symbols.sentence_spacing" msg = u"More than two spaces after the period; use 1 or 2." regex = "\. {3}" return existence_check ( text , [ regex ] , err , msg , max_errors = 3 , require_padding = False )
Use no more than two spaces after a period .
16,782
def check_email ( ) : server = smtplib . SMTP ( "smtp.gmail.com" , 587 ) server . ehlo ( ) server . starttls ( ) server . ehlo ( ) server . login ( user , password ) g = gmail . login ( user , password ) unread = g . inbox ( ) . mail ( unread = True ) for u in unread : u . fetch ( ) signature = ( u . fr . decode ( 'utf...
Check the mail account and lint new mail .
16,783
def check_bottleneck ( text ) : err = "mixed_metaphors.misc.bottleneck" msg = u"Mixed metaphor — bottles with big necks are easy to pass through." list = [ "biggest bottleneck" , "big bottleneck" , "large bottleneck" , "largest bottleneck" , "world-wide bottleneck" , "huge bottleneck" , "massive bottleneck" , ] return ...
Avoid mixing metaphors about bottles and their necks .
16,784
def check_misc ( text ) : err = "mixed_metaphors.misc.misc" msg = u"Mixed metaphor. Try '{}'." preferences = [ [ "cream rises to the top" , [ "cream rises to the crop" ] ] , [ "fasten your seatbelts" , [ "button your seatbelts" ] ] , [ "a minute to decompress" , [ "a minute to decompose" ] ] , [ "sharpest tool in the s...
Avoid mixing metaphors .
16,785
def checkout ( self , revision , options ) : rev = revision . key self . repo . git . checkout ( rev )
Checkout a specific revision .
16,786
def generate_cache_path ( path ) : logger . debug ( f"Generating cache for {path}" ) sha = hashlib . sha1 ( str ( path ) . encode ( ) ) . hexdigest ( ) [ : 9 ] HOME = pathlib . Path . home ( ) cache_path = str ( HOME / ".wily" / sha ) logger . debug ( f"Cache path is {cache_path}" ) return cache_path
Generate a reusable path to cache results .
16,787
def load ( config_path = DEFAULT_CONFIG_PATH ) : if not pathlib . Path ( config_path ) . exists ( ) : logger . debug ( f"Could not locate {config_path}, using default config." ) return DEFAULT_CONFIG config = configparser . ConfigParser ( default_section = DEFAULT_CONFIG_SECTION ) config . read ( config_path ) operator...
Load config file and set values to defaults where no present .
16,788
def cli ( ctx , debug , config , path , cache ) : ctx . ensure_object ( dict ) ctx . obj [ "DEBUG" ] = debug if debug : logger . setLevel ( "DEBUG" ) else : logger . setLevel ( "INFO" ) ctx . obj [ "CONFIG" ] = load_config ( config ) if path : logger . debug ( f"Fixing path to {path}" ) ctx . obj [ "CONFIG" ] . path = ...
\ U0001F98A Inspect and search through the complexity of your source code .
16,789
def build ( ctx , max_revisions , targets , operators , archiver ) : config = ctx . obj [ "CONFIG" ] from wily . commands . build import build if max_revisions : logger . debug ( f"Fixing revisions to {max_revisions}" ) config . max_revisions = max_revisions if operators : logger . debug ( f"Fixing operators to {operat...
Build the wily cache .
16,790
def report ( ctx , file , metrics , number , message , format , console_format , output ) : config = ctx . obj [ "CONFIG" ] if not exists ( config ) : handle_no_cache ( ctx ) if not metrics : metrics = get_default_metrics ( config ) logger . info ( f"Using default metrics {metrics}" ) new_output = Path ( ) . cwd ( ) if...
Show metrics for a given file .
16,791
def diff ( ctx , files , metrics , all , detail ) : config = ctx . obj [ "CONFIG" ] if not exists ( config ) : handle_no_cache ( ctx ) if not metrics : metrics = get_default_metrics ( config ) logger . info ( f"Using default metrics {metrics}" ) else : metrics = metrics . split ( "," ) logger . info ( f"Using specified...
Show the differences in metrics for each file .
16,792
def graph ( ctx , path , metrics , output , x_axis , changes ) : config = ctx . obj [ "CONFIG" ] if not exists ( config ) : handle_no_cache ( ctx ) from wily . commands . graph import graph logger . debug ( f"Running report on {path} for metrics {metrics}" ) graph ( config = config , path = path , metrics = metrics , o...
Graph a specific metric for a given file if a path is given all files within path will be graphed .
16,793
def list_metrics ( ctx ) : config = ctx . obj [ "CONFIG" ] if not exists ( config ) : handle_no_cache ( ctx ) from wily . commands . list_metrics import list_metrics list_metrics ( )
List the available metrics .
16,794
def handle_no_cache ( context ) : logger . error ( f"Could not locate wily cache, the cache is required to provide insights." ) p = input ( "Do you want to run setup and index your project now? [y/N]" ) if p . lower ( ) != "y" : exit ( 1 ) else : revisions = input ( "How many previous git revisions do you want to index...
Handle lack - of - cache error prompt user for index process .
16,795
def metric_parts ( metric ) : operator , met = resolve_metric_as_tuple ( metric ) return operator . name , met . name
Convert a metric name into the operator and metric names .
16,796
def graph ( config , path , metrics , output = None , x_axis = None , changes = True , text = False ) : logger . debug ( "Running report command" ) data = [ ] state = State ( config ) abs_path = config . path / pathlib . Path ( path ) if x_axis is None : x_axis = "history" else : x_operator , x_key = metric_parts ( x_a...
Graph information about the cache and runtime .
16,797
def list_metrics ( ) : for name , operator in ALL_OPERATORS . items ( ) : print ( f"{name} operator:" ) if len ( operator . cls . metrics ) > 0 : print ( tabulate . tabulate ( headers = ( "Name" , "Description" , "Type" ) , tabular_data = operator . cls . metrics , tablefmt = DEFAULT_GRID_STYLE , ) )
List metrics available .
16,798
def run_operator ( operator , revision , config ) : instance = operator . cls ( config ) logger . debug ( f"Running {operator.name} operator on {revision.key}" ) return operator . name , instance . run ( revision , config )
Run an operator for the multiprocessing pool . Not called directly .
16,799
def build ( config , archiver , operators ) : try : logger . debug ( f"Using {archiver.name} archiver module" ) archiver = archiver . cls ( config ) revisions = archiver . revisions ( config . path , config . max_revisions ) except InvalidGitRepositoryError : logger . info ( f"Defaulting back to the filesystem archiver...
Build the history given a archiver and collection of operators .