idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
242,900
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 .
242,901
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...
Converts lists attributes to strings for all nodes and edges in G .
242,902
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 .
242,903
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...
Parse one or more WoS field - tagged data files .
242,904
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 =...
Attempts to split an author name into last and first parts .
242,905
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 , jou...
Parses cited references .
242,906
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 .
242,907
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 .
242,908
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 .
242,909
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 .
242,910
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 : ag...
Separates funding agency from grant numbers .
242,911
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 .
242,912
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 .
242,913
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 .
242,914
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 ( ) ) wi...
Generate a figure depicting burstness profiles for feature .
242,915
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 ...
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 .
242,916
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 .
242,917
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 .
242,918
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_neighb...
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 a...
242,919
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. ...
Calculates global closeness centrality for one or all nodes in the network .
242,920
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 .
242,921
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 ap...
Builds a vocabulary and replaces words with vocab indices .
242,922
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 .
242,923
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 (...
Yields aulast and auinit lists from value of authors node .
242,924
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...
Yields aulast and auinit from an author s full name .
242,925
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 : '&' , f . read ( ) ) root = ET . fromstring ( contents ) doi = root . attrib [ 'id' ] if self . K : return doi grams = [ ] for gram in root . fi...
Retrieve data for the ith file in the dataset .
242,926
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 .
242,927
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' , se...
Calls MALLET s import - file method .
242,928
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 ( ...
Calls MALLET s train - topic method .
242,929
def topics_in ( self , d , topn = 5 ) : return self . theta . features [ d ] . top ( topn )
List the top topn topics in document d .
242,930
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 .
242,931
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 .
242,932
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 .
242,933
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 .
242,934
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 .
242,935
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_inde...
Calculates the distribution of a feature across slices of the corpus .
242,936
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 ( to...
Retrieves the top topn most numerous features in the corpus .
242,937
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 [ 'da...
Estimate burstness profile for a feature over the date axis .
242,938
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 .
242,939
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 .
242,940
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 .
242,941
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...
Index any new nodes in graph and relabel the nodes in graph using the index .
242,942
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 , l...
Two terms are coupled if the posterior probability for both terms is greather than threshold for the same topic .
242,943
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 .
242,944
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 .
242,945
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 .
242,946
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...
A network of feature elements linked by their joint occurrence in papers .
242,947
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 : ...
A network of papers linked by their joint posession of features .
242,948
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 ...
A network of papers and one or more featuresets .
242,949
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 .
242,950
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 .
242,951
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 .
242,952
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
242,953
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 .
242,954
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 ....
Converts ElementTree node to a dictionary .
242,955
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
242,956
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...
This method creates a fixture for the django - tethne_paper model .
242,957
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...
This method creates a fixture for the django - tethne_citation model .
242,958
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 : i...
This method creates a fixture for the django - tethne_citation_institution model .
242,959
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 ( '.' , '' ) institu...
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 Ad...
242,960
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 = token...
This method is used to map the Affiliation between an author and Institution .
242,961
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 .
242,962
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 . normali...
Process a single line of data and store the result .
242,963
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_eo...
Open the data file .
242,964
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...
Get the next line of data .
242,965
def coauthors ( corpus , min_weight = 1 , edge_attrs = [ 'ayjid' , 'date' ] , ** kwargs ) : return cooccurrence ( corpus , 'authors' , min_weight = min_weight , edge_attrs = edge_attrs , ** kwargs )
A graph describing joint authorship in corpus .
242,966
def extract_text ( fpath ) : with codecs . open ( fpath , 'r' ) as f : document = f . read ( ) encoding = chardet . detect ( document ) [ 'encoding' ] document = document . decode ( encoding ) tokens = [ ] sentences = [ ] i = 0 for sentence in nltk . tokenize . sent_tokenize ( document ) : sentences . append ( i ) for ...
Extracts structured text content from a plain - text file at fpath .
242,967
def extract_pdf ( fpath ) : with codecs . open ( fpath , 'r' ) as f : document = slate . PDF ( f ) encoding = chardet . detect ( document [ 0 ] ) tokens = [ ] pages = [ ] sentences = [ ] tokenizer = nltk . tokenize . TextTilingTokenizer ( ) i = 0 for page in document : pages . append ( i ) page = page . decode ( encodi...
Extracts structured text content from a PDF at fpath .
242,968
def read ( path , corpus = True , index_by = 'uri' , follow_links = False , ** kwargs ) : parser = ZoteroParser ( path , index_by = index_by , follow_links = follow_links ) papers = parser . parse ( ) if corpus : c = Corpus ( papers , index_by = index_by , ** kwargs ) if c . duplicate_papers : warnings . warn ( "Duplic...
Read bibliographic data from Zotero RDF .
242,969
def handle_date ( self , value ) : try : return iso8601 . parse_date ( unicode ( value ) ) . year except iso8601 . ParseError : for datefmt in ( "%B %d, %Y" , "%Y-%m" , "%Y-%m-%d" , "%m/%d/%Y" ) : try : return datetime . strptime ( unicode ( value ) , datefmt ) . date ( ) . year except ValueError : pass
Attempt to coerced date to ISO8601 .
242,970
def postprocess_link ( self , entry ) : if not self . follow_links : return if type ( entry . link ) is not list : entry . link = [ entry . link ] for link in list ( entry . link ) : if not os . path . exists ( link ) : continue mime_type = magic . from_file ( link , mime = True ) if mime_type == 'application/pdf' : st...
Attempt to load full - text content from resource .
242,971
def webpush ( subscription_info , data = None , vapid_private_key = None , vapid_claims = None , content_encoding = "aes128gcm" , curl = False , timeout = None , ttl = 0 ) : vapid_headers = None if vapid_claims : if not vapid_claims . get ( 'aud' ) : url = urlparse ( subscription_info . get ( 'endpoint' ) ) aud = "{}:/...
One call solution to endcode and send data to the endpoint contained in subscription_info using optional VAPID auth headers .
242,972
def encode ( self , data , content_encoding = "aes128gcm" ) : if not data : return if not self . auth_key or not self . receiver_key : raise WebPushException ( "No keys specified in subscription info" ) salt = None if content_encoding not in self . valid_encodings : raise WebPushException ( "Invalid content encoding sp...
Encrypt the data .
242,973
def send ( self , data = None , headers = None , ttl = 0 , gcm_key = None , reg_id = None , content_encoding = "aes128gcm" , curl = False , timeout = None ) : if headers is None : headers = dict ( ) encoded = { } headers = CaseInsensitiveDict ( headers ) if data : encoded = self . encode ( data , content_encoding ) if ...
Encode and send the data to the Push Service .
242,974
def calendarplot ( data , how = 'sum' , yearlabels = True , yearascending = True , yearlabel_kws = None , subplot_kws = None , gridspec_kws = None , fig_kws = None , ** kwargs ) : yearlabel_kws = yearlabel_kws or { } subplot_kws = subplot_kws or { } gridspec_kws = gridspec_kws or { } fig_kws = fig_kws or { } years = np...
Plot a timeseries as a calendar heatmap .
242,975
def geosgeometry_str_to_struct ( value ) : result = geos_ptrn . match ( value ) if not result : return None return { 'srid' : result . group ( 1 ) , 'x' : result . group ( 2 ) , 'y' : result . group ( 3 ) , }
Parses a geosgeometry string into struct .
242,976
def get_env ( name , default = None ) : if name in os . environ : return os . environ [ name ] if default is not None : return default error_msg = "Set the {} env variable" . format ( name ) raise ImproperlyConfigured ( error_msg )
Get the environment variable or return exception
242,977
def user_defined_symbols ( self ) : sym_in_current = set ( self . symtable . keys ( ) ) sym_from_construction = set ( self . no_deepcopy ) unique_symbols = sym_in_current . difference ( sym_from_construction ) return unique_symbols
Return a set of symbols that have been added to symtable after construction .
242,978
def unimplemented ( self , node ) : self . raise_exception ( node , exc = NotImplementedError , msg = "'%s' not supported" % ( node . __class__ . __name__ ) )
Unimplemented nodes .
242,979
def raise_exception ( self , node , exc = None , msg = '' , expr = None , lineno = None ) : if self . error is None : self . error = [ ] if expr is None : expr = self . expr if len ( self . error ) > 0 and not isinstance ( node , ast . Module ) : msg = '%s' % msg err = ExceptionHolder ( node , exc = exc , msg = msg , e...
Add an exception .
242,980
def run ( self , node , expr = None , lineno = None , with_raise = True ) : if time . time ( ) - self . start_time > self . max_time : raise RuntimeError ( ERR_MAX_TIME . format ( self . max_time ) ) out = None if len ( self . error ) > 0 : return out if node is None : return out if isinstance ( node , str ) : node = s...
Execute parsed Ast representation for an expression .
242,981
def eval ( self , expr , lineno = 0 , show_errors = True ) : self . lineno = lineno self . error = [ ] self . start_time = time . time ( ) try : node = self . parse ( expr ) except : errmsg = exc_info ( ) [ 1 ] if len ( self . error ) > 0 : errmsg = "\n" . join ( self . error [ 0 ] . get_error ( ) ) if not show_errors ...
Evaluate a single statement .
242,982
def on_module ( self , node ) : out = None for tnode in node . body : out = self . run ( tnode ) return out
Module def .
242,983
def on_assert ( self , node ) : if not self . run ( node . test ) : self . raise_exception ( node , exc = AssertionError , msg = node . msg ) return True
Assert statement .
242,984
def on_name ( self , node ) : ctx = node . ctx . __class__ if ctx in ( ast . Param , ast . Del ) : return str ( node . id ) else : if node . id in self . symtable : return self . symtable [ node . id ] else : msg = "name '%s' is not defined" % node . id self . raise_exception ( node , exc = NameError , msg = msg )
Name node .
242,985
def on_attribute ( self , node ) : ctx = node . ctx . __class__ if ctx == ast . Store : msg = "attribute for storage: shouldn't be here!" self . raise_exception ( node , exc = RuntimeError , msg = msg ) sym = self . run ( node . value ) if ctx == ast . Del : return delattr ( sym , node . attr ) fmt = "cannnot access at...
Extract attribute .
242,986
def on_assign ( self , node ) : val = self . run ( node . value ) for tnode in node . targets : self . node_assign ( tnode , val ) return
Simple assignment .
242,987
def on_augassign ( self , node ) : return self . on_assign ( ast . Assign ( targets = [ node . target ] , value = ast . BinOp ( left = node . target , op = node . op , right = node . value ) ) )
Augmented assign .
242,988
def on_slice ( self , node ) : return slice ( self . run ( node . lower ) , self . run ( node . upper ) , self . run ( node . step ) )
Simple slice .
242,989
def on_extslice ( self , node ) : return tuple ( [ self . run ( tnode ) for tnode in node . dims ] )
Extended slice .
242,990
def on_delete ( self , node ) : for tnode in node . targets : if tnode . ctx . __class__ != ast . Del : break children = [ ] while tnode . __class__ == ast . Attribute : children . append ( tnode . attr ) tnode = tnode . value if tnode . __class__ == ast . Name and tnode . id not in self . readonly_symbols : children ....
Delete statement .
242,991
def on_unaryop ( self , node ) : return op2func ( node . op ) ( self . run ( node . operand ) )
Unary operator .
242,992
def on_binop ( self , node ) : return op2func ( node . op ) ( self . run ( node . left ) , self . run ( node . right ) )
Binary operator .
242,993
def on_boolop ( self , node ) : val = self . run ( node . values [ 0 ] ) is_and = ast . And == node . op . __class__ if ( is_and and val ) or ( not is_and and not val ) : for n in node . values [ 1 : ] : val = op2func ( node . op ) ( val , self . run ( n ) ) if ( is_and and not val ) or ( not is_and and val ) : break r...
Boolean operator .
242,994
def _printer ( self , * out , ** kws ) : flush = kws . pop ( 'flush' , True ) fileh = kws . pop ( 'file' , self . writer ) sep = kws . pop ( 'sep' , ' ' ) end = kws . pop ( 'sep' , '\n' ) print ( * out , file = fileh , sep = sep , end = end ) if flush : fileh . flush ( )
Generic print function .
242,995
def on_if ( self , node ) : block = node . body if not self . run ( node . test ) : block = node . orelse for tnode in block : self . run ( tnode )
Regular if - then - else statement .
242,996
def on_ifexp ( self , node ) : expr = node . orelse if self . run ( node . test ) : expr = node . body return self . run ( expr )
If expressions .
242,997
def on_while ( self , node ) : while self . run ( node . test ) : self . _interrupt = None for tnode in node . body : self . run ( tnode ) if self . _interrupt is not None : break if isinstance ( self . _interrupt , ast . Break ) : break else : for tnode in node . orelse : self . run ( tnode ) self . _interrupt = None
While blocks .
242,998
def on_for ( self , node ) : for val in self . run ( node . iter ) : self . node_assign ( node . target , val ) self . _interrupt = None for tnode in node . body : self . run ( tnode ) if self . _interrupt is not None : break if isinstance ( self . _interrupt , ast . Break ) : break else : for tnode in node . orelse : ...
For blocks .
242,999
def on_listcomp ( self , node ) : out = [ ] for tnode in node . generators : if tnode . __class__ == ast . comprehension : for val in self . run ( tnode . iter ) : self . node_assign ( tnode . target , val ) add = True for cond in tnode . ifs : add = add and self . run ( cond ) if add : out . append ( self . run ( node...
List comprehension .