idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
61,300
def include ( self , target ) : if self . _clean . isDict ( ) : return self . _wrap ( target in self . obj . values ( ) ) else : return self . _wrap ( target in self . obj )
Determine if a given value is included in the array or object using is .
61,301
def shuffle ( self ) : if ( self . _clean . isDict ( ) ) : return self . _wrap ( list ( ) ) cloned = self . obj [ : ] random . shuffle ( cloned ) return self . _wrap ( cloned )
Shuffle an array .
61,302
def sortBy ( self , val = None ) : if val is not None : if _ ( val ) . isString ( ) : return self . _wrap ( sorted ( self . obj , key = lambda x , * args : x . get ( val ) ) ) else : return self . _wrap ( sorted ( self . obj , key = val ) ) else : return self . _wrap ( sorted ( self . obj ) )
Sort the object s values by a criterion produced by an iterator .
61,303
def _lookupIterator ( self , val ) : if val is None : return lambda el , * args : el return val if _ . isCallable ( val ) else lambda obj , * args : obj [ val ]
An internal function to generate lookup iterators .
61,304
def _group ( self , obj , val , behavior ) : ns = self . Namespace ( ) ns . result = { } iterator = self . _lookupIterator ( val ) def e ( value , index , * args ) : key = iterator ( value , index ) behavior ( ns . result , key , value ) _ . each ( obj , e ) if len ( ns . result ) == 1 : try : return ns . result [ 0 ] ...
An internal function used for aggregate group by operations .
61,305
def groupBy ( self , val ) : def by ( result , key , value ) : if key not in result : result [ key ] = [ ] result [ key ] . append ( value ) res = self . _group ( self . obj , val , by ) return self . _wrap ( res )
Groups the object s values by a criterion . Pass either a string attribute to group by or a function that returns the criterion .
61,306
def indexBy ( self , val = None ) : if val is None : val = lambda * args : args [ 0 ] def by ( result , key , value ) : result [ key ] = value res = self . _group ( self . obj , val , by ) return self . _wrap ( res )
Indexes the object s values by a criterion similar to groupBy but for when you know that your index values will be unique .
61,307
def countBy ( self , val ) : def by ( result , key , value ) : if key not in result : result [ key ] = 0 result [ key ] += 1 res = self . _group ( self . obj , val , by ) return self . _wrap ( res )
Counts instances of an object that group by a certain criterion . Pass either a string attribute to count by or a function that returns the criterion .
61,308
def sortedIndex ( self , obj , iterator = lambda x : x ) : array = self . obj value = iterator ( obj ) low = 0 high = len ( array ) while low < high : mid = ( low + high ) >> 1 if iterator ( array [ mid ] ) < value : low = mid + 1 else : high = mid return self . _wrap ( low )
Use a comparator function to figure out the smallest index at which an object should be inserted so as to maintain order . Uses binary search .
61,309
def flatten ( self , shallow = None ) : return self . _wrap ( self . _flatten ( self . obj , shallow ) )
Return a completely flattened version of an array .
61,310
def uniq ( self , isSorted = False , iterator = None ) : ns = self . Namespace ( ) ns . results = [ ] ns . array = self . obj initial = self . obj if iterator is not None : initial = _ ( ns . array ) . map ( iterator ) def by ( memo , value , index ) : if ( ( _ . last ( memo ) != value or not len ( memo ) ) if isSorted...
Produce a duplicate - free version of the array . If the array has already been sorted you have the option of using a faster algorithm . Aliased as unique .
61,311
def intersection ( self , * args ) : if type ( self . obj [ 0 ] ) is int : a = self . obj else : a = tuple ( self . obj [ 0 ] ) setobj = set ( a ) for i , v in enumerate ( args ) : setobj = setobj & set ( args [ i ] ) return self . _wrap ( list ( setobj ) )
Produce an array that contains every item shared between all the passed - in arrays .
61,312
def difference ( self , * args ) : setobj = set ( self . obj ) for i , v in enumerate ( args ) : setobj = setobj - set ( args [ i ] ) return self . _wrap ( self . _clean . _toOriginal ( setobj ) )
Take the difference between one array and a number of other arrays . Only the elements present in just the first array will remain .
61,313
def indexOf ( self , item , isSorted = False ) : array = self . obj ret = - 1 if not ( self . _clean . isList ( ) or self . _clean . isTuple ( ) ) : return self . _wrap ( - 1 ) if isSorted : i = _ . sortedIndex ( array , item ) ret = i if array [ i ] is item else - 1 else : i = 0 l = len ( array ) while i < l : if arra...
Return the position of the first occurrence of an item in an array or - 1 if the item is not included in the array .
61,314
def lastIndexOf ( self , item ) : array = self . obj i = len ( array ) - 1 if not ( self . _clean . isList ( ) or self . _clean . isTuple ( ) ) : return self . _wrap ( - 1 ) while i > - 1 : if array [ i ] is item : return self . _wrap ( i ) i -= 1 return self . _wrap ( - 1 )
Return the position of the last occurrence of an item in an array or - 1 if the item is not included in the array .
61,315
def range ( self , * args ) : args = list ( args ) args . insert ( 0 , self . obj ) return self . _wrap ( range ( * args ) )
Generate an integer Array containing an arithmetic progression .
61,316
def partial ( self , * args ) : def part ( * args2 ) : args3 = args + args2 return self . obj ( * args3 ) return self . _wrap ( part )
Partially apply a function by creating a version that has had some of its arguments pre - filled without changing its dynamic this context .
61,317
def memoize ( self , hasher = None ) : ns = self . Namespace ( ) ns . memo = { } if hasher is None : hasher = lambda x : x def memoized ( * args , ** kwargs ) : key = hasher ( * args ) if key not in ns . memo : ns . memo [ key ] = self . obj ( * args , ** kwargs ) return ns . memo [ key ] return self . _wrap ( memoized...
Memoize an expensive function by storing its results .
61,318
def delay ( self , wait , * args ) : def call_it ( ) : self . obj ( * args ) t = Timer ( ( float ( wait ) / float ( 1000 ) ) , call_it ) t . start ( ) return self . _wrap ( self . obj )
Delays a function for the given number of milliseconds and then calls it with the arguments supplied .
61,319
def throttle ( self , wait ) : ns = self . Namespace ( ) ns . timeout = None ns . throttling = None ns . more = None ns . result = None def done ( ) : ns . more = ns . throttling = False whenDone = _ . debounce ( done , wait ) wait = ( float ( wait ) / float ( 1000 ) ) def throttled ( * args , ** kwargs ) : def later (...
Returns a function that when invoked will only be triggered at most once during a given window of time .
61,320
def debounce ( self , wait , immediate = None ) : wait = ( float ( wait ) / float ( 1000 ) ) def debounced ( * args , ** kwargs ) : def call_it ( ) : self . obj ( * args , ** kwargs ) try : debounced . t . cancel ( ) except ( AttributeError ) : pass debounced . t = Timer ( wait , call_it ) debounced . t . start ( ) ret...
Returns a function that as long as it continues to be invoked will not be triggered . The function will be called after it stops being called for N milliseconds . If immediate is passed trigger the function on the leading edge instead of the trailing .
61,321
def once ( self ) : ns = self . Namespace ( ) ns . memo = None ns . run = False def work_once ( * args , ** kwargs ) : if ns . run is False : ns . memo = self . obj ( * args , ** kwargs ) ns . run = True return ns . memo return self . _wrap ( work_once )
Returns a function that will be executed at most one time no matter how often you call it . Useful for lazy initialization .
61,322
def wrap ( self , wrapper ) : def wrapped ( * args , ** kwargs ) : if kwargs : kwargs [ "object" ] = self . obj else : args = list ( args ) args . insert ( 0 , self . obj ) return wrapper ( * args , ** kwargs ) return self . _wrap ( wrapped )
Returns the first function passed as an argument to the second allowing you to adjust arguments run code before and after and conditionally execute the original function .
61,323
def compose ( self , * args ) : args = list ( args ) def composed ( * ar , ** kwargs ) : lastRet = self . obj ( * ar , ** kwargs ) for i in args : lastRet = i ( lastRet ) return lastRet return self . _wrap ( composed )
Returns a function that is the composition of a list of functions each consuming the return value of the function that follows .
61,324
def after ( self , func ) : ns = self . Namespace ( ) ns . times = self . obj if ns . times <= 0 : return func ( ) def work_after ( * args ) : if ns . times <= 1 : return func ( * args ) ns . times -= 1 return self . _wrap ( work_after )
Returns a function that will only be executed after being called N times .
61,325
def invert ( self ) : keys = self . _clean . keys ( ) inverted = { } for key in keys : inverted [ self . obj [ key ] ] = key return self . _wrap ( inverted )
Invert the keys and values of an object . The values must be serializable .
61,326
def functions ( self ) : names = [ ] for i , k in enumerate ( self . obj ) : if _ ( self . obj [ k ] ) . isCallable ( ) : names . append ( k ) return self . _wrap ( sorted ( names ) )
Return a sorted list of the function names available on the object .
61,327
def pick ( self , * args ) : ns = self . Namespace ( ) ns . result = { } def by ( key , * args ) : if key in self . obj : ns . result [ key ] = self . obj [ key ] _ . each ( self . _flatten ( args , True , [ ] ) , by ) return self . _wrap ( ns . result )
Return a copy of the object only containing the whitelisted properties .
61,328
def defaults ( self , * args ) : ns = self . Namespace ns . obj = self . obj def by ( source , * ar ) : for i , prop in enumerate ( source ) : if prop not in ns . obj : ns . obj [ prop ] = source [ prop ] _ . each ( args , by ) return self . _wrap ( ns . obj )
Fill in a given object with default properties .
61,329
def tap ( self , interceptor ) : interceptor ( self . obj ) return self . _wrap ( self . obj )
Invokes interceptor with the obj and then returns obj . The primary purpose of this method is to tap into a method chain in order to perform operations on intermediate results within the chain .
61,330
def isEmpty ( self ) : if self . obj is None : return True if self . _clean . isString ( ) : ret = self . obj . strip ( ) is "" elif self . _clean . isDict ( ) : ret = len ( self . obj . keys ( ) ) == 0 else : ret = len ( self . obj ) == 0 return self . _wrap ( ret )
Is a given array string or object empty? An empty object has no enumerable own - properties .
61,331
def isFile ( self ) : try : filetype = file except NameError : filetype = io . IOBase return self . _wrap ( type ( self . obj ) is filetype )
Check if the given object is a file
61,332
def join ( self , glue = " " ) : j = glue . join ( [ str ( x ) for x in self . obj ] ) return self . _wrap ( j )
Javascript s join implementation
61,333
def result ( self , property , * args ) : if self . obj is None : return self . _wrap ( self . obj ) if ( hasattr ( self . obj , property ) ) : value = getattr ( self . obj , property ) else : value = self . obj . get ( property ) if _ . isCallable ( value ) : return self . _wrap ( value ( * args ) ) return self . _wra...
If the value of the named property is a function then invoke it ; otherwise return it .
61,334
def mixin ( self ) : methods = self . obj for i , k in enumerate ( methods ) : setattr ( underscore , k , methods [ k ] ) self . makeStatic ( ) return self . _wrap ( self . obj )
Add your own custom functions to the Underscore object ensuring that they re correctly added to the OOP wrapper as well .
61,335
def escape ( self ) : self . obj = self . obj . replace ( "&" , self . _html_escape_table [ "&" ] ) for i , k in enumerate ( self . _html_escape_table ) : v = self . _html_escape_table [ k ] if k is not "&" : self . obj = self . obj . replace ( k , v ) return self . _wrap ( self . obj )
Escape a string for HTML interpolation .
61,336
def unescape ( self ) : for i , k in enumerate ( self . _html_escape_table ) : v = self . _html_escape_table [ k ] self . obj = self . obj . replace ( v , k ) return self . _wrap ( self . obj )
Within an interpolation evaluation or escaping remove HTML escaping that had been previously added .
61,337
def value ( self ) : if self . _wrapped is not self . Null : return self . _wrapped else : return self . obj
returns the object instead of instance
61,338
def makeStatic ( ) : p = lambda value : inspect . ismethod ( value ) or inspect . isfunction ( value ) for eachMethod in inspect . getmembers ( underscore , predicate = p ) : m = eachMethod [ 0 ] if not hasattr ( _ , m ) : def caller ( a ) : def execute ( * args ) : if len ( args ) == 1 : r = getattr ( underscore ( arg...
Provide static access to underscore class
61,339
def init ( ) : global _users , _names _configure_app ( app ) _users , _names = _init_login_manager ( app ) _configure_logger ( ) init_scheduler ( app . config . get ( 'SQLALCHEMY_DATABASE_URI' ) ) db . init ( app . config . get ( 'SQLALCHEMY_DATABASE_URI' ) )
Initialise and configure the app database scheduler etc .
61,340
def _configure_app ( app_ ) : app_ . url_map . strict_slashes = False app_ . config . from_object ( default_settings ) app_ . config . from_envvar ( 'JOB_CONFIG' , silent = True ) db_url = app_ . config . get ( 'SQLALCHEMY_DATABASE_URI' ) if not db_url : raise Exception ( 'No db_url in config' ) app_ . wsgi_app = Proxy...
Configure the Flask WSGI app .
61,341
def _init_login_manager ( app_ ) : login_manager = flogin . LoginManager ( ) login_manager . setup_app ( app_ ) login_manager . anonymous_user = Anonymous login_manager . login_view = "login" users = { app_ . config [ 'USERNAME' ] : User ( 'Admin' , 0 ) } names = dict ( ( int ( v . get_id ( ) ) , k ) for k , v in users...
Initialise and configure the login manager .
61,342
def _configure_logger_for_production ( logger ) : stderr_handler = logging . StreamHandler ( sys . stderr ) stderr_handler . setLevel ( logging . INFO ) if 'STDERR' in app . config : logger . addHandler ( stderr_handler ) file_handler = logging . handlers . RotatingFileHandler ( app . config . get ( 'LOG_FILE' ) , maxB...
Configure the given logger for production deployment .
61,343
def _configure_logger ( ) : if not app . debug : _configure_logger_for_production ( logging . getLogger ( ) ) elif not app . testing : _configure_logger_for_debugging ( logging . getLogger ( ) )
Configure the logging module .
61,344
def init_scheduler ( db_uri ) : global scheduler scheduler = apscheduler . Scheduler ( ) scheduler . misfire_grace_time = 3600 scheduler . add_jobstore ( sqlalchemy_store . SQLAlchemyJobStore ( url = db_uri ) , 'default' ) scheduler . add_listener ( job_listener , events . EVENT_JOB_EXECUTED | events . EVENT_JOB_MISSED...
Initialise and configure the scheduler .
61,345
def job_listener ( event ) : job_id = event . job . args [ 0 ] if event . code == events . EVENT_JOB_MISSED : db . mark_job_as_missed ( job_id ) elif event . exception : if isinstance ( event . exception , util . JobError ) : error_object = event . exception . as_dict ( ) else : error_object = "\n" . join ( traceback ....
Listens to completed job
61,346
def status ( ) : job_types = async_types . keys ( ) + sync_types . keys ( ) counts = { } for job_status in job_statuses : counts [ job_status ] = db . ENGINE . execute ( db . JOBS_TABLE . count ( ) . where ( db . JOBS_TABLE . c . status == job_status ) ) . first ( ) [ 0 ] return flask . jsonify ( version = 0.1 , job_ty...
Show version available job types and name of service .
61,347
def login ( ) : username = None password = None next = flask . request . args . get ( 'next' ) auth = flask . request . authorization if flask . request . method == 'POST' : username = flask . request . form [ 'username' ] password = flask . request . form [ 'password' ] if auth and auth . type == 'basic' : username = ...
Log in as administrator
61,348
def user ( ) : user = flogin . current_user return flask . jsonify ( { 'id' : user . get_id ( ) , 'name' : user . name , 'is_active' : user . is_active ( ) , 'is_anonymous' : user . is_anonymous } )
Show information about the current user
61,349
def logout ( ) : flogin . logout_user ( ) next = flask . request . args . get ( 'next' ) return flask . redirect ( next or flask . url_for ( "user" ) )
Log out the active user
61,350
def job_list ( ) : args = dict ( ( key , value ) for key , value in flask . request . args . items ( ) ) limit = args . pop ( '_limit' , 100 ) offset = args . pop ( '_offset' , 0 ) select = sql . select ( [ db . JOBS_TABLE . c . job_id ] , from_obj = [ db . JOBS_TABLE . outerjoin ( db . METADATA_TABLE , db . JOBS_TABLE...
List all jobs .
61,351
def job_status ( job_id , show_job_key = False , ignore_auth = False ) : job_dict = db . get_job ( job_id ) if not job_dict : return json . dumps ( { 'error' : 'job_id not found' } ) , 404 , headers if not ignore_auth and not is_authorized ( job_dict ) : return json . dumps ( { 'error' : 'not authorized' } ) , 403 , he...
Show a specific job .
61,352
def job_delete ( job_id ) : conn = db . ENGINE . connect ( ) job = db . get_job ( job_id ) if not job : return json . dumps ( { 'error' : 'job_id not found' } ) , 404 , headers if not is_authorized ( job ) : return json . dumps ( { 'error' : 'not authorized' } ) , 403 , headers trans = conn . begin ( ) try : conn . exe...
Deletes the job together with its logs and metadata .
61,353
def clear_jobs ( ) : if not is_authorized ( ) : return json . dumps ( { 'error' : 'not authorized' } ) , 403 , headers days = flask . request . args . get ( 'days' , None ) return _clear_jobs ( days )
Clear old jobs
61,354
def job_data ( job_id ) : job_dict = db . get_job ( job_id ) if not job_dict : return json . dumps ( { 'error' : 'job_id not found' } ) , 404 , headers if not is_authorized ( job_dict ) : return json . dumps ( { 'error' : 'not authorized' } ) , 403 , headers if job_dict [ 'error' ] : return json . dumps ( { 'error' : j...
Get the raw data that the job returned . The mimetype will be the value provided in the metdata for the key mimetype .
61,355
def job ( job_id = None ) : if not job_id : job_id = str ( uuid . uuid4 ( ) ) job_key = str ( uuid . uuid4 ( ) ) try : input = flask . request . json except werkzeug . exceptions . BadRequest : return json . dumps ( { "error" : "Malformed json" } ) , 409 , headers if ( not input and 'application/json' in flask . reques...
Submit a job . If no id is provided a random id will be generated .
61,356
def is_authorized ( job = None ) : if flogin . current_user . is_authenticated : return True if job : job_key = flask . request . headers . get ( 'Authorization' ) if job_key == app . config . get ( 'SECRET_KEY' ) : return True return job [ 'job_key' ] == job_key return False
Returns true if the request is authorized for the job if provided . If no job is provided the user has to be admin to be authorized .
61,357
def send_result ( job_id , api_key = None ) : job_dict = db . get_job ( job_id ) result_url = job_dict . get ( 'result_url' ) if not result_url : db . delete_api_key ( job_id ) return True api_key_from_job = job_dict . pop ( 'api_key' , None ) if not api_key : api_key = api_key_from_job headers = { 'Content-Type' : 'ap...
Send results to where requested .
61,358
def init ( uri , echo = False ) : global ENGINE , _METADATA , JOBS_TABLE , METADATA_TABLE , LOGS_TABLE ENGINE = sqlalchemy . create_engine ( uri , echo = echo , convert_unicode = True ) _METADATA = sqlalchemy . MetaData ( ENGINE ) JOBS_TABLE = _init_jobs_table ( ) METADATA_TABLE = _init_metadata_table ( ) LOGS_TABLE = ...
Initialise the database .
61,359
def get_job ( job_id ) : if job_id : job_id = unicode ( job_id ) result = ENGINE . execute ( JOBS_TABLE . select ( ) . where ( JOBS_TABLE . c . job_id == job_id ) ) . first ( ) if not result : return None result_dict = { } for field in result . keys ( ) : value = getattr ( result , field ) if value is None : result_dic...
Return the job with the given job_id as a dict .
61,360
def add_pending_job ( job_id , job_key , job_type , api_key , data = None , metadata = None , result_url = None ) : if not data : data = { } data = json . dumps ( data ) if job_id : job_id = unicode ( job_id ) if job_type : job_type = unicode ( job_type ) if result_url : result_url = unicode ( result_url ) if api_key :...
Add a new job with status pending to the jobs table .
61,361
def _validate_error ( error ) : if error is None : return None elif isinstance ( error , basestring ) : return { "message" : error } else : try : message = error [ "message" ] if isinstance ( message , basestring ) : return error else : raise InvalidErrorObjectError ( "error['message'] must be a string" ) except ( Type...
Validate and return the given error object .
61,362
def _update_job ( job_id , job_dict ) : if job_id : job_id = unicode ( job_id ) if "error" in job_dict : job_dict [ "error" ] = _validate_error ( job_dict [ "error" ] ) job_dict [ "error" ] = json . dumps ( job_dict [ "error" ] ) job_dict [ "error" ] = unicode ( job_dict [ "error" ] ) if "data" in job_dict : job_dict [...
Update the database row for the given job_id with the given job_dict .
61,363
def mark_job_as_completed ( job_id , data = None ) : update_dict = { "status" : "complete" , "data" : json . dumps ( data ) , "finished_timestamp" : datetime . datetime . now ( ) , } _update_job ( job_id , update_dict )
Mark a job as completed successfully .
61,364
def mark_job_as_errored ( job_id , error_object ) : update_dict = { "status" : "error" , "error" : error_object , "finished_timestamp" : datetime . datetime . now ( ) , } _update_job ( job_id , update_dict )
Mark a job as failed with an error .
61,365
def _init_jobs_table ( ) : _jobs_table = sqlalchemy . Table ( 'jobs' , _METADATA , sqlalchemy . Column ( 'job_id' , sqlalchemy . UnicodeText , primary_key = True ) , sqlalchemy . Column ( 'job_type' , sqlalchemy . UnicodeText ) , sqlalchemy . Column ( 'status' , sqlalchemy . UnicodeText , index = True ) , sqlalchemy . ...
Initialise the jobs table in the db .
61,366
def _init_metadata_table ( ) : _metadata_table = sqlalchemy . Table ( 'metadata' , _METADATA , sqlalchemy . Column ( 'job_id' , sqlalchemy . ForeignKey ( "jobs.job_id" , ondelete = "CASCADE" ) , nullable = False , primary_key = True ) , sqlalchemy . Column ( 'key' , sqlalchemy . UnicodeText , primary_key = True ) , sql...
Initialise the metadata table in the db .
61,367
def _init_logs_table ( ) : _logs_table = sqlalchemy . Table ( 'logs' , _METADATA , sqlalchemy . Column ( 'job_id' , sqlalchemy . ForeignKey ( "jobs.job_id" , ondelete = "CASCADE" ) , nullable = False ) , sqlalchemy . Column ( 'timestamp' , sqlalchemy . DateTime ) , sqlalchemy . Column ( 'message' , sqlalchemy . Unicode...
Initialise the logs table in the db .
61,368
def _get_metadata ( job_id ) : job_id = unicode ( job_id ) results = ENGINE . execute ( METADATA_TABLE . select ( ) . where ( METADATA_TABLE . c . job_id == job_id ) ) . fetchall ( ) metadata = { } for row in results : value = row [ 'value' ] if row [ 'type' ] == 'json' : value = json . loads ( value ) metadata [ row [...
Return any metadata for the given job_id from the metadata table .
61,369
def _get_logs ( job_id ) : job_id = unicode ( job_id ) results = ENGINE . execute ( LOGS_TABLE . select ( ) . where ( LOGS_TABLE . c . job_id == job_id ) ) . fetchall ( ) results = [ dict ( result ) for result in results ] for result in results : result . pop ( "job_id" ) return results
Return any logs for the given job_id from the logs table .
61,370
def check_node_attributes ( pattern , node , * attributes ) : for attribute_name in attributes : attribute = node . get ( attribute_name ) if attribute is not None and pattern . search ( attribute ) : return True return False
Searches match in attributes against given pattern and if finds the match against any of them returns True .
61,371
def generate_hash_id ( node ) : try : content = tostring ( node ) except Exception : logger . exception ( "Generating of hash failed" ) content = to_bytes ( repr ( node ) ) hash_id = md5 ( content ) . hexdigest ( ) return hash_id [ : 8 ]
Generates a hash_id for the node in question .
61,372
def get_link_density ( node , node_text = None ) : if node_text is None : node_text = node . text_content ( ) node_text = normalize_whitespace ( node_text . strip ( ) ) text_length = len ( node_text ) if text_length == 0 : return 0.0 links_length = sum ( map ( _get_normalized_text_length , node . findall ( ".//a" ) ) )...
Computes the ratio for text in given node and text in links contained in the node . It is computed from number of characters in the texts .
61,373
def is_unlikely_node ( node ) : unlikely = check_node_attributes ( CLS_UNLIKELY , node , "class" , "id" ) maybe = check_node_attributes ( CLS_MAYBE , node , "class" , "id" ) return bool ( unlikely and not maybe and node . tag != "body" )
Short helper for checking unlikely status .
61,374
def score_candidates ( nodes ) : MIN_HIT_LENTH = 25 candidates = { } for node in nodes : logger . debug ( "* Scoring candidate %s %r" , node . tag , node . attrib ) parent = node . getparent ( ) if parent is None : logger . debug ( "Skipping candidate - parent node is 'None'." ) continue grand = parent . getparent ( ) ...
Given a list of potential nodes find some initial scores to start
61,375
def getTime ( self ) : T = 1 / float ( self . samp [ self . nrates - 1 ] ) endtime = self . endsamp [ self . nrates - 1 ] * T t = numpy . linspace ( 0 , endtime , self . endsamp [ self . nrates - 1 ] ) return t
Actually this function creates a time stamp vector based on the number of samples and sample rate .
61,376
def getAnalogID ( self , num ) : listidx = self . An . index ( num ) return self . Ach_id [ listidx ]
Returns the COMTRADE ID of a given channel number . The number to be given is the same of the COMTRADE header .
61,377
def getDigitalID ( self , num ) : listidx = self . Dn . index ( num ) return self . Dch_id [ listidx ]
Reads the COMTRADE ID of a given channel number . The number to be given is the same of the COMTRADE header .
61,378
def getAnalogType ( self , num ) : listidx = self . An . index ( num ) unit = self . uu [ listidx ] if unit == 'kV' or unit == 'V' : return 'V' elif unit == 'A' or unit == 'kA' : return 'I' else : print 'Unknown channel type' return 0
Returns the type of the channel num based on its unit stored in the Comtrade header file . Returns V for a voltage channel and I for a current channel .
61,379
def ReadDataFile ( self ) : if os . path . isfile ( self . filename [ 0 : - 4 ] + '.dat' ) : filename = self . filename [ 0 : - 4 ] + '.dat' elif os . path . isfile ( self . filename [ 0 : - 4 ] + '.DAT' ) : filename = self . filename [ 0 : - 4 ] + '.DAT' else : print "Data file File not found." return 0 self . filehan...
Reads the contents of the Comtrade . dat file and store them in a private variable . For accessing a specific channel data see methods getAnalogData and getDigitalData .
61,380
def getAnalogChannelData ( self , ChNumber ) : if not self . DatFileContent : print "No data file content. Use the method ReadDataFile first" return 0 if ( ChNumber > self . A ) : print "Channel number greater than the total number of channels." return 0 str_struct = "ii%dh" % ( self . A + int ( numpy . ceil ( ( float ...
Returns an array of numbers containing the data values of the channel number ChNumber . ChNumber is the number of the channal as in . cfg file .
61,381
def initLogger ( ) : global logger logger = logging . getLogger ( 'root' ) logger . setLevel ( logging . DEBUG ) ch = logging . StreamHandler ( sys . stdout ) ch . setLevel ( logging . INFO ) formatter = logging . Formatter ( "[%(asctime)s] %(levelname)s: %(message)s" , "%Y-%m-%d %H:%M:%S" ) ch . setFormatter ( formatt...
This code taken from Matt s Suspenders for initializing a logger
61,382
def writeSeqsToFiles ( seqArray , seqFNPrefix , offsetFN , uniformLength ) : if uniformLength : offsets = np . lib . format . open_memmap ( offsetFN , 'w+' , '<u8' , ( 1 , ) ) offsets [ 0 ] = uniformLength d = { '$' : 0 , 'A' : 1 , 'C' : 2 , 'G' : 3 , 'N' : 4 , 'T' : 5 } dArr = np . add ( np . zeros ( dtype = '<u1' , s...
This function takes a seqArray and saves the values to a memmap file that can be accessed for multi - processing . Additionally it saves some offset indices in a numpy file for quicker string access .
61,383
def decompressBWT ( inputDir , outputDir , numProcs , logger ) : msbwt = MultiStringBWT . CompressedMSBWT ( ) msbwt . loadMsbwt ( inputDir , logger ) outputFile = np . lib . format . open_memmap ( outputDir + '/msbwt.npy' , 'w+' , '<u1' , ( msbwt . getTotalSize ( ) , ) ) del outputFile worksize = 1000000 tups = [ None ...
This is called for taking a BWT and decompressing it back out to it s original form . While unusual to do it s included in this package for completion purposes .
61,384
def decompressBWTPoolProcess ( tup ) : ( inputDir , outputDir , startIndex , endIndex ) = tup if startIndex == endIndex : return True msbwt = MultiStringBWT . CompressedMSBWT ( ) msbwt . loadMsbwt ( inputDir , None ) outputBwt = np . load ( outputDir + '/msbwt.npy' , 'r+' ) outputBwt [ startIndex : endIndex ] = msbwt ....
Individual process for decompression
61,385
def clearAuxiliaryData ( dirName ) : if dirName != None : if os . path . exists ( dirName + '/auxiliary.npy' ) : os . remove ( dirName + '/auxiliary.npy' ) if os . path . exists ( dirName + '/totalCounts.p' ) : os . remove ( dirName + '/totalCounts.p' ) if os . path . exists ( dirName + '/totalCounts.npy' ) : os . remo...
This function removes auxiliary files associated with a given filename
61,386
def build_base_document ( dom , return_fragment = True ) : body_element = dom . find ( ".//body" ) if body_element is None : fragment = fragment_fromstring ( '<div id="readabilityBody"/>' ) fragment . append ( dom ) else : body_element . tag = "div" body_element . set ( "id" , "readabilityBody" ) fragment = body_elemen...
Builds a base document with the body as root .
61,387
def check_siblings ( candidate_node , candidate_list ) : candidate_css = candidate_node . node . get ( "class" ) potential_target = candidate_node . content_score * 0.2 sibling_target_score = potential_target if potential_target > 10 else 10 parent = candidate_node . node . getparent ( ) siblings = parent . getchildren...
Looks through siblings for content that might also be related . Things like preambles content split by ads that we removed etc .
61,388
def clean_document ( node ) : if node is None or len ( node ) == 0 : return None logger . debug ( "\n\n-------------- CLEANING DOCUMENT -----------------" ) to_drop = [ ] for n in node . iter ( ) : if "style" in n . attrib : n . set ( "style" , "" ) if n . tag in ( "object" , "embed" ) and not ok_embedded_video ( n ) :...
Cleans up the final document we return as the readable article .
61,389
def clean_conditionally ( node ) : if node . tag not in ( 'form' , 'table' , 'ul' , 'div' , 'p' ) : return weight = get_class_weight ( node ) content_score = 0 if weight + content_score < 0 : logger . debug ( 'Dropping conditional node' ) logger . debug ( 'Weight + score < 0' ) return True commas_count = node . text_co...
Remove the clean_el if it looks like bad content based on rules .
61,390
def find_candidates ( document ) : nodes_to_score = set ( ) should_remove = set ( ) for node in document . iter ( ) : if is_unlikely_node ( node ) : logger . debug ( "We should drop unlikely: %s %r" , node . tag , node . attrib ) should_remove . add ( node ) elif is_bad_link ( node ) : logger . debug ( "We should drop ...
Finds cadidate nodes for the readable version of the article .
61,391
def is_bad_link ( node ) : if node . tag != "a" : return False name = node . get ( "name" ) href = node . get ( "href" ) if name and not href : return True if href : href_parts = href . split ( "#" ) if len ( href_parts ) == 2 and len ( href_parts [ 1 ] ) > 25 : return True return False
Helper to determine if the node is link that is useless .
61,392
def candidates ( self ) : dom = self . dom if dom is None or len ( dom ) == 0 : return None candidates , unlikely_candidates = find_candidates ( dom ) drop_nodes_with_parents ( unlikely_candidates ) return candidates
Generates list of candidates from the DOM .
61,393
def _readable ( self ) : if not self . candidates : logger . info ( "No candidates found in document." ) return self . _handle_no_candidates ( ) best_candidates = sorted ( ( c for c in self . candidates . values ( ) ) , key = attrgetter ( "content_score" ) , reverse = True ) printer = PrettyPrinter ( indent = 2 ) logge...
The readable parsed article
61,394
def _handle_no_candidates ( self ) : if self . dom is not None and len ( self . dom ) : dom = prep_article ( self . dom ) dom = build_base_document ( dom , self . _return_fragment ) return self . _remove_orphans ( dom . get_element_by_id ( "readabilityBody" ) ) else : logger . info ( "No document to use." ) return buil...
If we fail to find a good candidate we need to find something else .
61,395
def fastaIterator ( fastaFN ) : if fastaFN [ len ( fastaFN ) - 3 : ] == '.gz' : fp = gzip . open ( fastaFN , 'r' ) else : fp = open ( fastaFN , 'r' ) label = '' segments = [ ] line = '' for line in fp : if line [ 0 ] == '>' : if label != '' : yield ( label , '' . join ( segments ) ) label = ( line . strip ( '\n' ) [ 1 ...
Iterator that yields tuples containing a sequence label and the sequence itself
61,396
def loadBWT ( bwtDir , logger = None ) : if os . path . exists ( bwtDir + '/msbwt.npy' ) : msbwt = MultiStringBWT ( ) msbwt . loadMsbwt ( bwtDir , logger ) return msbwt elif os . path . exists ( bwtDir + '/comp_msbwt.npy' ) : msbwt = CompressedMSBWT ( ) msbwt . loadMsbwt ( bwtDir , logger ) return msbwt else : logger ....
Generic load function this is recommended for anyone wishing to use this code as it will automatically detect compression and assign the appropriate class preferring the decompressed version if both exist .
61,397
def createMSBWTFromSeqs ( seqArray , mergedDir , numProcs , areUniform , logger ) : MSBWTGen . clearAuxiliaryData ( mergedDir ) seqFN = mergedDir + '/seqs.npy' offsetFN = mergedDir + '/offsets.npy' seqCopy = sorted ( seqArray ) if areUniform : uniformLength = len ( seqArray [ 0 ] ) else : uniformLength = 0 seqCopy = ''...
This function takes a series of sequences and creates the BWT using the technique from Cox and Bauer
61,398
def createMSBWTFromFastq ( fastqFNs , outputDir , numProcs , areUniform , logger ) : logger . info ( 'Saving sorted sequences...' ) seqFN = outputDir + '/seqs.npy' offsetFN = outputDir + '/offsets.npy' abtFN = outputDir + '/about.npy' bwtFN = outputDir + '/msbwt.npy' MSBWTGen . clearAuxiliaryData ( outputDir ) preproce...
This function takes fasta filenames and creates the BWT using the technique from Cox and Bauer by simply loading all string prior to computation
61,399
def createMSBWTFromBam ( bamFNs , outputDir , numProcs , areUniform , logger ) : logger . info ( 'Saving sorted sequences...' ) seqFN = outputDir + '/seqs.npy' offsetFN = outputDir + '/offsets.npy' abtFN = outputDir + '/about.npy' bwtFN = outputDir + '/msbwt.npy' MSBWTGen . clearAuxiliaryData ( outputDir ) preprocessBa...
This function takes a fasta filename and creates the BWT using the technique from Cox and Bauer