idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
48,300
def _get_template ( self ) : loader = PackageLoader ( self . _package_name , 'assets/templates' ) env = Environment ( extensions = [ 'jinja2.ext.with_' ] , loader = loader ) return env . get_template ( '{}.html' . format ( self . _report_name ) )
Returns a template for this report .
48,301
def _write ( self , context , report_dir , report_name , assets_dir = None , template = None ) : if template is None : template = self . _get_template ( ) report = template . render ( context ) output_file = os . path . join ( report_dir , report_name ) with open ( output_file , 'w' , encoding = 'utf-8' ) as fh : fh . ...
Writes the data in context in the report s template to report_name in report_dir .
48,302
def pull ( self ) : for item in self . input_stream : print ( '%s -' % item [ 'timestamp' ] , end = '' ) if item [ 'transport' ] : print ( item [ 'transport' ] [ 'type' ] , end = '' ) packet_type = item [ 'packet' ] [ 'type' ] print ( packet_type , end = '' ) packet = item [ 'packet' ] if packet_type in [ 'IP' , 'IP6' ...
Print out summary information about each packet from the input_stream
48,303
def pull ( self ) : for item in self . input_stream : print ( 'Timestamp: %s' % item [ 'timestamp' ] ) print ( 'Ethernet Frame: %s % ( net_utils . mac_to_str ( item [ 'eth' ] [ 'src' ] ) , net_utils . mac_to_str ( item [ 'eth' ] [ 'dst' ] ) , item [ 'eth' ] [ 'type' ] ) ) packet_type = item [ 'packet' ] [ 'type' ] pri...
Print out information about each packet from the input_stream
48,304
def load_backend ( ** orm_config ) : settings = { } settings [ 'SECRET_KEY' ] = orm_config . get ( 'secret_key' , '' ) db_config = orm_config [ 'database' ] if db_config : settings [ 'DATABASES' ] = { 'default' : database_settings ( db_config ) } from django_peeringdb . client_adaptor . setup import configure configure...
Load the client adaptor module of django_peeringdb Assumes config is valid .
48,305
def add_label_count ( self ) : self . _logger . info ( 'Adding label count' ) def add_label_count ( df ) : work_maxima = df . groupby ( constants . WORK_FIELDNAME , sort = False ) . max ( ) df . loc [ : , constants . LABEL_COUNT_FIELDNAME ] = work_maxima [ constants . COUNT_FIELDNAME ] . sum ( ) return df if self . _ma...
Adds to each result row a count of the number of occurrences of that n - gram across all works within the label .
48,306
def add_label_work_count ( self ) : self . _logger . info ( 'Adding label work count' ) def add_label_text_count ( df ) : work_maxima = df . groupby ( constants . WORK_FIELDNAME , sort = False ) . any ( ) df . loc [ : , constants . LABEL_WORK_COUNT_FIELDNAME ] = work_maxima [ constants . COUNT_FIELDNAME ] . sum ( ) ret...
Adds to each result row a count of the number of works within the label contain that n - gram .
48,307
def _annotate_bifurcated_extend_data ( self , row , smaller , larger , tokenize , join ) : lcf = constants . LABEL_COUNT_FIELDNAME nf = constants . NGRAM_FIELDNAME ngram = row [ constants . NGRAM_FIELDNAME ] label_count = row [ constants . LABEL_COUNT_FIELDNAME ] if label_count == 1 and not smaller . empty : ngram_toke...
Returns row annotated with whether it should be deleted or not .
48,308
def bifurcated_extend ( self , corpus , max_size ) : temp_fd , temp_path = tempfile . mkstemp ( text = True ) try : self . _prepare_bifurcated_extend_data ( corpus , max_size , temp_path , temp_fd ) finally : try : os . remove ( temp_path ) except OSError as e : msg = ( 'Failed to remove temporary file containing unred...
Replaces the results with those n - grams that contain any of the original n - grams and that represent points at which an n - gram is a constituent of multiple larger n - grams with a lower label count .
48,309
def collapse_witnesses ( self ) : if self . _matches . empty : self . _matches . rename ( columns = { constants . SIGLUM_FIELDNAME : constants . SIGLA_FIELDNAME } , inplace = True ) return self . _matches . loc [ : , constants . SIGLA_FIELDNAME ] = self . _matches [ constants . SIGLUM_FIELDNAME ] grouped = self . _matc...
Groups together witnesses for the same n - gram and work that has the same count and outputs a single row for each group .
48,310
def csv ( self , fh ) : self . _matches . to_csv ( fh , encoding = 'utf-8' , float_format = '%d' , index = False ) return fh
Writes the results data to fh in CSV format and returns fh .
48,311
def excise ( self , ngram ) : self . _logger . info ( 'Excising results containing "{}"' . format ( ngram ) ) if not ngram : return self . _matches = self . _matches [ ~ self . _matches [ constants . NGRAM_FIELDNAME ] . str . contains ( ngram , regex = False ) ]
Removes all rows whose n - gram contains ngram .
48,312
def extend ( self , corpus ) : self . _logger . info ( 'Extending results' ) if self . _matches . empty : return highest_n = self . _matches [ constants . SIZE_FIELDNAME ] . max ( ) if highest_n == 1 : self . _logger . warning ( 'Extending results that contain only 1-grams is unsupported; ' 'the original results will b...
Adds rows for all longer forms of n - grams in the results that are present in the witnesses .
48,313
def _generate_extended_matches ( self , extended_ngrams , highest_n , work , siglum , label ) : rows_list = [ ] for extended_ngram in extended_ngrams : text = Text ( extended_ngram , self . _tokenizer ) for size , ngrams in text . get_ngrams ( highest_n + 1 , len ( text . get_tokens ( ) ) ) : data = [ { constants . WOR...
Returns extended match data derived from extended_ngrams .
48,314
def _generate_extended_ngrams ( self , matches , work , siglum , label , corpus , highest_n ) : t_join = self . _tokenizer . joiner . join witness_matches = matches [ ( matches [ constants . WORK_FIELDNAME ] == work ) & ( matches [ constants . SIGLUM_FIELDNAME ] == siglum ) & ( matches [ constants . LABEL_FIELDNAME ] =...
Returns the n - grams of the largest size that exist in siglum witness to work under label generated from adding together overlapping n - grams in matches .
48,315
def _generate_filter_ngrams ( self , data , min_size ) : max_size = data [ constants . SIZE_FIELDNAME ] . max ( ) kept_ngrams = list ( data [ data [ constants . SIZE_FIELDNAME ] == min_size ] [ constants . NGRAM_FIELDNAME ] ) for size in range ( min_size + 1 , max_size + 1 ) : pattern = FilteredWitnessText . get_filter...
Returns the n - grams in data that do not contain any other n - gram in data .
48,316
def _generate_substrings ( self , ngram , size ) : text = Text ( ngram , self . _tokenizer ) substrings = [ ] for sub_size , ngrams in text . get_ngrams ( 1 , size - 1 ) : for sub_ngram , count in ngrams . items ( ) : substrings . extend ( [ sub_ngram ] * count ) return substrings
Returns a list of all substrings of ngram .
48,317
def group_by_witness ( self ) : if self . _matches . empty : self . _matches = pd . DataFrame ( { } , columns = [ constants . WORK_FIELDNAME , constants . SIGLUM_FIELDNAME , constants . LABEL_FIELDNAME , constants . NGRAMS_FIELDNAME , constants . NUMBER_FIELDNAME , constants . TOTAL_COUNT_FIELDNAME ] ) return def witne...
Groups results by witness providing a single summary field giving the n - grams found in it a count of their number and the count of their combined occurrences .
48,318
def _is_intersect_results ( results ) : sample = results . iloc [ 0 ] ngram = sample [ constants . NGRAM_FIELDNAME ] label = sample [ constants . LABEL_FIELDNAME ] return not ( results [ ( results [ constants . NGRAM_FIELDNAME ] == ngram ) & ( results [ constants . LABEL_FIELDNAME ] != label ) ] . empty )
Returns False if results has an n - gram that exists in only one label True otherwise .
48,319
def prune_by_ngram ( self , ngrams ) : self . _logger . info ( 'Pruning results by n-gram' ) self . _matches = self . _matches [ ~ self . _matches [ constants . NGRAM_FIELDNAME ] . isin ( ngrams ) ]
Removes results rows whose n - gram is in ngrams .
48,320
def prune_by_ngram_count_per_work ( self , minimum = None , maximum = None , label = None ) : self . _logger . info ( 'Pruning results by n-gram count per work' ) matches = self . _matches keep_ngrams = matches [ constants . NGRAM_FIELDNAME ] . unique ( ) if label is not None : matches = matches [ matches [ constants ....
Removes results rows if the n - gram count for all works bearing that n - gram is outside the range specified by minimum and maximum .
48,321
def prune_by_ngram_size ( self , minimum = None , maximum = None ) : self . _logger . info ( 'Pruning results by n-gram size' ) if minimum : self . _matches = self . _matches [ self . _matches [ constants . SIZE_FIELDNAME ] >= minimum ] if maximum : self . _matches = self . _matches [ self . _matches [ constants . SIZE...
Removes results rows whose n - gram size is outside the range specified by minimum and maximum .
48,322
def prune_by_work_count ( self , minimum = None , maximum = None , label = None ) : self . _logger . info ( 'Pruning results by work count' ) count_fieldname = 'tmp_count' matches = self . _matches if label is not None : matches = matches [ matches [ constants . LABEL_FIELDNAME ] == label ] filtered = matches [ matches...
Removes results rows for n - grams that are not attested in a number of works in the range specified by minimum and maximum .
48,323
def reciprocal_remove ( self ) : self . _logger . info ( 'Removing n-grams that are not attested in all labels' ) self . _matches = self . _reciprocal_remove ( self . _matches )
Removes results rows for which the n - gram is not present in at least one text in each labelled set of texts .
48,324
def reduce ( self ) : self . _logger . info ( 'Reducing the n-grams' ) data = { } labels = { } for row_index , row in self . _matches . iterrows ( ) : work = row [ constants . WORK_FIELDNAME ] siglum = row [ constants . SIGLUM_FIELDNAME ] labels [ work ] = row [ constants . LABEL_FIELDNAME ] witness_data = data . setde...
Removes results rows whose n - grams are contained in larger n - grams .
48,325
def _reduce_by_ngram ( self , data , ngram ) : count = data [ ngram ] [ 'count' ] for substring in self . _generate_substrings ( ngram , data [ ngram ] [ 'size' ] ) : try : substring_data = data [ substring ] except KeyError : continue else : substring_data [ 'count' ] -= count
Lowers the counts of all n - grams in data that are substrings of ngram by ngram \ s count .
48,326
def relabel ( self , catalogue ) : for work , label in catalogue . items ( ) : self . _matches . loc [ self . _matches [ constants . WORK_FIELDNAME ] == work , constants . LABEL_FIELDNAME ] = label
Relabels results rows according to catalogue .
48,327
def remove_label ( self , label ) : self . _logger . info ( 'Removing label "{}"' . format ( label ) ) count = self . _matches [ constants . LABEL_FIELDNAME ] . value_counts ( ) . get ( label , 0 ) self . _matches = self . _matches [ self . _matches [ constants . LABEL_FIELDNAME ] != label ] self . _logger . info ( 'Re...
Removes all results rows associated with label .
48,328
def sort ( self ) : self . _matches . sort_values ( by = [ constants . SIZE_FIELDNAME , constants . NGRAM_FIELDNAME , constants . COUNT_FIELDNAME , constants . LABEL_FIELDNAME , constants . WORK_FIELDNAME , constants . SIGLUM_FIELDNAME ] , ascending = [ False , True , False , True , True , True ] , inplace = True )
Sorts all results rows .
48,329
def zero_fill ( self , corpus ) : self . _logger . info ( 'Zero-filling results' ) zero_rows = [ ] work_sigla = { } grouping_cols = [ constants . LABEL_FIELDNAME , constants . NGRAM_FIELDNAME , constants . SIZE_FIELDNAME , constants . WORK_FIELDNAME ] grouped = self . _matches . groupby ( grouping_cols , sort = False )...
Adds rows to the results to ensure that for every n - gram that is attested in at least one witness every witness for that text has a row with added rows having a count of zero .
48,330
def get_logger ( ) : if not hasattr ( get_logger , 'logger' ) : get_logger . logger = logging . getLogger ( 'chains' ) format_str = '%(asctime)s [%(levelname)s] - %(module)s: %(message)s' logging . basicConfig ( datefmt = '%Y-%m-%d %H:%M:%S' , level = logging . INFO , format = format_str ) return get_logger . logger
Setup logging output defaults
48,331
def read_interface ( self ) : if self . _iface_is_file ( ) : self . pcap = pcapy . open_offline ( self . iface_name ) else : try : self . pcap = pcapy . open_live ( self . iface_name , 65536 , 1 , 0 ) except OSError : try : logger . warning ( 'Could not get promisc mode, turning flag off' ) self . pcap = pcapy . open_l...
Read Packets from the packet capture interface
48,332
def generate_parser ( ) : parser = argparse . ArgumentParser ( description = constants . TACL_DESCRIPTION , formatter_class = ParagraphFormatter ) subparsers = parser . add_subparsers ( title = 'subcommands' ) generate_align_subparser ( subparsers ) generate_catalogue_subparser ( subparsers ) generate_counts_subparser ...
Returns a parser configured with sub - commands and arguments .
48,333
def generate_align_subparser ( subparsers ) : parser = subparsers . add_parser ( 'align' , description = constants . ALIGN_DESCRIPTION , epilog = constants . ALIGN_EPILOG , formatter_class = ParagraphFormatter , help = constants . ALIGN_HELP ) parser . set_defaults ( func = align_results ) utils . add_common_arguments ...
Adds a sub - command parser to subparsers to generate aligned sequences from a set of results .
48,334
def generate_catalogue ( args , parser ) : catalogue = tacl . Catalogue ( ) catalogue . generate ( args . corpus , args . label ) catalogue . save ( args . catalogue )
Generates and saves a catalogue file .
48,335
def generate_catalogue_subparser ( subparsers ) : parser = subparsers . add_parser ( 'catalogue' , description = constants . CATALOGUE_DESCRIPTION , epilog = constants . CATALOGUE_EPILOG , formatter_class = ParagraphFormatter , help = constants . CATALOGUE_HELP ) utils . add_common_arguments ( parser ) parser . set_def...
Adds a sub - command parser to subparsers to generate and save a catalogue file .
48,336
def generate_counts_subparser ( subparsers ) : parser = subparsers . add_parser ( 'counts' , description = constants . COUNTS_DESCRIPTION , epilog = constants . COUNTS_EPILOG , formatter_class = ParagraphFormatter , help = constants . COUNTS_HELP ) parser . set_defaults ( func = ngram_counts ) utils . add_common_argume...
Adds a sub - command parser to subparsers to make a counts query .
48,337
def generate_diff_subparser ( subparsers ) : parser = subparsers . add_parser ( 'diff' , description = constants . DIFF_DESCRIPTION , epilog = constants . DIFF_EPILOG , formatter_class = ParagraphFormatter , help = constants . DIFF_HELP ) parser . set_defaults ( func = ngram_diff ) group = parser . add_mutually_exclusi...
Adds a sub - command parser to subparsers to make a diff query .
48,338
def generate_excise_subparser ( subparsers ) : parser = subparsers . add_parser ( 'excise' , description = constants . EXCISE_DESCRIPTION , help = constants . EXCISE_HELP ) parser . set_defaults ( func = excise ) utils . add_common_arguments ( parser ) parser . add_argument ( 'ngrams' , metavar = 'NGRAMS' , help = cons...
Adds a sub - command parser to subparsers to excise n - grams from witnesses .
48,339
def generate_highlight_subparser ( subparsers ) : parser = subparsers . add_parser ( 'highlight' , description = constants . HIGHLIGHT_DESCRIPTION , epilog = constants . HIGHLIGHT_EPILOG , formatter_class = ParagraphFormatter , help = constants . HIGHLIGHT_HELP ) parser . set_defaults ( func = highlight_text ) utils . ...
Adds a sub - command parser to subparsers to highlight a witness text with its matches in a result .
48,340
def generate_intersect_subparser ( subparsers ) : parser = subparsers . add_parser ( 'intersect' , description = constants . INTERSECT_DESCRIPTION , epilog = constants . INTERSECT_EPILOG , formatter_class = ParagraphFormatter , help = constants . INTERSECT_HELP ) parser . set_defaults ( func = ngram_intersection ) util...
Adds a sub - command parser to subparsers to make an intersection query .
48,341
def generate_lifetime_subparser ( subparsers ) : parser = subparsers . add_parser ( 'lifetime' , description = constants . LIFETIME_DESCRIPTION , epilog = constants . LIFETIME_EPILOG , formatter_class = ParagraphFormatter , help = constants . LIFETIME_HELP ) parser . set_defaults ( func = lifetime_report ) utils . add_...
Adds a sub - command parser to subparsers to make a lifetime report .
48,342
def generate_ngrams ( args , parser ) : store = utils . get_data_store ( args ) corpus = utils . get_corpus ( args ) if args . catalogue : catalogue = utils . get_catalogue ( args ) else : catalogue = None store . add_ngrams ( corpus , args . min_size , args . max_size , catalogue )
Adds n - grams data to the data store .
48,343
def generate_ngrams_subparser ( subparsers ) : parser = subparsers . add_parser ( 'ngrams' , description = constants . NGRAMS_DESCRIPTION , epilog = constants . NGRAMS_EPILOG , formatter_class = ParagraphFormatter , help = constants . NGRAMS_HELP ) parser . set_defaults ( func = generate_ngrams ) utils . add_common_arg...
Adds a sub - command parser to subparsers to add n - grams data to the data store .
48,344
def generate_prepare_subparser ( subparsers ) : parser = subparsers . add_parser ( 'prepare' , description = constants . PREPARE_DESCRIPTION , epilog = constants . PREPARE_EPILOG , formatter_class = ParagraphFormatter , help = constants . PREPARE_HELP ) parser . set_defaults ( func = prepare_xml ) utils . add_common_ar...
Adds a sub - command parser to subparsers to prepare source XML files for stripping .
48,345
def generate_search_subparser ( subparsers ) : parser = subparsers . add_parser ( 'search' , description = constants . SEARCH_DESCRIPTION , epilog = constants . SEARCH_EPILOG , formatter_class = ParagraphFormatter , help = constants . SEARCH_HELP ) parser . set_defaults ( func = search_texts ) utils . add_common_argume...
Adds a sub - command parser to subparsers to generate search results for a set of n - grams .
48,346
def generate_statistics_subparser ( subparsers ) : parser = subparsers . add_parser ( 'stats' , description = constants . STATISTICS_DESCRIPTION , formatter_class = ParagraphFormatter , help = constants . STATISTICS_HELP ) parser . set_defaults ( func = generate_statistics ) utils . add_common_arguments ( parser ) util...
Adds a sub - command parser to subparsers to generate statistics from a set of results .
48,347
def generate_strip_subparser ( subparsers ) : parser = subparsers . add_parser ( 'strip' , description = constants . STRIP_DESCRIPTION , epilog = constants . STRIP_EPILOG , formatter_class = ParagraphFormatter , help = constants . STRIP_HELP ) parser . set_defaults ( func = strip_files ) utils . add_common_arguments ( ...
Adds a sub - command parser to subparsers to process prepared files for use with the tacl ngrams command .
48,348
def generate_supplied_diff_subparser ( subparsers ) : parser = subparsers . add_parser ( 'sdiff' , description = constants . SUPPLIED_DIFF_DESCRIPTION , epilog = constants . SUPPLIED_DIFF_EPILOG , formatter_class = ParagraphFormatter , help = constants . SUPPLIED_DIFF_HELP ) parser . set_defaults ( func = supplied_diff...
Adds a sub - command parser to subparsers to run a diff query using the supplied results sets .
48,349
def generate_supplied_intersect_subparser ( subparsers ) : parser = subparsers . add_parser ( 'sintersect' , description = constants . SUPPLIED_INTERSECT_DESCRIPTION , epilog = constants . SUPPLIED_INTERSECT_EPILOG , formatter_class = ParagraphFormatter , help = constants . SUPPLIED_INTERSECT_HELP ) parser . set_defaul...
Adds a sub - command parser to subparsers to run an intersect query using the supplied results sets .
48,350
def highlight_text ( args , parser ) : tokenizer = utils . get_tokenizer ( args ) corpus = utils . get_corpus ( args ) output_dir = os . path . abspath ( args . output ) if os . path . exists ( output_dir ) : parser . exit ( status = 3 , message = 'Output directory already exists, ' 'aborting.\n' ) os . makedirs ( outp...
Outputs the result of highlighting a text .
48,351
def lifetime_report ( args , parser ) : catalogue = utils . get_catalogue ( args ) tokenizer = utils . get_tokenizer ( args ) results = tacl . Results ( args . results , tokenizer ) output_dir = os . path . abspath ( args . output ) os . makedirs ( output_dir , exist_ok = True ) report = tacl . LifetimeReport ( ) repor...
Generates a lifetime report .
48,352
def ngram_counts ( args , parser ) : store = utils . get_data_store ( args ) corpus = utils . get_corpus ( args ) catalogue = utils . get_catalogue ( args ) store . validate ( corpus , catalogue ) store . counts ( catalogue , sys . stdout )
Outputs the results of performing a counts query .
48,353
def ngram_diff ( args , parser ) : store = utils . get_data_store ( args ) corpus = utils . get_corpus ( args ) catalogue = utils . get_catalogue ( args ) tokenizer = utils . get_tokenizer ( args ) store . validate ( corpus , catalogue ) if args . asymmetric : store . diff_asymmetric ( catalogue , args . asymmetric , t...
Outputs the results of performing a diff query .
48,354
def ngram_intersection ( args , parser ) : store = utils . get_data_store ( args ) corpus = utils . get_corpus ( args ) catalogue = utils . get_catalogue ( args ) store . validate ( corpus , catalogue ) store . intersection ( catalogue , sys . stdout )
Outputs the results of performing an intersection query .
48,355
def prepare_xml ( args , parser ) : if args . source == constants . TEI_SOURCE_CBETA_GITHUB : corpus_class = tacl . TEICorpusCBETAGitHub else : raise Exception ( 'Unsupported TEI source option provided' ) corpus = corpus_class ( args . input , args . output ) corpus . tidy ( )
Prepares XML files for stripping .
48,356
def search_texts ( args , parser ) : store = utils . get_data_store ( args ) corpus = utils . get_corpus ( args ) catalogue = utils . get_catalogue ( args ) store . validate ( corpus , catalogue ) ngrams = [ ] for ngram_file in args . ngrams : ngrams . extend ( utils . get_ngrams ( ngram_file ) ) store . search ( catal...
Searches texts for presence of n - grams .
48,357
def strip_files ( args , parser ) : stripper = tacl . Stripper ( args . input , args . output ) stripper . strip_files ( )
Processes prepared XML files for use with the tacl ngrams command .
48,358
def http_meta_data ( self ) : for flow in self . input_stream : if flow [ 'direction' ] == 'CTS' : try : request = dpkt . http . Request ( flow [ 'payload' ] ) request_data = data_utils . make_dict ( request ) request_data [ 'uri' ] = self . _clean_uri ( request [ 'uri' ] ) flow [ 'http' ] = { 'type' : 'HTTP_REQUEST' ,...
Pull out the application metadata for each flow in the input_stream
48,359
def transport_meta_data ( self ) : for item in self . input_stream : trans_data = item [ 'packet' ] [ 'data' ] trans_type = self . _get_transport_type ( trans_data ) if trans_type and trans_data : item [ 'transport' ] = data_utils . make_dict ( trans_data ) item [ 'transport' ] [ 'type' ] = trans_type item [ 'transport...
Pull out the transport metadata for each packet in the input_stream
48,360
def _readable_flags ( transport ) : if 'flags' not in transport : return None _flag_list = [ ] flags = transport [ 'flags' ] if flags & dpkt . tcp . TH_SYN : if flags & dpkt . tcp . TH_ACK : _flag_list . append ( 'syn_ack' ) else : _flag_list . append ( 'syn' ) elif flags & dpkt . tcp . TH_FIN : if flags & dpkt . tcp ....
Method that turns bit flags into a human readable list
48,361
def _create_breakdown_chart ( self , data , work , output_dir ) : chart_data = data . loc [ work ] . sort_values ( by = SHARED , ascending = False ) [ [ SHARED , UNIQUE , COMMON ] ] csv_path = os . path . join ( output_dir , 'breakdown_{}.csv' . format ( work ) ) chart_data . to_csv ( csv_path )
Generates and writes to a file in output_dir the data used to display a stacked bar chart .
48,362
def _create_chord_chart ( self , data , works , output_dir ) : matrix = [ ] chord_data = data . unstack ( BASE_WORK ) [ SHARED ] for index , row_data in chord_data . fillna ( value = 0 ) . iterrows ( ) : matrix . append ( [ value / 100 for value in row_data ] ) colours = generate_colours ( len ( works ) ) colour_works ...
Generates and writes to a file in output_dir the data used to display a chord chart .
48,363
def _create_matrix_chart ( self , data , works , output_dir ) : nodes = [ { 'work' : work , 'group' : 1 } for work in works ] weights = data . stack ( ) . unstack ( RELATED_WORK ) . max ( ) seen = [ ] links = [ ] for ( source , target ) , weight in weights . iteritems ( ) : if target not in seen and target != source : ...
Generates and writes to a file in output_dir the data used to display a matrix chart .
48,364
def _create_related_chart ( self , data , work , output_dir ) : chart_data = data [ work ] . dropna ( ) . sort_values ( by = SHARED_RELATED_WORK , ascending = False ) csv_path = os . path . join ( output_dir , 'related_{}.csv' . format ( work ) ) chart_data . to_csv ( csv_path )
Generates and writes to a file in output_dir the data used to display a grouped bar chart .
48,365
def _drop_no_label_results ( self , results , fh ) : results . seek ( 0 ) results = Results ( results , self . _tokenizer ) results . remove_label ( self . _no_label ) results . csv ( fh )
Writes results to fh minus those results associated with the no label .
48,366
def _generate_statistics ( self , out_path , results_path ) : if not os . path . exists ( out_path ) : report = StatisticsReport ( self . _corpus , self . _tokenizer , results_path ) report . generate_statistics ( ) with open ( out_path , mode = 'w' , encoding = 'utf-8' , newline = '' ) as fh : report . csv ( fh )
Writes a statistics report for the results at results_path to out_path .
48,367
def _process_diff ( self , yes_work , maybe_work , work_dir , ym_results_path , yn_results_path , stats ) : distinct_results_path = os . path . join ( work_dir , 'distinct_{}.csv' . format ( maybe_work ) ) results = [ yn_results_path , ym_results_path ] labels = [ self . _no_label , self . _maybe_label ] self . _run_qu...
Returns statistics on the difference between the intersection of yes_work and maybe_work and the intersection of yes_work and no works .
48,368
def _process_intersection ( self , yes_work , maybe_work , work_dir , ym_results_path , stats ) : catalogue = { yes_work : self . _no_label , maybe_work : self . _maybe_label } self . _run_query ( ym_results_path , self . _store . intersection , [ catalogue ] , False ) return self . _update_stats ( 'intersect' , work_d...
Returns statistics on the intersection between yes_work and maybe_work .
48,369
def _process_maybe_work ( self , yes_work , maybe_work , work_dir , yn_results_path , stats ) : if maybe_work == yes_work : return stats self . _logger . info ( 'Processing "maybe" work {} against "yes" work {}.' . format ( maybe_work , yes_work ) ) for siglum in self . _corpus . get_sigla ( maybe_work ) : witness = ( ...
Returns statistics of how yes_work compares with maybe_work .
48,370
def _process_works ( self , maybe_works , no_works , output_dir ) : output_data_dir = os . path . join ( output_dir , 'data' ) no_catalogue = { work : self . _no_label for work in no_works } self . _ym_intersects_dir = os . path . join ( output_data_dir , 'ym_intersects' ) data = { } os . makedirs ( self . _ym_intersec...
Collect and return the data of how each work in maybe_works relates to each other work .
48,371
def _process_yes_work ( self , yes_work , no_catalogue , maybe_works , output_dir ) : self . _logger . info ( 'Processing "maybe" work {} as "yes".' . format ( yes_work ) ) stats = { COMMON : { } , SHARED : { } , UNIQUE : { } } yes_work_dir = os . path . join ( output_dir , yes_work ) os . makedirs ( yes_work_dir , exi...
Returns statistics of how yes_work compares with the other works in no_catalogue and the maybe works .
48,372
def _run_query ( self , path , query , query_args , drop_no = True ) : if os . path . exists ( path ) : return output_results = io . StringIO ( newline = '' ) query ( * query_args , output_fh = output_results ) with open ( path , mode = 'w' , encoding = 'utf-8' , newline = '' ) as fh : if drop_no : self . _drop_no_labe...
Runs query and outputs results to a file at path .
48,373
def _add_indices ( self ) : self . _logger . info ( 'Adding database indices' ) self . _conn . execute ( constants . CREATE_INDEX_TEXTNGRAM_SQL ) self . _logger . info ( 'Indices added' )
Adds the database indices relating to n - grams .
48,374
def add_ngrams ( self , corpus , minimum , maximum , catalogue = None ) : self . _initialise_database ( ) if catalogue : for work in catalogue : for witness in corpus . get_witnesses ( work ) : self . _add_text_ngrams ( witness , minimum , maximum ) else : for witness in corpus . get_witnesses ( ) : self . _add_text_ng...
Adds n - gram data from corpus to the data store .
48,375
def _add_temporary_ngrams ( self , ngrams ) : ngrams = [ ngram for ngram in ngrams if ngram and isinstance ( ngram , str ) ] seen = { } ngrams = [ seen . setdefault ( x , x ) for x in ngrams if x not in seen ] self . _conn . execute ( constants . DROP_TEMPORARY_NGRAMS_TABLE_SQL ) self . _conn . execute ( constants . CR...
Adds ngrams to a temporary table .
48,376
def _add_temporary_results ( self , results , label ) : NGRAM , SIZE , NAME , SIGLUM , COUNT , LABEL = constants . QUERY_FIELDNAMES reader = csv . DictReader ( results ) data = [ ( row [ NGRAM ] , row [ SIZE ] , row [ NAME ] , row [ SIGLUM ] , row [ COUNT ] , label ) for row in reader ] self . _conn . executemany ( con...
Adds results to a temporary table with label .
48,377
def _add_text_ngrams ( self , witness , minimum , maximum ) : text_id = self . _get_text_id ( witness ) self . _logger . info ( 'Adding n-grams ({} <= n <= {}) for {}' . format ( minimum , maximum , witness . get_filename ( ) ) ) skip_sizes = [ ] for size in range ( minimum , maximum + 1 ) : if self . _has_ngrams ( tex...
Adds n - gram data from witness to the data store .
48,378
def _add_text_record ( self , witness ) : filename = witness . get_filename ( ) name , siglum = witness . get_names ( ) self . _logger . info ( 'Adding record for text {}' . format ( filename ) ) checksum = witness . get_checksum ( ) token_count = len ( witness . get_tokens ( ) ) with self . _conn : cursor = self . _co...
Adds a Text record for witness .
48,379
def _add_text_size_ngrams ( self , text_id , size , ngrams ) : unique_ngrams = len ( ngrams ) self . _logger . info ( 'Adding {} unique {}-grams' . format ( unique_ngrams , size ) ) parameters = [ [ text_id , ngram , size , count ] for ngram , count in ngrams . items ( ) ] with self . _conn : self . _conn . execute ( c...
Adds ngrams that are of size size to the data store .
48,380
def _analyse ( self , table = '' ) : self . _logger . info ( 'Starting analysis of database' ) self . _conn . execute ( constants . ANALYSE_SQL . format ( table ) ) self . _logger . info ( 'Analysis of database complete' )
Analyses the database or table if it is supplied .
48,381
def _check_diff_result ( row , matches , tokenize , join ) : ngram_tokens = tokenize ( row [ constants . NGRAM_FIELDNAME ] ) sub_ngram1 = join ( ngram_tokens [ : - 1 ] ) sub_ngram2 = join ( ngram_tokens [ 1 : ] ) count = constants . COUNT_FIELDNAME discard = False status1 = matches . get ( sub_ngram1 ) if status1 == 0 ...
Returns row possibly with its count changed to 0 depending on the status of the n - grams that compose it .
48,382
def counts ( self , catalogue , output_fh ) : labels = list ( self . _set_labels ( catalogue ) ) label_placeholders = self . _get_placeholders ( labels ) query = constants . SELECT_COUNTS_SQL . format ( label_placeholders ) self . _logger . info ( 'Running counts query' ) self . _logger . debug ( 'Query: {}\nLabels: {}...
Returns output_fh populated with CSV results giving n - gram counts of the witnesses of the works in catalogue .
48,383
def _csv ( self , cursor , fieldnames , output_fh ) : self . _logger . info ( 'Finished query; outputting results in CSV format' ) if sys . platform in ( 'win32' , 'cygwin' ) and output_fh is sys . stdout : writer = csv . writer ( output_fh , lineterminator = '\n' ) else : writer = csv . writer ( output_fh ) writer . w...
Writes the rows of cursor in CSV format to output_fh and returns it .
48,384
def _csv_temp ( self , cursor , fieldnames ) : temp_fd , temp_path = tempfile . mkstemp ( text = True ) with open ( temp_fd , 'w' , encoding = 'utf-8' , newline = '' ) as results_fh : self . _csv ( cursor , fieldnames , results_fh ) return temp_path
Writes the rows of cursor in CSV format to a temporary file and returns the path to that file .
48,385
def _delete_text_ngrams ( self , text_id ) : with self . _conn : self . _conn . execute ( constants . DELETE_TEXT_NGRAMS_SQL , [ text_id ] ) self . _conn . execute ( constants . DELETE_TEXT_HAS_NGRAMS_SQL , [ text_id ] )
Deletes all n - grams associated with text_id from the data store .
48,386
def _diff ( self , cursor , tokenizer , output_fh ) : temp_path = self . _csv_temp ( cursor , constants . QUERY_FIELDNAMES ) output_fh = self . _reduce_diff_results ( temp_path , tokenizer , output_fh ) try : os . remove ( temp_path ) except OSError as e : self . _logger . error ( 'Failed to remove temporary file conta...
Returns output_fh with diff results that have been reduced .
48,387
def diff ( self , catalogue , tokenizer , output_fh ) : labels = self . _sort_labels ( self . _set_labels ( catalogue ) ) if len ( labels ) < 2 : raise MalformedQueryError ( constants . INSUFFICIENT_LABELS_QUERY_ERROR ) label_placeholders = self . _get_placeholders ( labels ) query = constants . SELECT_DIFF_SQL . forma...
Returns output_fh populated with CSV results giving the n - grams that are unique to the witnesses of each labelled set of works in catalogue .
48,388
def diff_asymmetric ( self , catalogue , prime_label , tokenizer , output_fh ) : labels = list ( self . _set_labels ( catalogue ) ) if len ( labels ) < 2 : raise MalformedQueryError ( constants . INSUFFICIENT_LABELS_QUERY_ERROR ) try : labels . remove ( prime_label ) except ValueError : raise MalformedQueryError ( cons...
Returns output_fh populated with CSV results giving the difference in n - grams between the witnesses of labelled sets of works in catalogue limited to those works labelled with prime_label .
48,389
def diff_supplied ( self , results_filenames , labels , tokenizer , output_fh ) : self . _add_temporary_results_sets ( results_filenames , labels ) query = constants . SELECT_DIFF_SUPPLIED_SQL self . _logger . info ( 'Running supplied diff query' ) self . _logger . debug ( 'Query: {}' . format ( query ) ) self . _log_q...
Returns output_fh populated with CSV results giving the n - grams that are unique to the witnesses in each set of works in results_sets using the labels in labels .
48,390
def _drop_indices ( self ) : self . _logger . info ( 'Dropping database indices' ) self . _conn . execute ( constants . DROP_TEXTNGRAM_INDEX_SQL ) self . _logger . info ( 'Finished dropping database indices' )
Drops the database indices relating to n - grams .
48,391
def _get_text_id ( self , witness ) : name , siglum = witness . get_names ( ) text_record = self . _conn . execute ( constants . SELECT_TEXT_SQL , [ name , siglum ] ) . fetchone ( ) if text_record is None : text_id = self . _add_text_record ( witness ) else : text_id = text_record [ 'id' ] if text_record [ 'checksum' ]...
Returns the database ID of the Text record for witness .
48,392
def _has_ngrams ( self , text_id , size ) : if self . _conn . execute ( constants . SELECT_HAS_NGRAMS_SQL , [ text_id , size ] ) . fetchone ( ) is None : return False return True
Returns True if a text has existing records for n - grams of size size .
48,393
def intersection ( self , catalogue , output_fh ) : labels = self . _sort_labels ( self . _set_labels ( catalogue ) ) if len ( labels ) < 2 : raise MalformedQueryError ( constants . INSUFFICIENT_LABELS_QUERY_ERROR ) label_placeholders = self . _get_placeholders ( labels ) subquery = self . _get_intersection_subquery ( ...
Returns output_fh populated with CSV results giving the intersection in n - grams of the witnesses of labelled sets of works in catalogue .
48,394
def intersection_supplied ( self , results_filenames , labels , output_fh ) : self . _add_temporary_results_sets ( results_filenames , labels ) query = constants . SELECT_INTERSECT_SUPPLIED_SQL parameters = [ len ( labels ) ] self . _logger . info ( 'Running supplied intersect query' ) self . _logger . debug ( 'Query: ...
Returns output_fh populated with CSV results giving the n - grams that are common to witnesses in every set of works in results_sets using the labels in labels .
48,395
def _reduce_diff_results ( self , matches_path , tokenizer , output_fh ) : self . _logger . info ( 'Removing filler results' ) tokenize = tokenizer . tokenize join = tokenizer . joiner . join results = [ ] previous_witness = ( None , None ) previous_data = { } ngram_index = constants . QUERY_FIELDNAMES . index ( consta...
Returns output_fh populated with a reduced set of data from matches_fh .
48,396
def search ( self , catalogue , ngrams , output_fh ) : labels = list ( self . _set_labels ( catalogue ) ) label_placeholders = self . _get_placeholders ( labels ) if ngrams : self . _add_temporary_ngrams ( ngrams ) query = constants . SELECT_SEARCH_SQL . format ( label_placeholders ) else : query = constants . SELECT_S...
Returns output_fh populated with CSV results for each n - gram in ngrams that occurs within labelled witnesses in catalogue .
48,397
def _set_labels ( self , catalogue ) : with self . _conn : self . _conn . execute ( constants . UPDATE_LABELS_SQL , [ '' ] ) labels = { } for work , label in catalogue . items ( ) : self . _conn . execute ( constants . UPDATE_LABEL_SQL , [ label , work ] ) cursor = self . _conn . execute ( constants . SELECT_TEXT_TOKEN...
Returns a dictionary of the unique labels in catalogue and the count of all tokens associated with each and sets the record of each Text to its corresponding label .
48,398
def _update_text_record ( self , witness , text_id ) : checksum = witness . get_checksum ( ) token_count = len ( witness . get_tokens ( ) ) with self . _conn : self . _conn . execute ( constants . UPDATE_TEXT_SQL , [ checksum , token_count , text_id ] )
Updates the record with text_id with witness \ s checksum and token count .
48,399
def validate ( self , corpus , catalogue ) : is_valid = True for name in catalogue : count = 0 for witness in corpus . get_witnesses ( name ) : count += 1 name , siglum = witness . get_names ( ) filename = witness . get_filename ( ) row = self . _conn . execute ( constants . SELECT_TEXT_SQL , [ name , siglum ] ) . fetc...
Returns True if all of the files labelled in catalogue are up - to - date in the database .