idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
54,000
def get_facet_objects_serializer ( self , * args , ** kwargs ) : facet_objects_serializer_class = self . get_facet_objects_serializer_class ( ) kwargs [ "context" ] = self . get_serializer_context ( ) return facet_objects_serializer_class ( * args , ** kwargs )
Return the serializer instance which should be used for serializing faceted objects .
54,001
def bind ( self , field_name , parent ) : assert self . source != field_name , ( "It is redundant to specify `source='%s'` on field '%s' in " "serializer '%s', because it is the same as the field name. " "Remove the `source` keyword argument." % ( field_name , self . __class__ . __name__ , parent . __class__ . __name__ ) ) self . field_name = field_name self . parent = parent if self . label is None : self . label = field_name . replace ( '_' , ' ' ) . capitalize ( ) if self . source is None : self . source = self . convert_field_name ( field_name ) if self . source == '*' : self . source_attrs = [ ] else : self . source_attrs = self . source . split ( '.' )
Initializes the field name and parent for the field instance . Called when a field is added to the parent serializer instance . Taken from DRF and modified to support drf_haystack multiple index functionality .
54,002
def _get_default_field_kwargs ( model , field ) : kwargs = { } try : field_name = field . model_attr or field . index_fieldname model_field = model . _meta . get_field ( field_name ) kwargs . update ( get_field_kwargs ( field_name , model_field ) ) delete_attrs = [ "allow_blank" , "choices" , "model_field" , "allow_unicode" , ] for attr in delete_attrs : if attr in kwargs : del kwargs [ attr ] except FieldDoesNotExist : pass return kwargs
Get the required attributes from the model field in order to instantiate a REST Framework serializer field .
54,003
def _get_index_class_name ( self , index_cls ) : cls_name = index_cls . __name__ aliases = self . Meta . index_aliases return aliases . get ( cls_name , cls_name . split ( '.' ) [ - 1 ] )
Converts in index model class to a name suitable for use as a field name prefix . A user may optionally specify custom aliases via an index_aliases attribute on the Meta class
54,004
def get_fields ( self ) : fields = self . Meta . fields exclude = self . Meta . exclude ignore_fields = self . Meta . ignore_fields indices = self . Meta . index_classes declared_fields = copy . deepcopy ( self . _declared_fields ) prefix_field_names = len ( indices ) > 1 field_mapping = OrderedDict ( ) for index_cls in self . Meta . index_classes : prefix = "" if prefix_field_names : prefix = "_%s__" % self . _get_index_class_name ( index_cls ) for field_name , field_type in six . iteritems ( index_cls . fields ) : orig_name = field_name field_name = "%s%s" % ( prefix , field_name ) if orig_name in ignore_fields or field_name in ignore_fields : continue if exclude : if orig_name in exclude or field_name in exclude : continue if fields : if orig_name not in fields and field_name not in fields : continue model = index_cls ( ) . get_model ( ) kwargs = self . _get_default_field_kwargs ( model , field_type ) kwargs [ 'prefix_field_names' ] = prefix_field_names field_mapping [ field_name ] = self . _field_mapping [ field_type ] ( ** kwargs ) if declared_fields : for field_name in declared_fields : field_mapping [ field_name ] = declared_fields [ field_name ] return field_mapping
Get the required fields for serializing the result .
54,005
def to_representation ( self , instance ) : if self . Meta . serializers : ret = self . multi_serializer_representation ( instance ) else : ret = super ( HaystackSerializer , self ) . to_representation ( instance ) prefix_field_names = len ( getattr ( self . Meta , "index_classes" ) ) > 1 current_index = self . _get_index_class_name ( type ( instance . searchindex ) ) for field in self . fields . keys ( ) : value_method = getattr ( self , "get_{}" . format ( field ) , None ) if value_method and callable ( value_method ) : ret [ field ] = value_method ( ) orig_field = field if prefix_field_names : parts = field . split ( "__" ) if len ( parts ) > 1 : index = parts [ 0 ] [ 1 : ] field = parts [ 1 ] if index == current_index : ret [ field ] = ret [ orig_field ] del ret [ orig_field ] elif field not in chain ( instance . searchindex . fields . keys ( ) , self . _declared_fields . keys ( ) ) : del ret [ orig_field ] if getattr ( instance , "highlighted" , None ) : ret [ "highlighted" ] = instance . highlighted [ 0 ] return ret
If we have a serializer mapping use that . Otherwise use standard serializer behavior Since we might be dealing with multiple indexes some fields might not be valid for all results . Do not render the fields which don t belong to the search result .
54,006
def get_narrow_url ( self , instance ) : text = instance [ 0 ] request = self . context [ "request" ] query_params = request . GET . copy ( ) page_query_param = self . get_paginate_by_param ( ) if page_query_param and page_query_param in query_params : del query_params [ page_query_param ] selected_facets = set ( query_params . pop ( self . root . facet_query_params_text , [ ] ) ) selected_facets . add ( "%(field)s_exact:%(text)s" % { "field" : self . parent_field , "text" : text } ) query_params . setlist ( self . root . facet_query_params_text , sorted ( selected_facets ) ) path = "%(path)s?%(query)s" % { "path" : request . path_info , "query" : query_params . urlencode ( ) } url = request . build_absolute_uri ( path ) return serializers . Hyperlink ( url , "narrow-url" )
Return a link suitable for narrowing on the current item .
54,007
def to_representation ( self , field , instance ) : self . parent_field = field return super ( FacetFieldSerializer , self ) . to_representation ( instance )
Set the parent_field property equal to the current field on the serializer class so that each field can query it to see what kind of attribute they are processing .
54,008
def get_fields ( self ) : field_mapping = OrderedDict ( ) for field , data in self . instance . items ( ) : field_mapping . update ( { field : self . facet_dict_field_class ( child = self . facet_list_field_class ( child = self . facet_field_serializer_class ( data ) ) , required = False ) } ) if self . serialize_objects is True : field_mapping [ "objects" ] = serializers . SerializerMethodField ( ) return field_mapping
This returns a dictionary containing the top most fields dates fields and queries .
54,009
def get_objects ( self , instance ) : view = self . context [ "view" ] queryset = self . context [ "objects" ] page = view . paginate_queryset ( queryset ) if page is not None : serializer = view . get_facet_objects_serializer ( page , many = True ) return OrderedDict ( [ ( "count" , self . get_count ( queryset ) ) , ( "next" , view . paginator . get_next_link ( ) ) , ( "previous" , view . paginator . get_previous_link ( ) ) , ( "results" , serializer . data ) ] ) serializer = view . get_serializer ( queryset , many = True ) return serializer . data
Return a list of objects matching the faceted result .
54,010
def get_document_field ( instance ) : for name , field in instance . searchindex . fields . items ( ) : if field . document is True : return name
Returns which field the search index has marked as it s document = True field .
54,011
def apply_filters ( self , queryset , applicable_filters = None , applicable_exclusions = None ) : if applicable_filters : queryset = queryset . filter ( applicable_filters ) if applicable_exclusions : queryset = queryset . exclude ( applicable_exclusions ) return queryset
Apply constructed filters and excludes and return the queryset
54,012
def build_filters ( self , view , filters = None ) : query_builder = self . get_query_builder ( backend = self , view = view ) return query_builder . build_query ( ** ( filters if filters else { } ) )
Get the query builder instance and return constructed query filters .
54,013
def filter_queryset ( self , request , queryset , view ) : applicable_filters , applicable_exclusions = self . build_filters ( view , filters = self . get_request_filters ( request ) ) return self . apply_filters ( queryset = queryset , applicable_filters = self . process_filters ( applicable_filters , queryset , view ) , applicable_exclusions = self . process_filters ( applicable_exclusions , queryset , view ) )
Return the filtered queryset .
54,014
def get_query_builder ( self , * args , ** kwargs ) : query_builder = self . get_query_builder_class ( ) return query_builder ( * args , ** kwargs )
Return the query builder class instance that should be used to build the query which is passed to the search engine backend .
54,015
def apply_filters ( self , queryset , applicable_filters = None , applicable_exclusions = None ) : for field , options in applicable_filters [ "field_facets" ] . items ( ) : queryset = queryset . facet ( field , ** options ) for field , options in applicable_filters [ "date_facets" ] . items ( ) : queryset = queryset . date_facet ( field , ** options ) for field , options in applicable_filters [ "query_facets" ] . items ( ) : queryset = queryset . query_facet ( field , ** options ) return queryset
Apply faceting to the queryset
54,016
def __convert_to_df ( a , val_col = None , group_col = None , val_id = None , group_id = None ) : if not group_col : group_col = 'groups' if not val_col : val_col = 'vals' if isinstance ( a , DataFrame ) : x = a . copy ( ) if not { group_col , val_col } . issubset ( a . columns ) : raise ValueError ( 'Specify correct column names using `group_col` and `val_col` args' ) return x , val_col , group_col elif isinstance ( a , list ) or ( isinstance ( a , np . ndarray ) and not a . shape . count ( 2 ) ) : grps_len = map ( len , a ) grps = list ( it . chain ( * [ [ i + 1 ] * l for i , l in enumerate ( grps_len ) ] ) ) vals = list ( it . chain ( * a ) ) return DataFrame ( { val_col : vals , group_col : grps } ) , val_col , group_col elif isinstance ( a , np . ndarray ) : if not ( all ( [ val_id , group_id ] ) ) : if np . argmax ( a . shape ) : a = a . T ax = [ np . unique ( a [ : , 0 ] ) . size , np . unique ( a [ : , 1 ] ) . size ] if np . asscalar ( np . diff ( ax ) ) : __val_col = np . argmax ( ax ) __group_col = np . argmin ( ax ) else : raise ValueError ( 'Cannot infer input format.\nPlease specify `val_id` and `group_id` args' ) cols = { __val_col : val_col , __group_col : group_col } else : cols = { val_id : val_col , group_id : group_col } cols_vals = dict ( sorted ( cols . items ( ) ) ) . values ( ) return DataFrame ( a , columns = cols_vals ) , val_col , group_col
Hidden helper method to create a DataFrame with input data for further processing .
54,017
def posthoc_tukey_hsd ( x , g , alpha = 0.05 ) : result = pairwise_tukeyhsd ( x , g , alpha = 0.05 ) groups = np . array ( result . groupsunique , dtype = np . str ) groups_len = len ( groups ) vs = np . zeros ( ( groups_len , groups_len ) , dtype = np . int ) for a in result . summary ( ) [ 1 : ] : a0 = str ( a [ 0 ] ) a1 = str ( a [ 1 ] ) a0i = np . where ( groups == a0 ) [ 0 ] [ 0 ] a1i = np . where ( groups == a1 ) [ 0 ] [ 0 ] vs [ a0i , a1i ] = 1 if str ( a [ 5 ] ) == 'True' else 0 vs = np . triu ( vs ) np . fill_diagonal ( vs , - 1 ) tri_lower = np . tril_indices ( vs . shape [ 0 ] , - 1 ) vs [ tri_lower ] = vs . T [ tri_lower ] return DataFrame ( vs , index = groups , columns = groups )
Pairwise comparisons with TukeyHSD confidence intervals . This is a convenience function to make statsmodels pairwise_tukeyhsd method more applicable for further use .
54,018
def posthoc_mannwhitney ( a , val_col = None , group_col = None , use_continuity = True , alternative = 'two-sided' , p_adjust = None , sort = True ) : x , _val_col , _group_col = __convert_to_df ( a , val_col , group_col ) if not sort : x [ _group_col ] = Categorical ( x [ _group_col ] , categories = x [ _group_col ] . unique ( ) , ordered = True ) x . sort_values ( by = [ _group_col , _val_col ] , ascending = True , inplace = True ) groups = np . unique ( x [ _group_col ] ) x_len = groups . size vs = np . zeros ( ( x_len , x_len ) ) tri_upper = np . triu_indices ( vs . shape [ 0 ] , 1 ) tri_lower = np . tril_indices ( vs . shape [ 0 ] , - 1 ) vs [ : , : ] = 0 combs = it . combinations ( range ( x_len ) , 2 ) for i , j in combs : vs [ i , j ] = ss . mannwhitneyu ( x . loc [ x [ _group_col ] == groups [ i ] , _val_col ] , x . loc [ x [ _group_col ] == groups [ j ] , _val_col ] , use_continuity = use_continuity , alternative = alternative ) [ 1 ] if p_adjust : vs [ tri_upper ] = multipletests ( vs [ tri_upper ] , method = p_adjust ) [ 1 ] vs [ tri_lower ] = vs . T [ tri_lower ] np . fill_diagonal ( vs , - 1 ) return DataFrame ( vs , index = groups , columns = groups )
Pairwise comparisons with Mann - Whitney rank test .
54,019
def posthoc_wilcoxon ( a , val_col = None , group_col = None , zero_method = 'wilcox' , correction = False , p_adjust = None , sort = False ) : x , _val_col , _group_col = __convert_to_df ( a , val_col , group_col ) if not sort : x [ _group_col ] = Categorical ( x [ _group_col ] , categories = x [ _group_col ] . unique ( ) , ordered = True ) groups = np . unique ( x [ _group_col ] ) x_len = groups . size vs = np . zeros ( ( x_len , x_len ) ) tri_upper = np . triu_indices ( vs . shape [ 0 ] , 1 ) tri_lower = np . tril_indices ( vs . shape [ 0 ] , - 1 ) vs [ : , : ] = 0 combs = it . combinations ( range ( x_len ) , 2 ) for i , j in combs : vs [ i , j ] = ss . wilcoxon ( x . loc [ x [ _group_col ] == groups [ i ] , _val_col ] , x . loc [ x [ _group_col ] == groups [ j ] , _val_col ] , zero_method = zero_method , correction = correction ) [ 1 ] if p_adjust : vs [ tri_upper ] = multipletests ( vs [ tri_upper ] , method = p_adjust ) [ 1 ] vs [ tri_lower ] = vs . T [ tri_lower ] np . fill_diagonal ( vs , - 1 ) return DataFrame ( vs , index = groups , columns = groups )
Pairwise comparisons with Wilcoxon signed - rank test . It is a non - parametric version of the paired T - test for use with non - parametric ANOVA .
54,020
def shutdown_waits_for ( coro , loop = None ) : loop = loop or get_event_loop ( ) fut = loop . create_future ( ) async def coro_proxy ( ) : try : result = await coro except ( CancelledError , Exception ) as e : set_fut_done = partial ( fut . set_exception , e ) else : set_fut_done = partial ( fut . set_result , result ) if not fut . cancelled ( ) : set_fut_done ( ) new_coro = coro_proxy ( ) _DO_NOT_CANCEL_COROS . add ( new_coro ) loop . create_task ( new_coro ) async def inner ( ) : return await fut return inner ( )
Prevent coro from being cancelled during the shutdown sequence .
54,021
def run ( coro : 'Optional[Coroutine]' = None , * , loop : Optional [ AbstractEventLoop ] = None , shutdown_handler : Optional [ Callable [ [ AbstractEventLoop ] , None ] ] = None , executor_workers : int = 10 , executor : Optional [ Executor ] = None , use_uvloop : bool = False ) -> None : logger . debug ( 'Entering run()' ) assert not ( loop and use_uvloop ) , ( "'loop' and 'use_uvloop' parameters are mutually " "exclusive. (Just make your own uvloop and pass it in)." ) if use_uvloop : import uvloop asyncio . set_event_loop_policy ( uvloop . EventLoopPolicy ( ) ) loop_was_supplied = bool ( loop ) if not loop_was_supplied : loop = get_event_loop ( ) if coro : async def new_coro ( ) : try : await coro except asyncio . CancelledError : pass loop . create_task ( new_coro ( ) ) shutdown_handler = shutdown_handler or _shutdown_handler if WINDOWS : loop . create_task ( windows_support_wakeup ( ) ) def windows_handler ( sig , frame ) : signame = signal . Signals ( sig ) . name logger . critical ( 'Received signal: %s. Stopping the loop.' , signame ) shutdown_handler ( loop ) signal . signal ( signal . SIGBREAK , windows_handler ) signal . signal ( signal . SIGINT , windows_handler ) else : loop . add_signal_handler ( SIGINT , shutdown_handler , loop ) loop . add_signal_handler ( SIGTERM , shutdown_handler , loop ) if not executor : logger . debug ( 'Creating default executor' ) executor = ThreadPoolExecutor ( max_workers = executor_workers ) loop . set_default_executor ( executor ) try : loop . run_forever ( ) except KeyboardInterrupt : logger . info ( 'Got KeyboardInterrupt' ) if WINDOWS : shutdown_handler ( ) logger . info ( 'Entering shutdown phase.' ) def sep ( ) : tasks = all_tasks ( loop = loop ) do_not_cancel = set ( ) for t in tasks : if t . _coro in _DO_NOT_CANCEL_COROS : do_not_cancel . add ( t ) tasks -= do_not_cancel logger . info ( 'Cancelling pending tasks.' ) for t in tasks : logger . debug ( 'Cancelling task: %s' , t ) t . cancel ( ) return tasks , do_not_cancel tasks , do_not_cancel = sep ( ) group = gather ( * tasks , * do_not_cancel , return_exceptions = True ) logger . info ( 'Running pending tasks till complete' ) loop . run_until_complete ( group ) logger . info ( 'Waiting for executor shutdown.' ) executor . shutdown ( wait = True ) if not loop_was_supplied : logger . info ( 'Closing the loop.' ) loop . close ( ) logger . critical ( 'Leaving. Bye!' )
Start up the event loop and wait for a signal to shut down .
54,022
def command ( self , * args , ** kwargs ) : if len ( args ) == 1 and isinstance ( args [ 0 ] , collections . Callable ) : return self . _generate_command ( args [ 0 ] ) else : def _command ( func ) : return self . _generate_command ( func , * args , ** kwargs ) return _command
Convenient decorator simply creates corresponding command
54,023
def _generate_command ( self , func , name = None , ** kwargs ) : func_pointer = name or func . __name__ storm_config = get_storm_config ( ) aliases , additional_kwarg = None , None if 'aliases' in storm_config : for command , alias_list in six . iteritems ( storm_config . get ( "aliases" ) ) : if func_pointer == command : aliases = alias_list break func_help = func . __doc__ and func . __doc__ . strip ( ) subparser = self . subparsers . add_parser ( name or func . __name__ , aliases = aliases , help = func_help ) spec = inspect . getargspec ( func ) opts = reversed ( list ( izip_longest ( reversed ( spec . args or [ ] ) , reversed ( spec . defaults or [ ] ) , fillvalue = self . _POSITIONAL ( ) ) ) ) for k , v in opts : argopts = getattr ( func , 'argopts' , { } ) args , kwargs = argopts . get ( k , ( [ ] , { } ) ) args = list ( args ) is_positional = isinstance ( v , self . _POSITIONAL ) options = [ arg for arg in args if arg . startswith ( '-' ) ] if isinstance ( v , list ) : kwargs . update ( { 'action' : 'append' , } ) if is_positional : if options : args = options kwargs . update ( { 'required' : True , 'dest' : k } ) else : args = [ k ] else : args = options or [ '--%s' % k ] kwargs . update ( { 'default' : v , 'dest' : k } ) arg = subparser . add_argument ( * args , ** kwargs ) subparser . set_defaults ( ** { self . _COMMAND_FLAG : func } ) return func
Generates a command parser for given func .
54,024
def execute ( self , arg_list ) : arg_map = self . parser . parse_args ( arg_list ) . __dict__ command = arg_map . pop ( self . _COMMAND_FLAG ) return command ( ** arg_map )
Main function to parse and dispatch commands by given arg_list
54,025
def add ( name , connection_uri , id_file = "" , o = [ ] , config = None ) : storm_ = get_storm_instance ( config ) try : if '@' in name : raise ValueError ( 'invalid value: "@" cannot be used in name.' ) user , host , port = parse ( connection_uri , user = get_default ( "user" , storm_ . defaults ) , port = get_default ( "port" , storm_ . defaults ) ) storm_ . add_entry ( name , host , user , port , id_file , o ) print ( get_formatted_message ( '{0} added to your ssh config. you can connect ' 'it by typing "ssh {0}".' . format ( name ) , 'success' ) ) except ValueError as error : print ( get_formatted_message ( error , 'error' ) , file = sys . stderr ) sys . exit ( 1 )
Adds a new entry to sshconfig .
54,026
def clone ( name , clone_name , config = None ) : storm_ = get_storm_instance ( config ) try : if '@' in name : raise ValueError ( 'invalid value: "@" cannot be used in name.' ) storm_ . clone_entry ( name , clone_name ) print ( get_formatted_message ( '{0} added to your ssh config. you can connect ' 'it by typing "ssh {0}".' . format ( clone_name ) , 'success' ) ) except ValueError as error : print ( get_formatted_message ( error , 'error' ) , file = sys . stderr ) sys . exit ( 1 )
Clone an entry to the sshconfig .
54,027
def move ( name , entry_name , config = None ) : storm_ = get_storm_instance ( config ) try : if '@' in name : raise ValueError ( 'invalid value: "@" cannot be used in name.' ) storm_ . clone_entry ( name , entry_name , keep_original = False ) print ( get_formatted_message ( '{0} moved in ssh config. you can ' 'connect it by typing "ssh {0}".' . format ( entry_name ) , 'success' ) ) except ValueError as error : print ( get_formatted_message ( error , 'error' ) , file = sys . stderr ) sys . exit ( 1 )
Move an entry to the sshconfig .
54,028
def edit ( name , connection_uri , id_file = "" , o = [ ] , config = None ) : storm_ = get_storm_instance ( config ) try : if ',' in name : name = " " . join ( name . split ( "," ) ) user , host , port = parse ( connection_uri , user = get_default ( "user" , storm_ . defaults ) , port = get_default ( "port" , storm_ . defaults ) ) storm_ . edit_entry ( name , host , user , port , id_file , o ) print ( get_formatted_message ( '"{0}" updated successfully.' . format ( name ) , 'success' ) ) except ValueError as error : print ( get_formatted_message ( error , 'error' ) , file = sys . stderr ) sys . exit ( 1 )
Edits the related entry in ssh config .
54,029
def update ( name , connection_uri = "" , id_file = "" , o = [ ] , config = None ) : storm_ = get_storm_instance ( config ) settings = { } if id_file != "" : settings [ 'identityfile' ] = id_file for option in o : k , v = option . split ( "=" ) settings [ k ] = v try : storm_ . update_entry ( name , ** settings ) print ( get_formatted_message ( '"{0}" updated successfully.' . format ( name ) , 'success' ) ) except ValueError as error : print ( get_formatted_message ( error , 'error' ) , file = sys . stderr ) sys . exit ( 1 )
Enhanced version of the edit command featuring multiple edits using regular expressions to match entries
54,030
def delete ( name , config = None ) : storm_ = get_storm_instance ( config ) try : storm_ . delete_entry ( name ) print ( get_formatted_message ( 'hostname "{0}" deleted successfully.' . format ( name ) , 'success' ) ) except ValueError as error : print ( get_formatted_message ( error , 'error' ) , file = sys . stderr ) sys . exit ( 1 )
Deletes a single host .
54,031
def list ( config = None ) : storm_ = get_storm_instance ( config ) try : result = colored ( 'Listing entries:' , 'white' , attrs = [ "bold" , ] ) + "\n\n" result_stack = "" for host in storm_ . list_entries ( True ) : if host . get ( "type" ) == 'entry' : if not host . get ( "host" ) == "*" : result += " {0} -> {1}@{2}:{3}" . format ( colored ( host [ "host" ] , 'green' , attrs = [ "bold" , ] ) , host . get ( "options" ) . get ( "user" , get_default ( "user" , storm_ . defaults ) ) , host . get ( "options" ) . get ( "hostname" , "[hostname_not_specified]" ) , host . get ( "options" ) . get ( "port" , get_default ( "port" , storm_ . defaults ) ) ) extra = False for key , value in six . iteritems ( host . get ( "options" ) ) : if not key in [ "user" , "hostname" , "port" ] : if not extra : custom_options = colored ( '\n\t[custom options] ' , 'white' ) result += " {0}" . format ( custom_options ) extra = True if isinstance ( value , collections . Sequence ) : if isinstance ( value , builtins . list ) : value = "," . join ( value ) result += "{0}={1} " . format ( key , value ) if extra : result = result [ 0 : - 1 ] result += "\n\n" else : result_stack = colored ( " (*) General options: \n" , "green" , attrs = [ "bold" , ] ) for key , value in six . iteritems ( host . get ( "options" ) ) : if isinstance ( value , type ( [ ] ) ) : result_stack += "\t {0}: " . format ( colored ( key , "magenta" ) ) result_stack += ', ' . join ( value ) result_stack += "\n" else : result_stack += "\t {0}: {1}\n" . format ( colored ( key , "magenta" ) , value , ) result_stack = result_stack [ 0 : - 1 ] + "\n" result += result_stack print ( get_formatted_message ( result , "" ) ) except Exception as error : print ( get_formatted_message ( str ( error ) , 'error' ) , file = sys . stderr ) sys . exit ( 1 )
Lists all hosts from ssh config .
54,032
def search ( search_text , config = None ) : storm_ = get_storm_instance ( config ) try : results = storm_ . search_host ( search_text ) if len ( results ) == 0 : print ( 'no results found.' ) if len ( results ) > 0 : message = 'Listing results for {0}:\n' . format ( search_text ) message += "" . join ( results ) print ( message ) except Exception as error : print ( get_formatted_message ( str ( error ) , 'error' ) , file = sys . stderr ) sys . exit ( 1 )
Searches entries by given search text .
54,033
def delete_all ( config = None ) : storm_ = get_storm_instance ( config ) try : storm_ . delete_all_entries ( ) print ( get_formatted_message ( 'all entries deleted.' , 'success' ) ) except Exception as error : print ( get_formatted_message ( str ( error ) , 'error' ) , file = sys . stderr ) sys . exit ( 1 )
Deletes all hosts from ssh config .
54,034
def backup ( target_file , config = None ) : storm_ = get_storm_instance ( config ) try : storm_ . backup ( target_file ) except Exception as error : print ( get_formatted_message ( str ( error ) , 'error' ) , file = sys . stderr ) sys . exit ( 1 )
Backups the main ssh configuration into target file .
54,035
def web ( port , debug = False , theme = "modern" , ssh_config = None ) : from storm import web as _web _web . run ( port , debug , theme , ssh_config )
Starts the web UI .
54,036
def _strip_list_attributes ( graph_ ) : for n_ in graph_ . nodes ( data = True ) : for k , v in n_ [ 1 ] . iteritems ( ) : if type ( v ) is list : graph_ . node [ n_ [ 0 ] ] [ k ] = unicode ( v ) for e_ in graph_ . edges ( data = True ) : for k , v in e_ [ 2 ] . iteritems ( ) : if type ( v ) is list : graph_ . edge [ e_ [ 0 ] ] [ e_ [ 1 ] ] [ k ] = unicode ( v ) return graph_
Converts lists attributes to strings for all nodes and edges in G .
54,037
def _safe_type ( value ) : if type ( value ) is str : dtype = 'string' if type ( value ) is unicode : dtype = 'string' if type ( value ) is int : dtype = 'integer' if type ( value ) is float : dtype = 'real' return dtype
Converts Python type names to XGMML - safe type names .
54,038
def read ( path , corpus = True , index_by = 'wosid' , streaming = False , parse_only = None , corpus_class = Corpus , ** kwargs ) : if not os . path . exists ( path ) : raise ValueError ( 'No such file or directory' ) if parse_only : parse_only . append ( index_by ) if streaming : return streaming_read ( path , corpus = corpus , index_by = index_by , parse_only = parse_only , ** kwargs ) if os . path . isdir ( path ) : papers = [ ] for sname in os . listdir ( path ) : if sname . endswith ( 'txt' ) and not sname . startswith ( '.' ) : papers += read ( os . path . join ( path , sname ) , corpus = False , parse_only = parse_only ) else : papers = WoSParser ( path ) . parse ( parse_only = parse_only ) if corpus : return corpus_class ( papers , index_by = index_by , ** kwargs ) return papers
Parse one or more WoS field - tagged data files .
54,039
def parse_author ( self , value ) : tokens = tuple ( [ t . upper ( ) . strip ( ) for t in value . split ( ',' ) ] ) if len ( tokens ) == 1 : tokens = value . split ( ' ' ) if len ( tokens ) > 0 : if len ( tokens ) > 1 : aulast , auinit = tokens [ 0 : 2 ] else : aulast = tokens [ 0 ] auinit = '' else : aulast , auinit = tokens [ 0 ] , '' aulast = _strip_punctuation ( aulast ) . upper ( ) auinit = _strip_punctuation ( auinit ) . upper ( ) return aulast , auinit
Attempts to split an author name into last and first parts .
54,040
def handle_CR ( self , value ) : citation = self . entry_class ( ) value = strip_tags ( value ) ptn = '([\w\s\W]+),\s([0-9]{4}),\s([\w\s]+)' ny_match = re . match ( ptn , value , flags = re . U ) nj_match = re . match ( '([\w\s\W]+),\s([\w\s]+)' , value , flags = re . U ) if ny_match is not None : name_raw , date , journal = ny_match . groups ( ) elif nj_match is not None : name_raw , journal = nj_match . groups ( ) date = None else : return datematch = re . match ( '([0-9]{4})' , value ) if datematch : date = datematch . group ( 1 ) name_raw = None if name_raw : name_tokens = [ t . replace ( '.' , '' ) for t in name_raw . split ( ' ' ) ] if len ( name_tokens ) > 4 or value . startswith ( '*' ) : proc = lambda x : _strip_punctuation ( x ) aulast = ' ' . join ( [ proc ( n ) for n in name_tokens ] ) . upper ( ) auinit = '' elif len ( name_tokens ) > 0 : aulast = name_tokens [ 0 ] . upper ( ) proc = lambda x : _space_sep ( _strip_punctuation ( x ) ) auinit = ' ' . join ( [ proc ( n ) for n in name_tokens [ 1 : ] ] ) . upper ( ) else : aulast = name_tokens [ 0 ] . upper ( ) auinit = '' setattr ( citation , 'authors_init' , [ ( aulast , auinit ) ] ) if date : date = int ( date ) setattr ( citation , 'date' , date ) setattr ( citation , 'journal' , journal ) v_match = re . search ( '\,\s+V([0-9A-Za-z]+)' , value ) if v_match is not None : volume = v_match . group ( 1 ) else : volume = None setattr ( citation , 'volume' , volume ) p_match = re . search ( '\,\s+[Pp]([0-9A-Za-z]+)' , value ) if p_match is not None : page = p_match . group ( 1 ) else : page = None setattr ( citation , 'pageStart' , page ) doi_match = re . search ( 'DOI\s(.*)' , value ) if doi_match is not None : doi = doi_match . group ( 1 ) else : doi = None setattr ( citation , 'doi' , doi ) return citation
Parses cited references .
54,041
def postprocess_WC ( self , entry ) : if type ( entry . WC ) not in [ str , unicode ] : WC = u' ' . join ( [ unicode ( k ) for k in entry . WC ] ) else : WC = entry . WC entry . WC = [ k . strip ( ) . upper ( ) for k in WC . split ( ';' ) ]
Parse WC keywords .
54,042
def postprocess_subject ( self , entry ) : if type ( entry . subject ) not in [ str , unicode ] : subject = u' ' . join ( [ unicode ( k ) for k in entry . subject ] ) else : subject = entry . subject entry . subject = [ k . strip ( ) . upper ( ) for k in subject . split ( ';' ) ]
Parse subject keywords .
54,043
def postprocess_authorKeywords ( self , entry ) : if type ( entry . authorKeywords ) not in [ str , unicode ] : aK = u' ' . join ( [ unicode ( k ) for k in entry . authorKeywords ] ) else : aK = entry . authorKeywords entry . authorKeywords = [ k . strip ( ) . upper ( ) for k in aK . split ( ';' ) ]
Parse author keywords .
54,044
def postprocess_keywordsPlus ( self , entry ) : if type ( entry . keywordsPlus ) in [ str , unicode ] : entry . keywordsPlus = [ k . strip ( ) . upper ( ) for k in entry . keywordsPlus . split ( ';' ) ]
Parse WoS Keyword Plus keywords .
54,045
def postprocess_funding ( self , entry ) : if type ( entry . funding ) not in [ str , unicode ] : return sources = [ fu . strip ( ) for fu in entry . funding . split ( ';' ) ] sources_processed = [ ] for source in sources : m = re . search ( '(.*)?\s+\[(.+)\]' , source ) if m : agency , grant = m . groups ( ) else : agency , grant = source , None sources_processed . append ( ( agency , grant ) ) entry . funding = sources_processed
Separates funding agency from grant numbers .
54,046
def postprocess_authors_full ( self , entry ) : if type ( entry . authors_full ) is not list : entry . authors_full = [ entry . authors_full ]
If only a single author was found ensure that authors_full is nonetheless a list .
54,047
def postprocess_authors_init ( self , entry ) : if type ( entry . authors_init ) is not list : entry . authors_init = [ entry . authors_init ]
If only a single author was found ensure that authors_init is nonetheless a list .
54,048
def postprocess_citedReferences ( self , entry ) : if type ( entry . citedReferences ) is not list : entry . citedReferences = [ entry . citedReferences ]
If only a single cited reference was found ensure that citedReferences is nonetheless a list .
54,049
def plot_burstness ( corpus , B , ** kwargs ) : try : import matplotlib . pyplot as plt import matplotlib . patches as mpatches except ImportError : raise RuntimeError ( 'This method requires the package matplotlib.' ) color = kwargs . get ( 'color' , 'red' ) years = sorted ( corpus . indices [ 'date' ] . keys ( ) ) width = years [ 1 ] - years [ 0 ] height = 1.0 fig = plt . figure ( figsize = ( 10 , len ( B ) / 4. ) ) f = 1 axes = { } for key , value in B . iteritems ( ) : x , y = value ax = fig . add_subplot ( len ( B ) , 1 , f ) f += 1 ax . set_yticks ( [ ] ) ax . set_xbound ( min ( years ) , max ( years ) + 1 ) if not f == len ( B ) + 1 : ax . set_xticklabels ( [ ] ) rect = mpatches . Rectangle ( ( min ( years ) , 0 ) , sorted ( x ) [ 0 ] - min ( years ) , height , fill = True , linewidth = 0.0 ) rect . set_facecolor ( 'black' ) rect . set_alpha ( 0.3 ) ax . add_patch ( rect ) for d in xrange ( min ( x ) , max ( x ) ) : try : i = x . index ( d ) except ValueError : continue xy = ( d , 0. ) state = y [ i ] rect = mpatches . Rectangle ( xy , width , height , fill = True , linewidth = 0.0 ) rect . set_facecolor ( color ) rect . set_alpha ( state ) ax . add_patch ( rect ) ax . set_ylabel ( key , rotation = 0 , horizontalalignment = 'right' , verticalalignment = 'center' ) plt . subplots_adjust ( left = 0.5 ) fig . tight_layout ( h_pad = 0.25 ) plt . show ( )
Generate a figure depicting burstness profiles for feature .
54,050
def simplify_multigraph ( multigraph , time = False ) : graph = nx . Graph ( ) for node in multigraph . nodes ( data = True ) : u = node [ 0 ] node_attribs = node [ 1 ] graph . add_node ( u , node_attribs ) for v in multigraph [ u ] : edges = multigraph . get_edge_data ( u , v ) edge_attribs = { 'weight' : len ( edges ) } if time : start = 3000 end = 0 found_date = False for edge in edges . values ( ) : try : found_date = True if edge [ 'date' ] < start : start = edge [ 'date' ] if edge [ 'date' ] > end : end = edge [ 'date' ] except KeyError : pass if found_date : edge_attribs [ 'start' ] = start edge_attribs [ 'end' ] = end graph . add_edge ( u , v , edge_attribs ) return graph
Simplifies a graph by condensing multiple edges between the same node pair into a single edge with a weight attribute equal to the number of edges .
54,051
def citation_count ( papers , key = 'ayjid' , verbose = False ) : if verbose : print "Generating citation counts for " + unicode ( len ( papers ) ) + " papers..." counts = Counter ( ) for P in papers : if P [ 'citations' ] is not None : for p in P [ 'citations' ] : counts [ p [ key ] ] += 1 return counts
Generates citation counts for all of the papers cited by papers .
54,052
def connected ( G , method_name , ** kwargs ) : warnings . warn ( "To be removed in 0.8. Use GraphCollection.analyze instead." , DeprecationWarning ) return G . analyze ( [ 'connected' , method_name ] , ** kwargs )
Performs analysis methods from networkx . connected on each graph in the collection .
54,053
def attachment_probability ( G ) : warnings . warn ( "Removed in 0.8. Too domain-specific." ) probs = { } G_ = None k_ = None for k , g in G . graphs . iteritems ( ) : new_edges = { } if G_ is not None : for n in g . nodes ( ) : try : old_neighbors = set ( G_ [ n ] . keys ( ) ) if len ( old_neighbors ) > 0 : new_neighbors = set ( g [ n ] . keys ( ) ) - old_neighbors new_edges [ n ] = float ( len ( new_neighbors ) ) else : new_edges [ n ] = 0. except KeyError : pass N = sum ( new_edges . values ( ) ) probs [ k_ ] = { n : 0. for n in G_ . nodes ( ) } if N > 0. : for n in G . nodes ( ) : try : probs [ k_ ] [ n ] = new_edges [ n ] / N except KeyError : pass if probs [ k_ ] is not None : networkx . set_node_attributes ( G . graphs [ k_ ] , 'attachment_probability' , probs [ k_ ] ) G_ = G k_ = k key = G . graphs . keys ( ) [ - 1 ] zprobs = { n : 0. for n in G . graphs [ key ] . nodes ( ) } networkx . set_node_attributes ( G . graphs [ key ] , 'attachment_probability' , zprobs ) return probs
Calculates the observed attachment probability for each node at each time - step . Attachment probability is calculated based on the observed new edges in the next time - step . So if a node acquires new edges at time t this will accrue to the node s attachment probability at time t - 1 . Thus at a given time one can ask whether degree and attachment probability are related .
54,054
def global_closeness_centrality ( g , node = None , normalize = True ) : if not node : C = { } for node in g . nodes ( ) : C [ node ] = global_closeness_centrality ( g , node , normalize = normalize ) return C values = nx . shortest_path_length ( g , node ) . values ( ) c = sum ( [ 1. / pl for pl in values if pl != 0. ] ) / len ( g ) if normalize : ac = 0 for sg in nx . connected_component_subgraphs ( g ) : if len ( sg . nodes ( ) ) > 1 : aspl = nx . average_shortest_path_length ( sg ) ac += ( 1. / aspl ) * ( float ( len ( sg ) ) / float ( len ( g ) ) ** 2 ) c = c / ac return c
Calculates global closeness centrality for one or all nodes in the network .
54,055
def ngrams ( path , elem , ignore_hash = True ) : grams = GramGenerator ( path , elem , ignore_hash = ignore_hash ) return FeatureSet ( { k : Feature ( f ) for k , f in grams } )
Yields N - grams from a JSTOR DfR dataset .
54,056
def tokenize ( ngrams , min_tf = 2 , min_df = 2 , min_len = 3 , apply_stoplist = False ) : vocab = { } vocab_ = { } word_tf = Counter ( ) word_df = Counter ( ) token_tf = Counter ( ) token_df = Counter ( ) t_ngrams = { } for grams in ngrams . values ( ) : for g , c in grams : word_tf [ g ] += c word_df [ g ] += 1 if apply_stoplist : stoplist = stopwords . words ( ) for doi , grams in ngrams . iteritems ( ) : t_ngrams [ doi ] = [ ] for g , c in grams : ignore = False if word_tf [ g ] < min_tf or word_df [ g ] < min_df or len ( g ) < min_len : ignore = True elif apply_stoplist : for w in g . split ( ) : if w in stoplist : ignore = True if not ignore : if type ( g ) is str : g = unicode ( g ) g = unidecode ( g ) if g not in vocab . values ( ) : i = len ( vocab ) vocab [ i ] = g vocab_ [ g ] = i else : i = vocab_ [ g ] token_tf [ i ] += c token_df [ i ] += 1 t_ngrams [ doi ] . append ( ( i , c ) ) return t_ngrams , vocab , token_tf
Builds a vocabulary and replaces words with vocab indices .
54,057
def _handle_pagerange ( pagerange ) : try : pr = re . compile ( "pp\.\s([0-9]+)\-([0-9]+)" ) start , end = re . findall ( pr , pagerange ) [ 0 ] except IndexError : start = end = 0 return unicode ( start ) , unicode ( end )
Yields start and end pages from DfR pagerange field .
54,058
def _handle_authors ( authors ) : aulast = [ ] auinit = [ ] if type ( authors ) is list : for author in authors : if type ( author ) is str : author = unicode ( author ) author = unidecode ( author ) try : l , i = _handle_author ( author ) aulast . append ( l ) auinit . append ( i ) except ValueError : pass elif type ( authors ) is str or type ( authors ) is unicode : if type ( authors ) is str : authors = unicode ( authors ) author = unidecode ( authors ) try : l , i = _handle_author ( author ) aulast . append ( l ) auinit . append ( i ) except ValueError : pass else : raise ValueError ( "authors must be a list or a string" ) return aulast , auinit
Yields aulast and auinit lists from value of authors node .
54,059
def _handle_author ( author ) : lname = author . split ( ' ' ) try : auinit = lname [ 0 ] [ 0 ] final = lname [ - 1 ] . upper ( ) if final in [ 'JR.' , 'III' ] : aulast = lname [ - 2 ] . upper ( ) + " " + final . strip ( "." ) else : aulast = final except IndexError : raise ValueError ( "malformed author name" ) return aulast , auinit
Yields aulast and auinit from an author s full name .
54,060
def _get ( self , i ) : with open ( os . path . join ( self . path , self . elem , self . files [ i ] ) , 'r' ) as f : contents = re . sub ( '(&)(?!amp;)' , lambda match : '&amp;' , f . read ( ) ) root = ET . fromstring ( contents ) doi = root . attrib [ 'id' ] if self . K : return doi grams = [ ] for gram in root . findall ( self . elem_xml ) : text = unidecode ( unicode ( gram . text . strip ( ) ) ) if ( not self . ignore_hash or '#' not in list ( text ) ) : c = ( text , number ( gram . attrib [ 'weight' ] ) ) grams . append ( c ) if self . V : return grams return doi , grams
Retrieve data for the ith file in the dataset .
54,061
def _generate_corpus ( self ) : target = self . temp + 'mallet' paths = write_documents ( self . corpus , target , self . featureset_name , [ 'date' , 'title' ] ) self . corpus_path , self . metapath = paths self . _export_corpus ( )
Writes a corpus to disk amenable to MALLET topic modeling .
54,062
def _export_corpus ( self ) : if not os . path . exists ( self . mallet_bin ) : raise IOError ( "MALLET path invalid or non-existent." ) self . input_path = os . path . join ( self . temp , "input.mallet" ) exit = subprocess . call ( [ self . mallet_bin , 'import-file' , '--input' , self . corpus_path , '--output' , self . input_path , '--keep-sequence' , '--remove-stopwords' ] ) if exit != 0 : msg = "MALLET import-file failed with exit code {0}." . format ( exit ) raise RuntimeError ( msg )
Calls MALLET s import - file method .
54,063
def run ( self , ** kwargs ) : if not os . path . exists ( self . mallet_bin ) : raise IOError ( "MALLET path invalid or non-existent." ) for attr in [ 'Z' , 'max_iter' ] : if not hasattr ( self , attr ) : raise AttributeError ( 'Please set {0}' . format ( attr ) ) self . ll = [ ] self . num_iters = 0 logger . debug ( 'run() with k={0} for {1} iterations' . format ( self . Z , self . max_iter ) ) prog = re . compile ( u'\<([^\)]+)\>' ) ll_prog = re . compile ( r'(\d+)' ) p = subprocess . Popen ( [ self . mallet_bin , 'train-topics' , '--input' , self . input_path , '--num-topics' , unicode ( self . Z ) , '--num-iterations' , unicode ( self . max_iter ) , '--output-doc-topics' , self . dt , '--word-topic-counts-file' , self . wt , '--output-model' , self . om ] , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) while p . poll ( ) is None : l = p . stderr . readline ( ) try : this_ll = float ( re . findall ( u'([-+]\d+\.\d+)' , l ) [ 0 ] ) self . ll . append ( this_ll ) except IndexError : pass try : this_iter = float ( prog . match ( l ) . groups ( ) [ 0 ] ) progress = int ( 100. * this_iter / self . max_iter ) print 'Modeling progress: {0}%.\r' . format ( progress ) , except AttributeError : pass self . num_iters += self . max_iter self . load ( )
Calls MALLET s train - topic method .
54,064
def topics_in ( self , d , topn = 5 ) : return self . theta . features [ d ] . top ( topn )
List the top topn topics in document d .
54,065
def list_topic ( self , k , Nwords = 10 ) : return [ ( self . vocabulary [ w ] , p ) for w , p in self . phi . features [ k ] . top ( Nwords ) ]
List the top topn words for topic k .
54,066
def list_topics ( self , Nwords = 10 ) : return [ ( k , self . list_topic ( k , Nwords ) ) for k in xrange ( len ( self . phi ) ) ]
List the top Nwords words for each topic .
54,067
def print_topics ( self , Nwords = 10 ) : print ( 'Topic\tTop %i words' % Nwords ) for k , words in self . list_topics ( Nwords ) : print ( unicode ( k ) . ljust ( 3 ) + '\t' + ' ' . join ( list ( zip ( * words ) ) [ 0 ] ) )
Print the top Nwords words for each topic .
54,068
def topic_over_time ( self , k , mode = 'counts' , slice_kwargs = { } ) : return self . corpus . feature_distribution ( 'topics' , k , mode = mode , ** slice_kwargs )
Calculate the representation of topic k in the corpus over time .
54,069
def distribution ( self , ** slice_kwargs ) : values = [ ] keys = [ ] for key , size in self . slice ( count_only = True , ** slice_kwargs ) : values . append ( size ) keys . append ( key ) return keys , values
Calculates the number of papers in each slice as defined by slice_kwargs .
54,070
def feature_distribution ( self , featureset_name , feature , mode = 'counts' , ** slice_kwargs ) : values = [ ] keys = [ ] fset = self . features [ featureset_name ] for key , papers in self . slice ( subcorpus = False , ** slice_kwargs ) : allfeatures = [ v for v in chain ( * [ fset . features [ self . _generate_index ( p ) ] for p in papers if self . _generate_index ( p ) in fset . features ] ) ] if len ( allfeatures ) < 1 : keys . append ( key ) values . append ( 0. ) continue count = 0. for elem , v in allfeatures : if elem != feature : continue if mode == 'counts' : count += v else : count += 1. values . append ( count ) keys . append ( key ) return keys , values
Calculates the distribution of a feature across slices of the corpus .
54,071
def top_features ( self , featureset_name , topn = 20 , by = 'counts' , perslice = False , slice_kwargs = { } ) : if perslice : return [ ( k , subcorpus . features [ featureset_name ] . top ( topn , by = by ) ) for k , subcorpus in self . slice ( ** slice_kwargs ) ] return self . features [ featureset_name ] . top ( topn , by = by )
Retrieves the top topn most numerous features in the corpus .
54,072
def feature_burstness ( corpus , featureset_name , feature , k = 5 , normalize = True , s = 1.1 , gamma = 1. , ** slice_kwargs ) : if featureset_name not in corpus . features : corpus . index_feature ( featureset_name ) if 'date' not in corpus . indices : corpus . index ( 'date' ) dates = [ min ( corpus . indices [ 'date' ] . keys ( ) ) - 1 ] X_ = [ 1. ] years , values = corpus . feature_distribution ( featureset_name , feature ) for year , N in izip ( years , values ) : if N == 0 : continue if N > 1 : if year == dates [ - 1 ] + 1 : for n in xrange ( int ( N ) ) : X_ . append ( 1. / N ) dates . append ( year ) else : X_ . append ( float ( year - dates [ - 1 ] ) ) dates . append ( year ) for n in xrange ( int ( N ) - 1 ) : X_ . append ( 1. / ( N - 1 ) ) dates . append ( year ) else : X_ . append ( float ( year - dates [ - 1 ] ) ) dates . append ( year ) st = _forward ( map ( lambda x : x * 100 , X_ ) , s = s , gamma = gamma , k = k ) A = defaultdict ( list ) for i in xrange ( len ( X_ ) ) : A [ dates [ i ] ] . append ( st [ i ] ) if normalize : A = { key : mean ( values ) / k for key , values in A . items ( ) } else : A = { key : mean ( values ) for key , values in A . items ( ) } D = sorted ( A . keys ( ) ) return D [ 1 : ] , [ A [ d ] for d in D [ 1 : ] ]
Estimate burstness profile for a feature over the date axis .
54,073
def cocitation ( corpus , min_weight = 1 , edge_attrs = [ 'ayjid' , 'date' ] , ** kwargs ) : return cooccurrence ( corpus , 'citations' , min_weight = min_weight , edge_attrs = edge_attrs , ** kwargs )
Generate a cocitation network .
54,074
def context_chunk ( self , context , j ) : N_chunks = len ( self . contexts [ context ] ) start = self . contexts [ context ] [ j ] if j == N_chunks - 1 : end = len ( self ) else : end = self . contexts [ context ] [ j + 1 ] return [ self [ i ] for i in xrange ( start , end ) ]
Retrieve the tokens in the j th chunk of context context .
54,075
def add_context ( self , name , indices , level = None ) : self . _validate_context ( ( name , indices ) ) if level is None : level = len ( self . contexts_ranked ) self . contexts_ranked . insert ( level , name ) self . contexts [ name ] = indices
Add a new context level to the hierarchy .
54,076
def index ( self , name , graph ) : nodes = graph . nodes ( ) new_nodes = list ( set ( nodes ) - set ( self . node_index . values ( ) ) ) start = max ( len ( self . node_index ) - 1 , max ( self . node_index . keys ( ) ) ) for i in xrange ( start , start + len ( new_nodes ) ) : n = new_nodes . pop ( ) self . node_index [ i ] , self . node_lookup [ n ] = n , i self . graphs_containing [ n ] . append ( name ) new_labels = { n : self . node_lookup [ n ] for n in nodes } indexed_graph = nx . relabel . relabel_nodes ( graph , new_labels , copy = True ) return indexed_graph
Index any new nodes in graph and relabel the nodes in graph using the index .
54,077
def terms ( model , threshold = 0.01 , ** kwargs ) : select = lambda f , v , c , dc : v > threshold graph = cooccurrence ( model . phi , filter = select , ** kwargs ) label_map = { k : v for k , v in model . vocabulary . items ( ) if k in graph . nodes ( ) } graph . name = '' return networkx . relabel_nodes ( graph , label_map )
Two terms are coupled if the posterior probability for both terms is greather than threshold for the same topic .
54,078
def topic_coupling ( model , threshold = None , ** kwargs ) : if not threshold : threshold = 3. / model . Z select = lambda f , v , c , dc : v > threshold graph = coupling ( model . corpus , 'topics' , filter = select , ** kwargs ) graph . name = '' return graph
Two papers are coupled if they both contain a shared topic above a threshold .
54,079
def kl_divergence ( V_a , V_b ) : Ndiff = _shared_features ( V_a , V_b ) aprob = map ( lambda v : float ( v ) / sum ( V_a ) , V_a ) bprob = map ( lambda v : float ( v ) / sum ( V_b ) , V_b ) aprob , bprob = _smooth ( aprob , bprob , Ndiff ) return sum ( map ( lambda a , b : ( a - b ) * log ( a / b ) , aprob , bprob ) )
Calculate Kullback - Leibler distance .
54,080
def _shared_features ( adense , bdense ) : a_indices = set ( nonzero ( adense ) ) b_indices = set ( nonzero ( bdense ) ) shared = list ( a_indices & b_indices ) diff = list ( a_indices - b_indices ) Ndiff = len ( diff ) return Ndiff
Number of features in adense that are also in bdense .
54,081
def cooccurrence ( corpus_or_featureset , featureset_name = None , min_weight = 1 , edge_attrs = [ 'ayjid' , 'date' ] , filter = None ) : if not filter : filter = lambda f , v , c , dc : dc >= min_weight featureset = _get_featureset ( corpus_or_featureset , featureset_name ) if type ( corpus_or_featureset ) in [ Corpus , StreamingCorpus ] : attributes = { i : { a : corpus_or_featureset . indices_lookup [ i ] [ a ] for a in edge_attrs } for i in corpus_or_featureset . indexed_papers . keys ( ) } c = lambda f : featureset . count ( f ) dc = lambda f : featureset . documentCount ( f ) attributes = { } if type ( featureset ) is FeatureSet : select = lambda feature : [ f for f , v in feature if filter ( f , v , c ( f ) , dc ( f ) ) ] elif type ( featureset ) is StructuredFeatureSet : select = lambda feature : [ f for f in feature if filter ( f , feature . count ( f ) , c ( f ) , dc ( f ) ) ] pairs = Counter ( ) eattrs = defaultdict ( dict ) nattrs = defaultdict ( dict ) nset = set ( ) for paper , feature in featureset . iteritems ( ) : if len ( feature ) == 0 : continue selected = select ( feature ) nset |= set ( selected ) for combo in combinations ( selected , 2 ) : combo = tuple ( sorted ( combo ) ) pairs [ combo ] += 1 if paper in attributes : eattrs [ combo ] = attributes [ paper ] for n in list ( nset ) : nattrs [ n ] [ 'count' ] = featureset . count ( n ) nattrs [ n ] [ 'documentCount' ] = featureset . documentCount ( n ) return _generate_graph ( nx . Graph , pairs , edge_attrs = eattrs , node_attrs = nattrs , min_weight = min_weight )
A network of feature elements linked by their joint occurrence in papers .
54,082
def coupling ( corpus_or_featureset , featureset_name = None , min_weight = 1 , filter = lambda f , v , c , dc : True , node_attrs = [ ] ) : featureset = _get_featureset ( corpus_or_featureset , featureset_name ) c = lambda f : featureset . count ( f ) dc = lambda f : featureset . documentCount ( f ) f = lambda elem : featureset . index [ elem ] v = lambda p , f : featureset . features [ p ] . value ( f ) select = lambda p , elem : filter ( f ( elem ) , v ( p , f ( elem ) ) , c ( f ( elem ) ) , dc ( f ( elem ) ) ) pairs = defaultdict ( list ) for elem , papers in featureset . with_feature . iteritems ( ) : selected = [ p for p in papers if select ( p , elem ) ] for combo in combinations ( selected , 2 ) : combo = tuple ( sorted ( combo ) ) pairs [ combo ] . append ( featureset . index [ elem ] ) graph = nx . Graph ( ) for combo , features in pairs . iteritems ( ) : count = len ( features ) if count >= min_weight : graph . add_edge ( combo [ 0 ] , combo [ 1 ] , features = features , weight = count ) for attr in node_attrs : for node in graph . nodes ( ) : value = '' if node in corpus_or_featureset : paper = corpus_or_featureset [ node ] if hasattr ( paper , attr ) : value = getattr ( paper , attr ) if value is None : value = '' elif callable ( value ) : value = value ( ) graph . node [ node ] [ attr ] = value return graph
A network of papers linked by their joint posession of features .
54,083
def multipartite ( corpus , featureset_names , min_weight = 1 , filters = { } ) : pairs = Counter ( ) node_type = { corpus . _generate_index ( p ) : { 'type' : 'paper' } for p in corpus . papers } for featureset_name in featureset_names : ftypes = { } featureset = _get_featureset ( corpus , featureset_name ) for paper , feature in featureset . iteritems ( ) : if featureset_name in filters : if not filters [ featureset_name ] ( featureset , feature ) : continue if len ( feature ) < 1 : continue for f in list ( zip ( * feature ) ) [ 0 ] : ftypes [ f ] = { 'type' : featureset_name } pairs [ ( paper , f ) ] += 1 node_type . update ( ftypes ) return _generate_graph ( nx . DiGraph , pairs , node_attrs = node_type , min_weight = min_weight )
A network of papers and one or more featuresets .
54,084
def _strip_punctuation ( s ) : if type ( s ) is str and not PYTHON_3 : return s . translate ( string . maketrans ( "" , "" ) , string . punctuation ) else : translate_table = dict ( ( ord ( char ) , u'' ) for char in u'!"#%\'()*+,-./:;<=>?@[\]^_`{|}~' ) return s . translate ( translate_table )
Removes all punctuation characters from a string .
54,085
def overlap ( listA , listB ) : if ( listA is None ) or ( listB is None ) : return [ ] else : return list ( set ( listA ) & set ( listB ) )
Return list of objects shared by listA listB .
54,086
def subdict ( super_dict , keys ) : sub_dict = { } valid_keys = super_dict . keys ( ) for key in keys : if key in valid_keys : sub_dict [ key ] = super_dict [ key ] return sub_dict
Returns a subset of the super_dict with the specified keys .
54,087
def concat_list ( listA , listB , delim = ' ' ) : if len ( listA ) != len ( listB ) : raise IndexError ( 'Input lists are not parallel.' ) listC = [ ] for i in xrange ( len ( listA ) ) : app = listA [ i ] + delim + listB [ i ] listC . append ( app ) return listC
Concatenate list elements pair - wise with the delim character Returns the concatenated list Raises index error if lists are not parallel
54,088
def strip_non_ascii ( s ) : stripped = ( c for c in s if 0 < ord ( c ) < 127 ) clean_string = u'' . join ( stripped ) return clean_string
Returns the string without non - ASCII characters .
54,089
def dict_from_node ( node , recursive = False ) : dict = { } for snode in node : if len ( snode ) > 0 : if recursive : value = dict_from_node ( snode , True ) else : value = len ( snode ) elif snode . text is not None : value = snode . text else : value = u'' if snode . tag in dict . keys ( ) : if type ( dict [ snode . tag ] ) is list : dict [ snode . tag ] . append ( value ) else : dict [ snode . tag ] = [ dict [ snode . tag ] , value ] else : dict [ snode . tag ] = value return dict
Converts ElementTree node to a dictionary .
54,090
def feed ( self , data ) : try : self . rawdata = self . rawdata + data except TypeError : data = unicode ( data ) self . rawdata = self . rawdata + data self . goahead ( 0 )
added this check as sometimes we are getting the data in integer format instead of string
54,091
def serializePaper ( self ) : pid = tethnedao . getMaxPaperID ( ) papers_details = [ ] for paper in self . corpus : pid = pid + 1 paper_key = getattr ( paper , Serialize . paper_source_map [ self . source ] ) self . paperIdMap [ paper_key ] = pid paper_data = { "model" : "django-tethne.paper" , "pk" : self . paperIdMap [ paper_key ] , "fields" : { "paper_id" : paper_key , "corpus" : self . corpus_id , "pub_date" : getattr ( paper , 'date' , '' ) , "volume" : getattr ( paper , 'volume' , '' ) , "title" : getattr ( paper , 'title' , '' ) , "abstract" : getattr ( paper , 'abstract' , '' ) , } } papers_details . append ( paper_data ) return papers_details
This method creates a fixture for the django - tethne_paper model .
54,092
def serializeCitation ( self ) : citation_details = [ ] citation_id = tethnedao . getMaxCitationID ( ) for citation in self . corpus . features [ 'citations' ] . index . values ( ) : date_match = re . search ( r'(\d+)' , citation ) if date_match is not None : date = date_match . group ( 1 ) if date_match is None : date_match = re . search ( r"NONE" , citation ) date = date_match . group ( ) first_author = citation . replace ( '_' , ' ' ) . split ( date ) [ 0 ] . rstrip ( ) journal = citation . replace ( '_' , ' ' ) . split ( date ) [ 1 ] . lstrip ( ) citation_key = citation if citation_key not in self . citationIdMap : citation_id += 1 self . citationIdMap [ citation_key ] = citation_id citation_data = { "model" : "django-tethne.citation" , "pk" : citation_id , "fields" : { "literal" : citation , "journal" : journal , "first_author" : first_author , "date" : date } } citation_details . append ( citation_data ) return citation_details
This method creates a fixture for the django - tethne_citation model .
54,093
def serializeInstitution ( self ) : institution_data = [ ] institution_instance_data = [ ] affiliation_data = [ ] affiliation_id = tethnedao . getMaxAffiliationID ( ) institution_id = tethnedao . getMaxInstitutionID ( ) institution_instance_id = tethnedao . getMaxInstitutionInstanceID ( ) for paper in self . corpus : if hasattr ( paper , 'authorAddress' ) : paper_key = getattr ( paper , Serialize . paper_source_map [ self . source ] ) if type ( paper . authorAddress ) is unicode : institution_id += 1 institution_instance_id += 1 institute_literal , authors = SerializeUtility . get_auth_inst ( paper . authorAddress ) institute_row , institute_instance_row = self . get_details_from_inst_literal ( institute_literal , institution_id , institution_instance_id , paper_key ) if institute_row : institution_data . append ( institute_row ) institution_instance_data . append ( institute_instance_row ) if authors : for author in authors : affiliation_id += 1 affiliation_row = self . get_affiliation_details ( author , affiliation_id , institute_literal ) affiliation_data . append ( affiliation_row ) elif type ( paper . authorAddress ) is list : for address in paper . authorAddress : institution_id += 1 institution_instance_id += 1 institute_literal , authors = SerializeUtility . get_auth_inst ( address ) institute_row , institute_instance_row = self . get_details_from_inst_literal ( institute_literal , institution_id , institution_instance_id , paper_key ) if institute_row : institution_data . append ( institute_row ) institution_instance_data . append ( institute_instance_row ) if authors is None : authors = prevAuthors for author in authors : affiliation_id += 1 affiliation_row = self . get_affiliation_details ( author , affiliation_id , institute_literal ) affiliation_data . append ( affiliation_row ) prevAuthors = authors return institution_data , institution_instance_data , affiliation_data
This method creates a fixture for the django - tethne_citation_institution model .
54,094
def get_details_from_inst_literal ( self , institute_literal , institution_id , institution_instance_id , paper_key ) : institute_details = institute_literal . split ( ',' ) institute_name = institute_details [ 0 ] country = institute_details [ len ( institute_details ) - 1 ] . lstrip ( ) . replace ( '.' , '' ) institute_row = None zipcode = "" state = "" city = "" if 'USA' in country : temp = country if ( len ( temp . split ( ) ) ) == 3 : country = temp . split ( ) [ 2 ] zipcode = temp . split ( ) [ 1 ] state = temp . split ( ) [ 0 ] elif ( len ( temp . split ( ) ) ) == 2 : country = temp . split ( ) [ 1 ] state = temp . split ( ) [ 0 ] city = institute_details [ len ( institute_details ) - 2 ] . lstrip ( ) addressline1 = "" for i in range ( 1 , len ( institute_details ) - 1 , 1 ) : if i != len ( institute_details ) - 2 : addressline1 = addressline1 + institute_details [ i ] + ',' else : addressline1 = addressline1 + institute_details [ i ] if institute_literal not in self . instituteIdMap : self . instituteIdMap [ institute_literal ] = institution_id institute_row = { "model" : "django-tethne.institution" , "pk" : institution_id , "fields" : { "institute_name" : institute_name , "addressLine1" : addressline1 , "country" : country , "zip" : zipcode , "state" : state , "city" : city } } department = "" if re . search ( 'Dept([^,]*),' , institute_literal ) is not None : department = re . search ( 'Dept([^,]*),' , institute_literal ) . group ( ) . replace ( ',' , '' ) institute_instance_row = { "model" : "django-tethne.institution_instance" , "pk" : institution_instance_id , "fields" : { "institution" : self . instituteIdMap [ institute_literal ] , "literal" : institute_literal , "institute_name" : institute_name , "addressLine1" : addressline1 , "country" : country , "paper" : self . paperIdMap [ paper_key ] , "department" : department , "zip" : zipcode , "state" : state , "city" : city } } return institute_row , institute_instance_row
This method parses the institute literal to get the following 1 . Department naame 2 . Country 3 . University name 4 . ZIP STATE AND CITY ( Only if the country is USA . For other countries the standard may vary . So parsing these values becomes very difficult . However the complete address can be found in the column AddressLine1
54,095
def get_affiliation_details ( self , value , affiliation_id , institute_literal ) : tokens = tuple ( [ t . upper ( ) . strip ( ) for t in value . split ( ',' ) ] ) if len ( tokens ) == 1 : tokens = value . split ( ) if len ( tokens ) > 0 : if len ( tokens ) > 1 : aulast , auinit = tokens [ 0 : 2 ] else : aulast = tokens [ 0 ] auinit = '' else : aulast , auinit = tokens [ 0 ] , '' aulast = _strip_punctuation ( aulast ) . upper ( ) auinit = _strip_punctuation ( auinit ) . upper ( ) author_key = auinit + aulast affiliation_row = { "model" : "django-tethne.affiliation" , "pk" : affiliation_id , "fields" : { "author" : self . authorIdMap [ author_key ] , "institution" : self . instituteIdMap [ institute_literal ] } } return affiliation_row
This method is used to map the Affiliation between an author and Institution .
54,096
def start ( self ) : while not self . is_start ( self . current_tag ) : self . next ( ) self . new_entry ( )
Find the first data entry and prepare to parse .
54,097
def handle ( self , tag , data ) : if self . is_end ( tag ) : self . postprocess_entry ( ) if self . is_start ( tag ) : self . new_entry ( ) if not data or not tag : return if getattr ( self , 'parse_only' , None ) and tag not in self . parse_only : return if isinstance ( data , unicode ) : data = unicodedata . normalize ( 'NFKD' , data ) handler = self . _get_handler ( tag ) if handler is not None : data = handler ( data ) if tag in self . tags : tag = self . tags [ tag ] if hasattr ( self . data [ - 1 ] , tag ) : value = getattr ( self . data [ - 1 ] , tag ) if tag in self . concat_fields : value = ' ' . join ( [ value , unicode ( data ) ] ) elif type ( value ) is list : value . append ( data ) elif value not in [ None , '' ] : value = [ value , data ] else : value = data setattr ( self . data [ - 1 ] , tag , value ) self . fields . add ( tag )
Process a single line of data and store the result .
54,098
def open ( self ) : if not os . path . exists ( self . path ) : raise IOError ( "No such path: {0}" . format ( self . path ) ) with open ( self . path , "rb" ) as f : msg = f . read ( ) result = chardet . detect ( msg ) self . buffer = codecs . open ( self . path , "rb" , encoding = result [ 'encoding' ] ) self . at_eof = False
Open the data file .
54,099
def next ( self ) : line = self . buffer . readline ( ) while line == '\n' : line = self . buffer . readline ( ) if line == '' : self . at_eof = True return None , None match = re . match ( '([A-Z]{2}|[C][1])\W(.*)' , line ) if match is not None : self . current_tag , data = match . groups ( ) else : self . current_tag = self . last_tag data = line . strip ( ) return self . current_tag , _cast ( data )
Get the next line of data .