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 classified' ) . id self . job . save ( ) | 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 . filter ( error_matches__text_log_error = text_log_error ) . values_list ( 'bug_number' , flat = True ) ) new_bugs = ( self . job . bugjobmap_set . exclude ( bug_id__in = existing_bugs ) . values_list ( 'bug_id' , flat = True ) ) if not new_bugs : return for bug_number in new_bugs : classification , _ = ClassifiedFailure . objects . get_or_create ( bug_number = bug_number ) text_log_error . create_match ( "ManualDetector" , classification ) if len ( new_bugs ) == 1 and not existing_bugs : text_log_error . verify_classification ( classification ) | 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 ) ) existing_maps = set ( BugJobMap . objects . filter ( bug_id__in = bug_numbers ) . values_list ( 'bug_id' ) ) for bug_number in ( bug_numbers - existing_maps ) : BugJobMap . objects . create ( job_id = job . id , bug_id = bug_number , user = user ) classification_name = 'intermittent' if user else 'autoclassified intermittent' classification = FailureClassification . objects . get ( name = classification_name ) return JobNote . objects . create ( job = job , failure_classification = classification , user = user , text = "" ) | 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 ( component in item [ "search" ] for component in components ) : for suggestion in itertools . chain ( item [ "bugs" ] [ "open_recent" ] , item [ "bugs" ] [ "all_others" ] ) : if suggestion [ "id" ] not in ids_seen : ids_seen . add ( suggestion [ "id" ] ) rv . append ( suggestion ) return rv | 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 , "stackwalk_stdout" : self . stackwalk_stdout , "stackwalk_stderr" : self . stackwalk_stderr , } data = { k : v for k , v in data . items ( ) if v } return data | 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_failure' ] ) continue other_matches . filter ( score__lt = match . score ) . update ( score = match . score ) yield match . id | 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_verified = True ) else : self . metadata . best_classification = classification self . metadata . best_is_verified = True self . metadata . save ( update_fields = [ 'best_classification' , 'best_is_verified' ] ) self . metadata . failure_line . elastic_search_insert ( ) match = self . matches . filter ( classified_failure = classification ) . first ( ) if not match : return newrelic . agent . record_custom_event ( 'user_verified_classification' , { 'matcher' : match . matcher_name , 'job_id' : self . id , } ) | 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 Response ( { "failure" : "Crash signature can't be more than 2048 characters." } , status = HTTP_400_BAD_REQUEST ) description = u"**Filed by:** {}\n{}" . format ( request . user . email . replace ( '@' , " [at] " ) , params . get ( "comment" , "" ) ) . encode ( "utf-8" ) summary = params . get ( "summary" ) . encode ( "utf-8" ) . strip ( ) url = settings . BUGFILER_API_URL + "/rest/bug" headers = { 'x-bugzilla-api-key' : settings . BUGFILER_API_KEY , 'Accept' : 'application/json' } data = { 'product' : params . get ( "product" ) , 'component' : params . get ( "component" ) , 'summary' : summary , 'keywords' : params . get ( "keywords" ) , 'blocks' : params . get ( "blocks" ) , 'depends_on' : params . get ( "depends_on" ) , 'see_also' : params . get ( "see_also" ) , 'version' : params . get ( "version" ) , 'cf_crash_signature' : params . get ( "crash_signature" ) , 'severity' : params . get ( "severity" ) , 'priority' : params . get ( "priority" ) , 'description' : description , 'comment_tags' : "treeherder" , } try : response = make_request ( url , method = 'POST' , headers = headers , json = data ) except requests . exceptions . HTTPError as e : try : message = e . response . json ( ) [ 'message' ] except ( ValueError , KeyError ) : message = e . response . text return Response ( { "failure" : message } , status = HTTP_400_BAD_REQUEST ) return Response ( { "success" : response . json ( ) [ "id" ] } ) | 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 ] . id | 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 already exists" return Response ( { "message" : message } ) | 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 ( serializer . data ) except BugJobMap . DoesNotExist : return Response ( "Object not found" , status = HTTP_404_NOT_FOUND ) | 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' , '' ) ) return Response ( { 'message' : 'note stored for job {0}' . format ( request . data [ 'job_id' ] ) } ) | 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 . dumps ( artifact ) } ) return artifact_list | 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 , e ) return except Exception as e : job_log . update_status ( JobLog . FAILED ) if isinstance ( e , HTTPError ) and e . response . status_code in ( 403 , 404 ) : logger . warning ( "Unable to retrieve log for %s: %s" , job_log . id , e ) return logger . error ( "Failed to download/parse log for %s: %s" , job_log . id , e ) raise try : serialized_artifacts = serialize_artifact_json_blobs ( artifact_list ) store_job_artifacts ( serialized_artifacts ) job_log . update_status ( JobLog . PARSED ) logger . debug ( "Stored artifact for %s %s" , job_log . job . repository . name , job_log . job . id ) except Exception as e : logger . error ( "Failed to store parsed artifact for %s: %s" , job_log . id , e ) raise | 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 = [ bug_suggestions_line ( err , term_cache ) for err in errors ] cache . set ( cache_key , error_summary , BUG_SUGGESTION_CACHE_TIMEOUT ) return 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 . search ( message ) if match : search_term = match . group ( 1 ) if match . group ( 1 ) is not None else match . group ( 2 ) else : test_name_or_path = REFTEST_RE . sub ( "" , test_name_or_path ) for splitter in ( "/" , "\\" ) : test_name_or_path = test_name_or_path . split ( splitter ) [ - 1 ] search_term = test_name_or_path if not ( search_term and is_helpful_search_term ( search_term ) ) : if is_helpful_search_term ( error_line ) : search_term = error_line else : search_term = None if search_term : search_term = search_term [ : 100 ] return search_term | 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' , 'Return code: 10' , 'mozalloc_abort(char const*)' , 'mozalloc_abort' , 'Exiting 1' , 'Exiting 9' , 'CrashingThread(void *)' , 'libSystem.B.dylib + 0xd7a' , 'linux-gate.so + 0x424' , 'TypeError: content is null' , 'leakcheck' , 'ImportError: No module named pygtk' , '# TBPL FAILURE #' ] return len ( search_term ) > 4 and search_term not in blacklist | 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_FIXED_BY_COMMIT_DAYS ) , text__isnull = False , job__repository__name__in = SETA_FIXED_BY_COMMIT_REPOS ) . exclude ( job__signature__build_platform__in = SETA_UNSUPPORTED_PLATFORMS ) . exclude ( text = "" ) . select_related ( 'job' , 'job__signature' , 'job__job_type' ) if not fixed_by_commit_data_set . exists ( ) : logger . warning ( "We couldn't find any fixed-by-commit jobs" ) return failures for job_note in fixed_by_commit_data_set . iterator ( ) : revision_id = job_note . text . strip ( '/' ) revision_id = revision_id . split ( '/' ) [ - 1 ] if not revision_id or len ( revision_id ) < 12 : continue try : if job_note . job . signature . build_system_type != 'buildbot' : if not job_note . job . job_type . name . startswith ( tuple ( SETA_SUPPORTED_TC_JOBTYPES ) ) : continue testtype = parse_testtype ( build_system_type = job_note . job . signature . build_system_type , job_type_name = job_note . job . job_type . name , platform_option = job_note . job . get_platform_option ( option_collection_map ) , ref_data_name = job_note . job . signature . name , ) if testtype : if is_job_blacklisted ( testtype ) : continue else : logger . warning ( 'We were unable to parse %s/%s' , job_note . job . job_type . name , job_note . job . signature . name ) continue failures [ revision_id ] . append ( unique_key ( testtype = testtype , buildtype = job_note . job . get_platform_option ( option_collection_map ) , platform = job_note . job . signature . build_platform ) ) except models . Job . DoesNotExist : logger . warning ( 'job_note %s has no job associated to it' , job_note . id ) continue logger . warning ( "Number of fixed_by_commit revisions: %s" , len ( failures ) ) return failures | 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 . buildsystem } return jp_index | 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" : pulse_job [ "display" ] . get ( "groupSymbol" ) , "product_name" : pulse_job . get ( "productName" , "unknown" ) , "state" : pulse_job [ "state" ] , "result" : self . _get_result ( pulse_job ) , "reason" : pulse_job . get ( "reason" , "unknown" ) , "who" : pulse_job . get ( "owner" , "unknown" ) , "build_system_type" : pulse_job [ "buildSystem" ] , "tier" : pulse_job . get ( "tier" , 1 ) , "machine" : self . _get_machine ( pulse_job ) , "option_collection" : self . _get_option_collection ( pulse_job ) , "log_references" : self . _get_log_references ( pulse_job ) , "artifacts" : self . _get_artifacts ( pulse_job , job_guid ) , } , "superseded" : pulse_job . get ( "coalesced" , [ ] ) , "revision" : pulse_job [ "origin" ] [ "revision" ] } for k , v in self . TIME_FIELD_MAP . items ( ) : if v in pulse_job : x [ "job" ] [ k ] = to_timestamp ( pulse_job [ v ] ) default_platform = pulse_job . get ( "buildMachine" , pulse_job . get ( "runMachine" , { } ) ) for k , v in self . PLATFORM_FIELD_MAP . items ( ) : platform_src = pulse_job [ v ] if v in pulse_job else default_platform x [ "job" ] [ k ] = self . _get_platform ( platform_src ) try : ( decoded_task_id , retry_id ) = job_guid . split ( '/' ) real_task_id = slugid . encode ( uuid . UUID ( decoded_task_id ) ) x [ "job" ] . update ( { "taskcluster_task_id" : real_task_id , "taskcluster_retry_id" : int ( retry_id ) } ) except Exception : pass return x | 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_FOUND ) | 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_health_test_failures = get_push_health_test_failures ( push , REPO_GROUPS [ 'trunk' ] ) test_result = 'fail' if len ( push_health_test_failures [ 'needInvestigation' ] ) else 'pass' return Response ( { 'revision' : revision , 'id' : push . id , 'result' : test_result , 'metrics' : [ { 'name' : 'Tests' , 'result' : test_result , 'failures' : push_health_test_failures , } , { 'name' : 'Builds (Not yet implemented)' , 'result' : 'pass' , 'details' : [ 'Wow, everything passed!' ] , } , { 'name' : 'Linting (Not yet implemented)' , 'result' : 'pass' , 'details' : [ 'Gosh, this code is really nicely formatted.' ] , } , { 'name' : 'Coverage (Not yet implemented)' , 'result' : 'pass' , 'details' : [ 'Covered 42% of the tests that are needed for feature ``foo``.' , 'Covered 100% of the tests that are needed for feature ``bar``.' , 'The ratio of people to cake is too many...' , ] , } , { 'name' : 'Performance (Not yet implemented)' , 'result' : 'pass' , 'details' : [ 'Ludicrous Speed' ] , } , ] , } ) | 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_jobs : return Response ( { job . push_id : job . taskcluster_metadata . task_id for job in decision_jobs } ) else : return Response ( "No decision tasks found for pushes: {}" . format ( push_ids ) , status = HTTP_404_NOT_FOUND ) | 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_language_bidi ( ) : config [ 'directionality' ] = 'rtl' else : config [ 'directionality' ] = 'ltr' return config | 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 = convert_language_code ( lang ) if lang not in enchant_languages : lang = lang [ : 2 ] if lang not in enchant_languages : logger . warning ( 'Missing {0} spellchecker dictionary!' . format ( lang ) ) continue if config . get ( 'spellchecker_language' ) is None : config [ 'spellchecker_language' ] = lang lang_names . append ( '{0}={1}' . format ( name , lang ) ) config [ 'spellchecker_languages' ] = ',' . join ( lang_names ) return config | 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 ) spell_checker = checker . SpellChecker ( data [ 'params' ] [ 'lang' ] ) spell_checker . set_text ( strip_tags ( data [ 'params' ] [ 'text' ] ) ) output [ 'result' ] = { spell_checker . word : spell_checker . suggest ( ) for err in spell_checker } except NameError : error = 'The pyenchant package is not installed!' logger . exception ( error ) except LookupError : logger . exception ( error ) except Exception : error = 'Unknown error!' logger . exception ( error ) if error is not None : output [ 'error' ] = error status = 500 return JsonResponse ( output , status = status ) | 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 , 'responsive_admin' : responsive_admin } , request = request ) , content_type = 'text/css; charset=utf-8' ) | 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 , ignore_case = False ) | 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 . path . join ( root , f ) print ( "Linting {}" . format ( f ) ) out = subprocess . check_output ( [ "proselint" , fullpath ] ) regex = r".+?:(?P<line>\d+):(?P<col>\d+): (?P<message>.+)" num_errors = len ( tuple ( re . finditer ( regex , out ) ) ) print ( "Found {} errors." . format ( num_errors ) ) subprocess . call ( [ "open" , fullpath ] ) input_val = None while not isinstance ( input_val , int ) : try : input_val = input ( "# of false alarms? " ) if input_val == "exit" : return else : input_val = int ( input_val ) fp += input_val tp += ( num_errors - input_val ) except ValueError : pass print ( "Currently {} hits and {} false alarms\n---" . format ( tp , fp ) ) if ( tp + fp ) > 0 : return tp * ( 1.0 * tp / ( tp + fp ) ) ** 2 else : return 0 | 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" , message = "No job with requested job_id." ) , 404 elif job . result is None : return jsonify ( status = "error" , message = "Job is not yet ready." ) , 202 else : errors = [ ] for i , e in enumerate ( job . result ) : app . logger . debug ( e ) errors . append ( { "check" : e [ 0 ] , "message" : e [ 1 ] , "line" : e [ 2 ] , "column" : e [ 3 ] , "start" : e [ 4 ] , "end" : e [ 5 ] , "extent" : e [ 5 ] - e [ 4 ] , "severity" : e [ 7 ] , "replacements" : e [ 8 ] , "source_name" : "" , "source_url" : "" , } ) return jsonify ( status = "success" , data = { "errors" : errors } ) | 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 . search ( regex , text ) . start ( ) + 1 return [ ( loc , loc + 1 , err , msg , "." ) ] else : return [ ] | 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" ] ] , [ "gay couple" , [ "homosexual couple" ] ] , [ "sexual orientation" , [ "sexual preference" ] ] , [ "openly gay" , [ "admitted homosexual" , "avowed homosexual" ] ] , [ "equal rights" , [ "special rights" ] ] ] return preferred_forms_check ( text , list , err , msg , ignore_case = False ) | 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 + ":" + str ( 1 + line ) + ":" + str ( 1 + column ) + ": " + check + " " + message ) | 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 = 0 if len ( paths ) == 0 : filepaths . append ( '-' ) for fp in filepaths : try : if fp == '-' : fp = '<stdin>' f = sys . stdin else : f = click . open_file ( fp , 'r' , encoding = "utf-8" , errors = "replace" ) errors = lint ( f , debug = debug ) num_errors += len ( errors ) print_errors ( fp , errors , output_json , compact = compact ) except Exception : traceback . print_exc ( ) close_cache_shelves ( ) if num_errors > 0 : sys . exit ( 1 ) else : sys . exit ( 0 ) | 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_extension in legal_extensions : joined_file = os . path . join ( dir_ , filename ) expanded_files . append ( joined_file ) else : expanded_files . append ( f ) return expanded_files | 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_dirname ) else : os . makedirs ( cache_dirname ) cache_filename = f . __module__ + "." + f . __name__ cachepath = os . path . join ( cache_dirname , cache_filename ) @ functools . wraps ( f ) def wrapped ( * args , ** kwargs ) : if hasattr ( f , '__self__' ) : args = args [ 1 : ] signature = ( f . __module__ + '.' + f . __name__ ) . encode ( "utf-8" ) tempargdict = inspect . getcallargs ( f , * args , ** kwargs ) for item in list ( tempargdict . items ( ) ) : signature += item [ 1 ] . encode ( "utf-8" ) key = hashlib . sha256 ( signature ) . hexdigest ( ) try : cache = _get_cache ( cachepath ) return cache [ key ] except KeyError : value = f ( * args , ** kwargs ) cache [ key ] = value cache . sync ( ) return value except TypeError : call_to = f . __module__ + '.' + f . __name__ print ( 'Warning: could not disk cache call to %s;' 'it probably has unhashable args. Error: %s' % ( call_to , traceback . format_exc ( ) ) ) return f ( * args , ** kwargs ) return wrapped | 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 ) : checks . append ( getattr ( module , d ) ) return checks | 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 . path . join ( _get_xdg_config_home ( ) , 'proselint' , 'config' ) ) ) has_overrides = True except IOError : pass if not has_overrides : try : user_options = json . load ( open ( os . path . join ( os . path . expanduser ( '~' ) , '.proselintrc' ) ) ) has_overrides = True except IOError : pass if has_overrides : if 'max_errors' in user_options : options [ 'max_errors' ] = user_options [ 'max_errors' ] if 'checks' in user_options : for ( key , value ) in user_options [ 'checks' ] . items ( ) : try : options [ 'checks' ] [ key ] = value except KeyError : pass return options | 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 ( status = "success" , data = { "errors" : out } ) , sort_keys = True ) | 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 , replacements ) = error ( line , column ) = line_and_column ( text , start ) if not is_quoted ( start , text ) : errors += [ ( check , message , line , column , start , end , end - start , "warning" , replacements ) ] if len ( errors ) > options [ "max_errors" ] : break errors = sorted ( errors [ : options [ "max_errors" ] ] , key = lambda e : ( e [ 2 ] , e [ 3 ] ) ) return errors | 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_minority = len ( matches [ 0 ] ) > len ( matches [ 1 ] ) for m in matches [ idx_minority ] : errors . append ( ( m . start ( ) + offset , m . end ( ) + offset , err , msg . format ( w [ ~ idx_minority ] , m . group ( 0 ) ) , w [ ~ idx_minority ] ) ) return errors | 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 . format ( r ) , text , flags = flags ) : txt = m . group ( 0 ) . strip ( ) errors . append ( ( m . start ( ) + 1 + offset , m . end ( ) + offset , err , msg . format ( p [ 0 ] , txt ) , p [ 0 ] ) ) errors = truncate_to_max ( errors , max_errors ) return errors | 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 : flags = flags | re . UNICODE if dotall : flags = flags | re . DOTALL if require_padding : regex = u"(?:^|\W){}[\W$]" else : regex = u"{}" errors = [ ] if excluded_topics : tps = topics ( text ) if any ( [ t in excluded_topics for t in tps ] ) : return errors rx = "|" . join ( regex . format ( w ) for w in list ) for m in re . finditer ( rx , text , flags = flags ) : txt = m . group ( 0 ) . strip ( ) errors . append ( ( m . start ( ) + 1 + offset , m . end ( ) + offset , err , msg . format ( txt ) , None ) ) errors = truncate_to_max ( errors , max_errors ) return errors | 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 ] errors = [ ( start1 , end1 , err1 , msg1 , replacements ) ] + errors return errors | 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" , float ( num_keywords > 2 ) ) | 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-8' ) + u . subject . decode ( 'utf-8' ) + u . body . decode ( 'utf-8' ) ) hash = hashlib . sha256 ( signature . encode ( 'utf-8' ) ) . hexdigest ( ) if user_to in u . to or user_to in u . headers . get ( 'Cc' , [ ] ) : job_id = conn . get ( hash ) if not job_id : r = requests . post ( api_url , data = { "text" : u . body } ) conn . set ( hash , r . json ( ) [ "job_id" ] ) print ( "Email {} sent for processing." . format ( hash ) ) else : r = requests . get ( api_url , params = { "job_id" : job_id } ) if r . json ( ) [ "status" ] == "success" : reply = quoted ( u . body ) errors = r . json ( ) [ 'data' ] [ 'errors' ] reply += "\r\n\r\n" . join ( [ json . dumps ( e ) for e in errors ] ) msg = MIMEMultipart ( ) msg [ "From" ] = "{} <{}>" . format ( name , user ) msg [ "To" ] = u . fr msg [ "Subject" ] = "Re: " + u . subject if u . headers . get ( 'Message-ID' ) : msg . add_header ( "In-Reply-To" , u . headers [ 'Message-ID' ] ) msg . add_header ( "References" , u . headers [ 'Message-ID' ] ) body = reply + "\r\n\r\n--\r\n" + tagline + "\r\n" + url msg . attach ( MIMEText ( body , "plain" ) ) text = msg . as_string ( ) server . sendmail ( user , u . fr , text ) u . read ( ) u . archive ( ) print ( "Email {} has been replied to." . format ( hash ) ) | 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 existence_check ( text , list , err , msg , max_errors = 1 ) | 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 shed" , [ "sharpest marble in the (shed|box)" ] ] , [ "not rocket science" , [ "not rocket surgery" ] ] , ] return preferred_forms_check ( text , preferences , err , msg ) | 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 ) operators = config . get ( section = DEFAULT_CONFIG_SECTION , option = "operators" , fallback = DEFAULT_OPERATORS ) archiver = config . get ( section = DEFAULT_CONFIG_SECTION , option = "archiver" , fallback = DEFAULT_ARCHIVER ) path = config . get ( section = DEFAULT_CONFIG_SECTION , option = "path" , fallback = "." ) max_revisions = int ( config . get ( section = DEFAULT_CONFIG_SECTION , option = "max_revisions" , fallback = DEFAULT_MAX_REVISIONS , ) ) return WilyConfig ( operators = operators , archiver = archiver , path = path , max_revisions = max_revisions ) | 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 = path if cache : logger . debug ( f"Fixing cache to {cache}" ) ctx . obj [ "CONFIG" ] . cache_path = cache logger . debug ( f"Loaded configuration from {config}" ) | \ 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 {operators}" ) config . operators = operators . strip ( ) . split ( "," ) if archiver : logger . debug ( f"Fixing archiver to {archiver}" ) config . archiver = archiver if targets : logger . debug ( f"Fixing targets to {targets}" ) config . targets = targets build ( config = config , archiver = resolve_archiver ( config . archiver ) , operators = resolve_operators ( config . operators ) , ) logger . info ( "Completed building wily history, run `wily report <file>` or `wily index` to see more." ) | 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 output : new_output = new_output / Path ( output ) else : new_output = new_output / "wily_report" / "index.html" from wily . commands . report import report logger . debug ( f"Running report on {file} for metric {metrics}" ) logger . debug ( f"Output format is {format}" ) report ( config = config , path = file , metrics = metrics , n = number , output = new_output , include_message = message , format = ReportFormat [ format ] , console_format = console_format , ) | 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 metrics {metrics}" ) from wily . commands . diff import diff logger . debug ( f"Running diff on {files} for metric {metrics}" ) diff ( config = config , files = files , metrics = metrics , changes_only = not all , detail = detail ) | 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 , output = output , x_axis = x_axis , changes = changes , ) | 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? : " ) revisions = int ( revisions ) path = input ( "Path to your source files; comma-separated for multiple: " ) paths = path . split ( "," ) context . invoke ( build , max_revisions = revisions , targets = paths , operators = None , ) | 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_axis ) if abs_path . is_dir ( ) : paths = [ p . relative_to ( config . path ) for p in pathlib . Path ( abs_path ) . glob ( "**/*.py" ) ] else : paths = [ path ] operator , key = metric_parts ( metrics [ 0 ] ) if len ( metrics ) == 1 : z_axis = None else : z_axis = resolve_metric ( metrics [ 1 ] ) z_operator , z_key = metric_parts ( metrics [ 1 ] ) for path in paths : x = [ ] y = [ ] z = [ ] labels = [ ] last_y = None for rev in state . index [ state . default_archiver ] . revisions : labels . append ( f"{rev.revision.author_name} <br>{rev.revision.message}" ) try : val = rev . get ( config , state . default_archiver , operator , str ( path ) , key ) if val != last_y or not changes : y . append ( val ) if z_axis : z . append ( rev . get ( config , state . default_archiver , z_operator , str ( path ) , z_key , ) ) if x_axis == "history" : x . append ( format_datetime ( rev . revision . date ) ) else : x . append ( rev . get ( config , state . default_archiver , x_operator , str ( path ) , x_key , ) ) last_y = val except KeyError : pass trace = go . Scatter ( x = x , y = y , mode = "lines+markers+text" if text else "lines+markers" , name = f"{path}" , ids = state . index [ state . default_archiver ] . revision_keys , text = labels , marker = dict ( size = 0 if z_axis is None else z , color = list ( range ( len ( y ) ) ) , ) , xcalendar = "gregorian" , hoveron = "points+fills" , ) data . append ( trace ) if output : filename = output auto_open = False else : filename = "wily-report.html" auto_open = True y_metric = resolve_metric ( metrics [ 0 ] ) title = f"{x_axis.capitalize()} of {y_metric.description} for {path}" plotly . offline . plot ( { "data" : data , "layout" : go . Layout ( title = title , xaxis = { "title" : x_axis } , yaxis = { "title" : y_metric . description } , ) , } , auto_open = auto_open , filename = filename , ) | 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, not a valid git repo" ) archiver = FilesystemArchiver ( config ) revisions = archiver . revisions ( config . path , config . max_revisions ) except Exception as e : if hasattr ( e , "message" ) : logger . error ( f"Failed to setup archiver: '{e.message}'" ) else : logger . error ( f"Failed to setup archiver: '{type(e)} - {e}'" ) exit ( 1 ) state = State ( config , archiver = archiver ) state . ensure_exists ( ) index = state . index [ archiver . name ] revisions = [ revision for revision in revisions if revision not in index ] logger . info ( f"Found {len(revisions)} revisions from '{archiver.name}' archiver in '{config.path}'." ) _op_desc = "," . join ( [ operator . name for operator in operators ] ) logger . info ( f"Running operators - {_op_desc}" ) bar = Bar ( "Processing" , max = len ( revisions ) * len ( operators ) ) state . operators = operators try : with multiprocessing . Pool ( processes = len ( operators ) ) as pool : for revision in revisions : archiver . checkout ( revision , config . checkout_options ) stats = { "operator_data" : { } } data = pool . starmap ( run_operator , [ ( operator , revision , config ) for operator in operators ] , ) for operator_name , result in data : roots = [ ] for entry in result . keys ( ) : parent = pathlib . Path ( entry ) . parents [ 0 ] if parent not in roots : roots . append ( parent ) for root in roots : aggregates = [ path for path in result . keys ( ) if root in pathlib . Path ( path ) . parents ] result [ str ( root ) ] = { } for metric in resolve_operator ( operator_name ) . cls . metrics : func = metric . aggregate values = [ result [ aggregate ] [ metric . name ] for aggregate in aggregates if aggregate in result and metric . name in result [ aggregate ] ] if len ( values ) > 0 : result [ str ( root ) ] [ metric . name ] = func ( values ) stats [ "operator_data" ] [ operator_name ] = result bar . next ( ) ir = index . add ( revision , operators = operators ) ir . store ( config , archiver , stats ) index . save ( ) bar . finish ( ) except Exception as e : logger . error ( f"Failed to build cache: '{e}'" ) raise e finally : archiver . finish ( ) | Build the history given a archiver and collection of operators . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.