idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
32,200
def _initialize_aws_identity_document ( cls ) : if cls . inited : return content = get_request ( _AWS_INSTANCE_IDENTITY_DOCUMENT_URI ) if content is not None : content = json . loads ( content ) for env_var , attribute_key in _AWS_ATTRIBUTES . items ( ) : attribute_value = content . get ( env_var ) if attribute_value i...
This method tries to establish an HTTP connection to AWS instance identity document url . If the application is running on an EC2 instance we should be able to get back a valid JSON document . Make a http get request call and store data in local map . This method should only be called once .
32,201
def get_metric_descriptor ( self ) : with self . _md_cache_lock : if self . _metric_descriptor is None : self . _metric_descriptor = metric_descriptor . MetricDescriptor ( self . name , self . description , self . measure . unit , metric_utils . get_metric_type ( self . measure , self . aggregation ) , [ label_key . La...
Get a MetricDescriptor for this view .
32,202
def new_stats_exporter ( service_name , hostname = None , endpoint = None , interval = None ) : endpoint = utils . DEFAULT_ENDPOINT if endpoint is None else endpoint exporter = StatsExporter ( ExportRpcHandler ( _create_stub ( endpoint ) , service_name , hostname ) ) transport . get_exporter_thread ( stats . stats , ex...
Create a new worker thread and attach the exporter to it .
32,203
def export_metrics ( self , metrics ) : metric_protos = [ ] for metric in metrics : metric_protos . append ( _get_metric_proto ( metric ) ) self . _rpc_handler . send ( metrics_service_pb2 . ExportMetricsServiceRequest ( metrics = metric_protos ) )
Exports given metrics to target metric service .
32,204
def send ( self , request ) : if not self . _initialized : self . _initialize ( request ) return try : self . _rpc . send ( request ) except grpc . RpcError as e : logging . info ( 'Found rpc error %s' , e , exc_info = True ) self . _initialize ( request )
Dispatches incoming request on rpc .
32,205
def _initialize ( self , request ) : request . node . MergeFrom ( self . _node ) request . resource . MergeFrom ( self . _resource ) self . _initial_request = request self . _rpc . open ( ) self . _initialized = True
Initializes the exporter rpc stream .
32,206
def connect ( * args , ** kwargs ) : kwargs [ 'cursor_factory' ] = TraceCursor conn = pg_connect ( * args , ** kwargs ) return conn
Create database connection use TraceCursor as the cursor_factory .
32,207
def get_view ( self , view_name , timestamp ) : view = self . _registered_views . get ( view_name ) if view is None : return None view_data_list = self . _measure_to_view_data_list_map . get ( view . measure . name ) if not view_data_list : return None for view_data in view_data_list : if view_data . view . name == vie...
get the View Data from the given View name
32,208
def register_view ( self , view , timestamp ) : if len ( self . exporters ) > 0 : try : for e in self . exporters : e . on_register_view ( view ) except AttributeError : pass self . _exported_views = None existing_view = self . _registered_views . get ( view . name ) if existing_view is not None : if existing_view == v...
registers the view s measure name to View Datas given a view
32,209
def record ( self , tags , measurement_map , timestamp , attachments = None ) : assert all ( vv >= 0 for vv in measurement_map . values ( ) ) for measure , value in measurement_map . items ( ) : if measure != self . _registered_measures . get ( measure . name ) : return view_datas = [ ] for measure_name , view_data_lis...
records stats with a set of tags
32,210
def export ( self , view_datas ) : view_datas_copy = [ self . copy_and_finalize_view_data ( vd ) for vd in view_datas ] if len ( self . exporters ) > 0 : for e in self . exporters : try : e . export ( view_datas_copy ) except AttributeError : pass
export view datas to registered exporters
32,211
def get_metrics ( self , timestamp ) : for vdl in self . _measure_to_view_data_list_map . values ( ) : for vd in vdl : metric = metric_utils . view_data_to_metric ( vd , timestamp ) if metric is not None : yield metric
Get a Metric for each registered view .
32,212
def _transmit ( self , envelopes ) : if not envelopes : return 0 blacklist_hostnames = execution_context . get_opencensus_attr ( 'blacklist_hostnames' , ) execution_context . set_opencensus_attr ( 'blacklist_hostnames' , [ 'dc.services.visualstudio.com' ] , ) try : response = requests . post ( url = self . options . en...
Transmit the data envelopes to the ingestion service . Return a negative value for partial success or non - retryable failure . Return 0 if all envelopes have been successfully ingested . Return the next retry time in seconds for retryable failure . This function should never throw exception .
32,213
def get_instance ( ) : resources = [ ] env_resource = resource . get_from_env ( ) if env_resource is not None : resources . append ( env_resource ) if k8s_utils . is_k8s_environment ( ) : resources . append ( resource . Resource ( _K8S_CONTAINER , k8s_utils . get_k8s_metadata ( ) ) ) if is_gce_environment ( ) : resourc...
Get a resource based on the application environment .
32,214
def lint ( session ) : session . interpreter = 'python3.6' session . install ( 'flake8' ) _install_dev_packages ( session ) session . run ( 'flake8' , '--exclude=contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/trace_exporter/gen/' , 'context/' , 'contrib/' , 'opencensus/' , 'tests/' , 'examples/' )
Run flake8 . Returns a failure if flake8 finds linting errors or sufficiently serious code quality issues .
32,215
def trace_integration ( tracer = None ) : log . info ( 'Integrated module: {}' . format ( MODULE_NAME ) ) monitoring . register ( MongoCommandListener ( tracer = tracer ) )
Integrate with pymongo to trace it using event listener .
32,216
def get_request ( request_url , request_headers = dict ( ) ) : request = Request ( request_url ) for key , val in request_headers . items ( ) : request . add_header ( key , val ) try : response = urlopen ( request , timeout = _REQUEST_TIMEOUT ) response_content = response . read ( ) except ( HTTPError , URLError , sock...
Execute http get request on given request_url with optional headers
32,217
def trace_integration ( tracer = None ) : log . info ( 'Integrated module: {}' . format ( MODULE_NAME ) ) if tracer is not None : execution_context . set_opencensus_tracer ( tracer ) for func in REQUESTS_WRAP_METHODS : requests_func = getattr ( requests , func ) wrapped = wrap_requests ( requests_func ) setattr ( reque...
Wrap the requests library to trace it .
32,218
def wrap_requests ( requests_func ) : def call ( url , * args , ** kwargs ) : blacklist_hostnames = execution_context . get_opencensus_attr ( 'blacklist_hostnames' ) parsed_url = urlparse ( url ) if parsed_url . port is None : dest_url = parsed_url . hostname else : dest_url = '{}:{}' . format ( parsed_url . hostname ,...
Wrap the requests function to trace it .
32,219
def wrap_session_request ( wrapped , instance , args , kwargs ) : method = kwargs . get ( 'method' ) or args [ 0 ] url = kwargs . get ( 'url' ) or args [ 1 ] blacklist_hostnames = execution_context . get_opencensus_attr ( 'blacklist_hostnames' ) parsed_url = urlparse ( url ) if parsed_url . port is None : dest_url = pa...
Wrap the session function to trace it .
32,220
def get_metric_type ( measure , aggregation ) : if aggregation . aggregation_type == aggregation_module . Type . NONE : raise ValueError ( "aggregation type must not be NONE" ) assert isinstance ( aggregation , AGGREGATION_TYPE_MAP [ aggregation . aggregation_type ] ) if aggregation . aggregation_type == aggregation_mo...
Get the corresponding metric type for the given stats type .
32,221
def is_gauge ( md_type ) : if md_type not in metric_descriptor . MetricDescriptorType : raise ValueError return md_type in { metric_descriptor . MetricDescriptorType . GAUGE_INT64 , metric_descriptor . MetricDescriptorType . GAUGE_DOUBLE , metric_descriptor . MetricDescriptorType . GAUGE_DISTRIBUTION }
Whether a given MetricDescriptorType value is a gauge .
32,222
def view_data_to_metric ( view_data , timestamp ) : if not view_data . tag_value_aggregation_data_map : return None md = view_data . view . get_metric_descriptor ( ) if is_gauge ( md . type ) : ts_start = None else : ts_start = view_data . start_time ts_list = [ ] for tag_vals , agg_data in view_data . tag_value_aggreg...
Convert a ViewData to a Metric at time timestamp .
32,223
def _set_django_attributes ( span , request ) : django_user = getattr ( request , 'user' , None ) if django_user is None : return user_id = django_user . pk try : user_name = django_user . get_username ( ) except AttributeError : return if user_id is not None : span . add_attribute ( 'django.user.id' , str ( user_id ) ...
Set the django related attributes .
32,224
def process_request ( self , request ) : if utils . disable_tracing_url ( request . path , self . blacklist_paths ) : return execution_context . set_opencensus_attr ( REQUEST_THREAD_LOCAL_KEY , request ) execution_context . set_opencensus_attr ( 'blacklist_hostnames' , self . blacklist_hostnames ) try : span_context = ...
Called on each request before Django decides which view to execute .
32,225
def process_view ( self , request , view_func , * args , ** kwargs ) : if utils . disable_tracing_url ( request . path , self . blacklist_paths ) : return try : tracer = _get_current_tracer ( ) span = tracer . current_span ( ) span . name = utils . get_func_name ( view_func ) except Exception : log . error ( 'Failed to...
Process view is executed before the view function here we get the function name add set it as the span name .
32,226
def format_span_json ( span ) : span_json = { 'displayName' : utils . get_truncatable_str ( span . name ) , 'spanId' : span . span_id , 'startTime' : span . start_time , 'endTime' : span . end_time , 'childSpanCount' : len ( span . _child_spans ) } parent_span_id = None if span . parent_span is not None : parent_span_i...
Helper to format a Span in JSON format .
32,227
def add_annotation ( self , description , ** attrs ) : at = attributes . Attributes ( attrs ) self . add_time_event ( time_event_module . TimeEvent ( datetime . utcnow ( ) , time_event_module . Annotation ( description , at ) ) )
Add an annotation to span .
32,228
def add_time_event ( self , time_event ) : if isinstance ( time_event , time_event_module . TimeEvent ) : self . time_events . append ( time_event ) else : raise TypeError ( "Type Error: received {}, but requires TimeEvent." . format ( type ( time_event ) . __name__ ) )
Add a TimeEvent .
32,229
def add_link ( self , link ) : if isinstance ( link , link_module . Link ) : self . links . append ( link ) else : raise TypeError ( "Type Error: received {}, but requires Link." . format ( type ( link ) . __name__ ) )
Add a Link .
32,230
def _check_type ( self ) : check_type = metric_descriptor . MetricDescriptorType . to_type_class ( self . descriptor . type ) for ts in self . time_series : if not ts . check_points_type ( check_type ) : raise ValueError ( "Invalid point value type" )
Check that point value types match the descriptor type .
32,231
def _check_start_timestamp ( self ) : if self . descriptor . type in ( metric_descriptor . MetricDescriptorType . CUMULATIVE_INT64 , metric_descriptor . MetricDescriptorType . CUMULATIVE_DOUBLE , metric_descriptor . MetricDescriptorType . CUMULATIVE_DISTRIBUTION , ) : for ts in self . time_series : if ts . start_timest...
Check that starting timestamp exists for cumulative metrics .
32,232
def is_valid_boundaries ( self , boundaries ) : if boundaries is not None : min_ = boundaries [ 0 ] for value in boundaries : if value < min_ : return False else : min_ = value return True return False
checks if the boundaries are in ascending order
32,233
def get_exporter_thread ( metric_producer , exporter , interval = None ) : weak_get = utils . get_weakref ( metric_producer . get_metrics ) weak_export = utils . get_weakref ( exporter . export_metrics ) def export_all ( ) : get = weak_get ( ) if get is None : raise TransportError ( "Metric producer is not available" )...
Get a running task that periodically exports metrics .
32,234
def _before_request ( self ) : if utils . disable_tracing_url ( flask . request . url , self . blacklist_paths ) : return try : span_context = self . propagator . from_headers ( flask . request . headers ) tracer = tracer_module . Tracer ( span_context = span_context , sampler = self . sampler , exporter = self . expor...
A function to be run before each request .
32,235
def _after_request ( self , response ) : if utils . disable_tracing_url ( flask . request . url , self . blacklist_paths ) : return response try : tracer = execution_context . get_opencensus_tracer ( ) tracer . add_attribute_to_current_span ( HTTP_STATUS_CODE , str ( response . status_code ) ) except Exception : log . ...
A function to be run after each request .
32,236
def get_func_name ( func ) : func_name = getattr ( func , '__name__' , func . __class__ . __name__ ) module_name = func . __module__ if module_name is not None : module_name = func . __module__ return '{}.{}' . format ( module_name , func_name ) return func_name
Return a name which includes the module name and function name .
32,237
def disable_tracing_url ( url , blacklist_paths = None ) : if blacklist_paths is None : blacklist_paths = DEFAULT_BLACKLIST_PATHS url = re . sub ( URL_PATTERN , '' , url ) url_path = url . split ( '/' , 1 ) [ 1 ] for path in blacklist_paths : if url_path . startswith ( path ) : return True return False
Disable tracing on the provided blacklist paths by default not tracing the health check request .
32,238
def disable_tracing_hostname ( url , blacklist_hostnames = None ) : if blacklist_hostnames is None : _tracer = execution_context . get_opencensus_tracer ( ) try : blacklist_hostnames = [ '{}:{}' . format ( _tracer . exporter . host_name , _tracer . exporter . port ) ] except ( AttributeError ) : blacklist_hostnames = [...
Disable tracing for the provided blacklist URLs by default not tracing the exporter url .
32,239
def set_enabled ( self , enabled ) : enabled_bit = '1' if enabled else '0' self . trace_options_byte = str ( self . trace_options_byte ) [ : - 1 ] + enabled_bit self . enabled = self . get_enabled
Update the last bit of the trace options byte str .
32,240
def get_k8s_metadata ( ) : k8s_metadata = { } gcp_cluster = ( gcp_metadata_config . GcpMetadataConfig . get_attribute ( gcp_metadata_config . CLUSTER_NAME_KEY ) ) if gcp_cluster is not None : k8s_metadata [ CLUSTER_NAME_KEY ] = gcp_cluster for attribute_key , attribute_env in _K8S_ENV_ATTRIBUTES . items ( ) : attribute...
Get kubernetes container metadata as on GCP GKE .
32,241
def insert ( self , key , value ) : if key in self . map : return try : tag_key = TagKey ( key ) tag_val = TagValue ( value ) self . map [ tag_key ] = tag_val except ValueError : raise
Inserts a key and value in the map if the map does not already contain the key .
32,242
def update ( self , key , value ) : if key in self . map : self . map [ key ] = value
Updates the map by updating the value of a key
32,243
def trace_integration ( tracer = None ) : log . info ( "Integrated module: {}" . format ( MODULE_NAME ) ) start_func = getattr ( threading . Thread , "start" ) setattr ( threading . Thread , start_func . __name__ , wrap_threading_start ( start_func ) ) run_func = getattr ( threading . Thread , "run" ) setattr ( threadi...
Wrap threading functions to trace .
32,244
def wrap_threading_start ( start_func ) : def call ( self ) : self . _opencensus_context = ( execution_context . get_opencensus_full_context ( ) ) return start_func ( self ) return call
Wrap the start function from thread . Put the tracer informations in the threading object .
32,245
def wrap_threading_run ( run_func ) : def call ( self ) : execution_context . set_opencensus_full_context ( * self . _opencensus_context ) return run_func ( self ) return call
Wrap the run function from thread . Get the tracer informations from the threading object and set it as current tracer .
32,246
def format_attributes_json ( self ) : attributes_json = { } for key , value in self . attributes . items ( ) : key = utils . check_str_length ( key ) [ 0 ] value = _format_attribute_value ( value ) if value is not None : attributes_json [ key ] = value result = { 'attributeMap' : attributes_json } return result
Convert the Attributes object to json format .
32,247
def add_sample ( self , value , timestamp , attachments ) : self . _count_data += 1 bucket = self . increment_bucket_count ( value ) if attachments is not None and self . exemplars is not None : self . exemplars [ bucket ] = Exemplar ( value , timestamp , attachments ) if self . count_data == 1 : self . _mean_data = va...
Adding a sample to Distribution Aggregation Data
32,248
def increment_bucket_count ( self , value ) : if len ( self . _bounds ) == 0 : self . _counts_per_bucket [ 0 ] += 1 return 0 for ii , bb in enumerate ( self . _bounds ) : if value < bb : self . _counts_per_bucket [ ii ] += 1 return ii else : last_bucket_index = len ( self . _bounds ) self . _counts_per_bucket [ last_bu...
Increment the bucket count based on a given value from the user
32,249
def load_crawler ( self , crawler , url , ignore_regex ) : self . process = CrawlerProcess ( self . cfg . get_scrapy_options ( ) ) self . process . crawl ( crawler , self . helper , url = url , config = self . cfg , ignore_regex = ignore_regex )
Loads the given crawler with the given url .
32,250
def _language ( self , item ) : response = item [ 'spider_response' ] . body root = html . fromstring ( response ) lang = root . get ( 'lang' ) if lang is None : lang = root . get ( 'xml:lang' ) if lang is None : meta = root . cssselect ( 'meta[name="language"]' ) if len ( meta ) > 0 : lang = meta [ 0 ] . get ( 'conten...
Returns the language of the extracted article by analyzing metatags and inspecting the visible text with langdetect
32,251
def parse ( self , response ) : if not self . helper . parse_crawler . content_type ( response ) : return yield self . helper . parse_crawler . pass_to_pipeline ( response , self . helper . url_extractor . get_allowed_domain ( response . url ) )
Passes the response to the pipeline .
32,252
def extract ( self , item , list_article_candidate ) : languages_extracted = [ ] language_newspaper = None for article_candidate in list_article_candidate : if article_candidate . language is not None : languages_extracted . append ( article_candidate . language ) if article_candidate . extractor == "newspaper" : langu...
Compares how often any language was detected .
32,253
def extract ( self , item , list_article_candidate ) : list_publish_date = [ ] for article_candidate in list_article_candidate : if article_candidate . publish_date != None : list_publish_date . append ( ( article_candidate . publish_date , article_candidate . extractor ) ) if len ( list_publish_date ) == 0 : return No...
Compares the extracted publish dates .
32,254
def meta_contains_article_keyword ( self , response , site_dict ) : contains_meta = response . xpath ( '//meta' ) . re ( '(= ?["\'][^"\']*article[^"\']*["\'])' ) if not contains_meta : return False return True
Determines wether the response s meta data contains the keyword article
32,255
def linked_headlines ( self , response , site_dict , check_self = False ) : h_all = 0 h_linked = 0 domain = UrlExtractor . get_allowed_domain ( site_dict [ "url" ] , False ) site_regex = r"href=[\"'][^\/]*\/\/(?:[^\"']*\.|)%s[\"'\/]" % domain for i in range ( 1 , 7 ) : for headline in response . xpath ( '//h%s' % i ) ....
Checks how many of the headlines on the site contain links .
32,256
def is_not_from_subdomain ( self , response , site_dict ) : root_url = re . sub ( re_url_root , '' , site_dict [ "url" ] ) return UrlExtractor . get_allowed_domain ( response . url ) == root_url
Ensures the response s url isn t from a subdomain .
32,257
def extract ( self , item , list_article_candidate ) : list_description = [ ] for article_candidate in list_article_candidate : if article_candidate . description != None : list_description . append ( ( article_candidate . description , article_candidate . extractor ) ) if len ( list_description ) == 0 : return None li...
Compares the extracted descriptions .
32,258
def close_spider ( self , _spider ) : self . df [ 'date_download' ] = pd . to_datetime ( self . df [ 'date_download' ] , errors = 'coerce' , infer_datetime_format = True ) self . df [ 'date_modify' ] = pd . to_datetime ( self . df [ 'date_modify' ] , errors = 'coerce' , infer_datetime_format = True ) self . df [ 'date_...
Write out to file
32,259
def _publish_date ( self , item ) : url = item [ 'url' ] html = deepcopy ( item [ 'spider_response' ] . body ) publish_date = None try : if html is None : request = urllib2 . Request ( url ) html = urllib2 . build_opener ( ) . open ( request ) . read ( ) html = BeautifulSoup ( html , "lxml" ) publish_date = self . _ext...
Returns the publish_date of the extracted article .
32,260
def _extract_from_url ( self , url ) : m = re . search ( re_pub_date , url ) if m : return self . parse_date_str ( m . group ( 0 ) ) return None
Try to extract from the article URL - simple but might work as a fallback
32,261
def delete_tags ( self , arg ) : if len ( arg ) > 0 : raw = html . fromstring ( arg ) return raw . text_content ( ) . strip ( ) return arg
Removes html - tags from extracted data .
32,262
def delete_whitespaces ( self , arg ) : arg = re . sub ( re_newline_spc , '' , arg ) arg = re . sub ( re_starting_whitespc , '' , arg ) arg = re . sub ( re_multi_spc_tab , '' , arg ) arg = re . sub ( re_double_newline , '' , arg ) arg = re . sub ( re_ending_spc_newline , '' , arg ) return arg
Removes newlines tabs and whitespaces at the beginning the end and if there is more than one .
32,263
def do_cleaning ( self , arg ) : if arg is not None : if isinstance ( arg , list ) : newlist = [ ] for entry in arg : newlist . append ( self . do_cleaning ( entry ) ) return newlist else : if sys . version_info [ 0 ] < 3 : arg = unicode ( arg ) else : arg = str ( arg ) arg = self . delete_tags ( arg ) arg = self . del...
Does the actual cleaning by using the delete methods above .
32,264
def clean ( self , list_article_candidates ) : results = [ ] for article_candidate in list_article_candidates : article_candidate . title = self . do_cleaning ( article_candidate . title ) article_candidate . description = self . do_cleaning ( article_candidate . description ) article_candidate . text = self . do_clean...
Iterates over each article_candidate and cleans every extracted data .
32,265
def compare ( self , item , article_candidates ) : result = ArticleCandidate ( ) result . title = self . comparer_title . extract ( item , article_candidates ) result . description = self . comparer_desciption . extract ( item , article_candidates ) result . text = self . comparer_text . extract ( item , article_candid...
Compares the article candidates using the different submodules and saves the best results in new ArticleCandidate object
32,266
def parse ( self , response ) : yield scrapy . Request ( self . helper . url_extractor . get_rss_url ( response ) , callback = self . rss_parse )
Extracts the Rss Feed and initiates crawling it .
32,267
def supports_site ( url ) : opener = urllib2 . build_opener ( urllib2 . HTTPRedirectHandler ) redirect = opener . open ( url ) . url response = urllib2 . urlopen ( redirect ) . read ( ) return re . search ( re_rss , response . decode ( 'utf-8' ) ) is not None
Rss Crawler are supported if by every site containing an rss feed .
32,268
def get_allowed_domain ( url , allow_subdomains = True ) : if allow_subdomains : return re . sub ( re_www , '' , re . search ( r'[^/]+\.[^/]+' , url ) . group ( 0 ) ) else : return re . search ( re_domain , UrlExtractor . get_allowed_domain ( url ) ) . group ( 0 )
Determines the url s domain .
32,269
def get_subdomain ( url ) : allowed_domain = UrlExtractor . get_allowed_domain ( url ) return allowed_domain [ : len ( allowed_domain ) - len ( UrlExtractor . get_allowed_domain ( url , False ) ) ]
Determines the domain s subdomains .
32,270
def follow_redirects ( url ) : opener = urllib2 . build_opener ( urllib2 . HTTPRedirectHandler ) return opener . open ( url ) . url
Get s the url actual address by following forwards
32,271
def get_sitemap_url ( url , allow_subdomains ) : if allow_subdomains : redirect = UrlExtractor . follow_redirects ( "http://" + UrlExtractor . get_allowed_domain ( url ) ) else : redirect = UrlExtractor . follow_redirects ( "http://" + UrlExtractor . get_allowed_domain ( url , False ) ) redirect = UrlExtractor . follow...
Determines the domain s robot . txt
32,272
def sitemap_check ( url ) : response = urllib2 . urlopen ( UrlExtractor . get_sitemap_url ( url , True ) ) return "Sitemap:" in response . read ( ) . decode ( 'utf-8' )
Sitemap - Crawler are supported by every site which have a Sitemap set in the robots . txt .
32,273
def get_url_directory_string ( url ) : domain = UrlExtractor . get_allowed_domain ( url ) splitted_url = url . split ( '/' ) for index in range ( len ( splitted_url ) ) : if not re . search ( domain , splitted_url [ index ] ) is None : if splitted_url [ - 1 ] is "" : splitted_url = splitted_url [ index + 1 : - 2 ] else...
Determines the url s directory string .
32,274
def get_url_file_name ( url ) : url_root_ext = os . path . splitext ( url ) if len ( url_root_ext [ 1 ] ) <= MAX_FILE_EXTENSION_LENGTH : return os . path . split ( url_root_ext [ 0 ] ) [ 1 ] else : return os . path . split ( url ) [ 1 ]
Determines the url s file name .
32,275
def load_config ( self ) : self . __config = { } for section in self . sections : self . __config [ section ] = { } options = self . parser . options ( section ) for option in options : try : opt = self . parser . get ( section , option ) try : self . __config [ section ] [ option ] = literal_eval ( opt ) except ( Synt...
Loads the config - file
32,276
def handle_logging ( self ) : configure_logging ( self . get_scrapy_options ( ) ) self . __scrapy_options [ "LOG_ENABLED" ] = False for msg in self . log_output : if msg [ "level" ] is "error" : self . log . error ( msg [ "msg" ] ) elif msg [ "level" ] is "info" : self . log . info ( msg [ "msg" ] ) elif msg [ "level" ...
To allow devs to log as early as possible logging will already be handled here
32,277
def option ( self , option ) : if self . __current_section is None : raise RuntimeError ( 'No section set in option-getting' ) return self . __config [ self . __current_section ] [ option ]
Gets the option set_section needs to be set before .
32,278
def get_url_array ( self ) : urlarray = [ ] for urlobjects in self . __json_object [ "base_urls" ] : urlarray . append ( urlobjects [ "url" ] ) return urlarray
Get all url - objects in an array
32,279
def find_matches ( self , list_title ) : list_title_matches = [ ] for a , b , in itertools . combinations ( list_title , 2 ) : if a == b : list_title_matches . append ( a ) return list_title_matches
Checks if there are any matches between extracted titles .
32,280
def extract_match ( self , list_title_matches ) : list_title_matches_set = set ( list_title_matches ) list_title_count = [ ] for match in list_title_matches_set : list_title_count . append ( ( list_title_matches . count ( match ) , match ) ) if list_title_count and max ( list_title_count ) [ 0 ] != min ( list_title_cou...
Extract the title with the most matches from the list .
32,281
def extract ( self , item , list_article_candidate ) : list_title = [ ] for article_candidate in list_article_candidate : if article_candidate . title is not None : list_title . append ( article_candidate . title ) if not list_title : return None list_title_matches = self . find_matches ( list_title ) matched_title = s...
Compares the extracted titles .
32,282
def cli ( cfg_file_path , resume , reset_elasticsearch , reset_mysql , reset_json , reset_all , no_confirm ) : "A generic news crawler and extractor." if reset_all : reset_elasticsearch = True reset_json = True reset_mysql = True if cfg_file_path and not cfg_file_path . endswith ( os . path . sep ) : cfg_file_path += o...
A generic news crawler and extractor .
32,283
def manage_crawlers ( self ) : sites = self . json . get_site_objects ( ) for index , site in enumerate ( sites ) : if "daemonize" in site : self . daemon_list . add_daemon ( index , site [ "daemonize" ] ) elif "additional_rss_daemon" in site : self . daemon_list . add_daemon ( index , site [ "additional_rss_daemon" ] ...
Manages all crawlers threads and limites the number of parallel running threads .
32,284
def manage_crawler ( self ) : index = True self . number_of_active_crawlers += 1 while not self . shutdown and index is not None : index = self . crawler_list . get_next_item ( ) if index is None : self . number_of_active_crawlers -= 1 break self . start_crawler ( index )
Manages a normal crawler thread .
32,285
def manage_daemon ( self ) : while not self . shutdown : item = self . daemon_list . get_next_item ( ) cur = time . time ( ) pajama_time = item [ 0 ] - cur if pajama_time > 0 : self . thread_event . wait ( pajama_time ) if not self . shutdown : self . start_crawler ( item [ 1 ] , daemonize = True )
Manages a daemonized crawler thread .
32,286
def start_crawler ( self , index , daemonize = False ) : call_process = [ sys . executable , self . __single_crawler , self . cfg_file_path , self . json_file_path , "%s" % index , "%s" % self . shall_resume , "%s" % daemonize ] self . log . debug ( "Calling Process: %s" , call_process ) crawler = Popen ( call_process ...
Starts a crawler from the input - array .
32,287
def graceful_stop ( self , signal_number = None , stack_frame = None ) : stop_msg = "Hard" if self . shutdown else "Graceful" if signal_number is None : self . log . info ( "%s stop called manually. " "Shutting down." , stop_msg ) else : self . log . info ( "%s stop called by signal #%s. Shutting down." "Stack Frame: %...
This function will be called when a graceful - stop is initiated .
32,288
def time_replacer ( match , timestamp ) : return time . strftime ( match . group ( 1 ) , time . gmtime ( timestamp ) )
Transforms the timestamp to the format the regex match determines .
32,289
def append_md5_if_too_long ( component , size ) : if len ( component ) > size : if size > 32 : component_size = size - 32 - 1 return "%s_%s" % ( component [ : component_size ] , hashlib . md5 ( component . encode ( 'utf-8' ) ) . hexdigest ( ) ) else : return hashlib . md5 ( component . encode ( 'utf-8' ) ) . hexdigest ...
Trims the component if it is longer than size and appends the component s md5 . Total must be of length size .
32,290
def remove_not_allowed_chars ( savepath ) : split_savepath = os . path . splitdrive ( savepath ) savepath_without_invalid_chars = re . sub ( r'<|>|:|\"|\||\?|\*' , '_' , split_savepath [ 1 ] ) return split_savepath [ 0 ] + savepath_without_invalid_chars
Removes invalid filepath characters from the savepath .
32,291
def get_abs_path_static ( savepath , relative_to_path ) : if os . path . isabs ( savepath ) : return os . path . abspath ( savepath ) else : return os . path . abspath ( os . path . join ( relative_to_path , ( savepath ) ) )
Figures out the savepath s absolute version .
32,292
def get_base_path ( path ) : if "%" not in path : return path path = os . path . split ( path ) [ 0 ] while "%" in path : path = os . path . split ( path ) [ 0 ] return path
Determines the longest possible beginning of a path that does not contain a % - Symbol .
32,293
def get_max_url_file_name_length ( savepath ) : number_occurrences = savepath . count ( '%max_url_file_name' ) number_occurrences += savepath . count ( '%appendmd5_max_url_file_name' ) savepath_copy = savepath size_without_max_url_file_name = len ( savepath_copy . replace ( '%max_url_file_name' , '' ) . replace ( '%app...
Determines the max length for any max ... parts .
32,294
def extract ( self , item ) : doc = Document ( deepcopy ( item [ 'spider_response' ] . body ) ) description = doc . summary ( ) article_candidate = ArticleCandidate ( ) article_candidate . extractor = self . _name article_candidate . title = doc . short_title ( ) article_candidate . description = description article_ca...
Creates an readability document and returns an ArticleCandidate containing article title and text .
32,295
def extract ( self , item ) : article_candidates = [ ] for extractor in self . extractor_list : article_candidates . append ( extractor . extract ( item ) ) article_candidates = self . cleaner . clean ( article_candidates ) article = self . comparer . compare ( item , article_candidates ) item [ 'article_title' ] = art...
Runs the HTML - response trough a list of initialized extractors a cleaner and compares the results .
32,296
def pass_to_pipeline_if_article ( self , response , source_domain , original_url , rss_title = None ) : if self . helper . heuristics . is_article ( response , original_url ) : return self . pass_to_pipeline ( response , source_domain , rss_title = None )
Responsible for passing a NewscrawlerItem to the pipeline if the response contains an article .
32,297
def recursive_requests ( response , spider , ignore_regex = '' , ignore_file_extensions = 'pdf' ) : return [ scrapy . Request ( response . urljoin ( href ) , callback = spider . parse ) for href in response . css ( "a::attr('href')" ) . extract ( ) if re . match ( r'.*\.' + ignore_file_extensions + r'$' , response . ur...
Manages recursive requests . Determines urls to recursivly crawl if they do not match certain file extensions and do not match a certain regex set in the config file .
32,298
def content_type ( self , response ) : if not re_html . match ( response . headers . get ( 'Content-Type' ) . decode ( 'utf-8' ) ) : self . log . warn ( "Dropped: %s's content is not of type " "text/html but %s" , response . url , response . headers . get ( 'Content-Type' ) ) return False else : return True
Ensures the response is of type
32,299
def extract ( self , item , list_article_candidate ) : list_topimage = [ ] for article_candidate in list_article_candidate : if article_candidate . topimage is not None : article_candidate . topimage = self . image_absoulte_path ( item [ 'url' ] , article_candidate . topimage ) list_topimage . append ( ( article_candid...
Compares the extracted top images .