idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
245,600
def bottleneck_matching ( I1 , I2 , matchidx , D , labels = [ "dgm1" , "dgm2" ] , ax = None ) : plot_diagrams ( [ I1 , I2 ] , labels = labels , ax = ax ) cp = np . cos ( np . pi / 4 ) sp = np . sin ( np . pi / 4 ) R = np . array ( [ [ cp , - sp ] , [ sp , cp ] ] ) if I1 . size == 0 : I1 = np . array ( [ [ 0 , 0 ] ] ) i...
Visualize bottleneck matching between two diagrams
472
7
245,601
def transform ( self , diagrams ) : # if diagram is empty, return empty image if len ( diagrams ) == 0 : return np . zeros ( ( self . nx , self . ny ) ) # if first entry of first entry is not iterable, then diagrams is singular and we need to make it a list of diagrams try : singular = not isinstance ( diagrams [ 0 ] [...
Convert diagram or list of diagrams to a persistence image .
292
12
245,602
def weighting ( self , landscape = None ) : # TODO: Implement a logistic function # TODO: use self.weighting_type to choose function if landscape is not None : if len ( landscape ) > 0 : maxy = np . max ( landscape [ : , 1 ] ) else : maxy = 1 def linear ( interval ) : # linear function of y such that f(0) = 0 and f(max...
Define a weighting function for stability results to hold the function must be 0 at y = 0 .
206
21
245,603
def show ( self , imgs , ax = None ) : ax = ax or plt . gca ( ) if type ( imgs ) is not list : imgs = [ imgs ] for i , img in enumerate ( imgs ) : ax . imshow ( img , cmap = plt . get_cmap ( "plasma" ) ) ax . axis ( "off" )
Visualize the persistence image
85
5
245,604
def resolve_orm_path ( model , orm_path ) : bits = orm_path . split ( '__' ) endpoint_model = reduce ( get_model_at_related_field , [ model ] + bits [ : - 1 ] ) if bits [ - 1 ] == 'pk' : field = endpoint_model . _meta . pk else : field = endpoint_model . _meta . get_field ( bits [ - 1 ] ) return field
Follows the queryset - style query path of orm_path starting from model class . If the path ends up referring to a bad field name django . db . models . fields . FieldDoesNotExist will be raised .
101
49
245,605
def get_model_at_related_field ( model , attr ) : field = model . _meta . get_field ( attr ) if hasattr ( field , 'related_model' ) : return field . related_model raise ValueError ( "{model}.{attr} ({klass}) is not a relationship field." . format ( * * { 'model' : model . __name__ , 'attr' : attr , 'klass' : field . __...
Looks up attr as a field of model and returns the related model class . If attr is not a relationship field ValueError is raised .
111
29
245,606
def contains_plural_field ( model , fields ) : source_model = model for orm_path in fields : model = source_model bits = orm_path . lstrip ( '+-' ) . split ( '__' ) for bit in bits [ : - 1 ] : field = model . _meta . get_field ( bit ) if field . many_to_many or field . one_to_many : return True model = get_model_at_rel...
Returns a boolean indicating if fields contains a relationship to multiple items .
112
13
245,607
def get_json_response_object ( self , datatable ) : # Ensure the object list is calculated. # Calling get_records() will do this implicitly, but we want simultaneous access to the # 'total_initial_record_count', and 'unpaged_record_count' values. datatable . populate_records ( ) draw = getattr ( self . request , self ....
Returns the JSON - compatible dictionary that will be serialized for an AJAX response .
227
17
245,608
def serialize_to_json ( self , response_data ) : indent = None if settings . DEBUG : indent = 4 # Serialize to JSON with Django's encoder: Adds date/time, decimal, # and UUID support. return json . dumps ( response_data , indent = indent , cls = DjangoJSONEncoder )
Returns the JSON string for the compiled data object .
71
10
245,609
def get_ajax ( self , request , * args , * * kwargs ) : response_data = self . get_json_response_object ( self . _datatable ) response = HttpResponse ( self . serialize_to_json ( response_data ) , content_type = "application/json" ) return response
Called when accessed via AJAX on the request method specified by the Datatable .
72
17
245,610
def get_active_ajax_datatable ( self ) : data = getattr ( self . request , self . request . method ) datatables_dict = self . get_datatables ( only = data [ 'datatable' ] ) return list ( datatables_dict . values ( ) ) [ 0 ]
Returns a single datatable according to the hint GET variable from an AJAX request .
69
17
245,611
def get_datatables ( self , only = None ) : if not hasattr ( self , '_datatables' ) : self . _datatables = { } datatable_classes = self . get_datatable_classes ( ) for name , datatable_class in datatable_classes . items ( ) : if only and name != only : continue queryset_getter_name = 'get_%s_datatable_queryset' % ( nam...
Returns a dict of the datatables served by this view .
510
13
245,612
def get_default_datatable_kwargs ( self , * * kwargs ) : kwargs [ 'view' ] = self # This is provided by default, but if the view is instantiated outside of the request cycle # (such as for the purposes of embedding that view's datatable elsewhere), the request may # not be required, so the user may not have a compellin...
Builds the default set of kwargs for initializing a Datatable class . Note that by default the MultipleDatatableMixin does not support any configuration via the view s class attributes and instead relies completely on the Datatable class itself to declare its configuration details .
163
54
245,613
def get_column_for_modelfield ( model_field ) : # If the field points to another model, we want to get the pk field of that other model and use # that as the real field. It is possible that a ForeignKey points to a model with table # inheritance, however, so we need to traverse the internal OneToOneField as well, so th...
Return the built - in Column class for a model field class .
157
13
245,614
def get_source_value ( self , obj , source , * * kwargs ) : result = [ ] for sub_source in self . expand_source ( source ) : # Call super() to get default logic, but send it the 'sub_source' sub_result = super ( CompoundColumn , self ) . get_source_value ( obj , sub_source , * * kwargs ) result . extend ( sub_result ) ...
Treat field as a nested sub - Column instance which explicitly stands in as the object to which term coercions and the query type lookup are delegated .
97
30
245,615
def _get_flat_db_sources ( self , model ) : sources = [ ] for source in self . sources : for sub_source in self . expand_source ( source ) : target_field = self . resolve_source ( model , sub_source ) if target_field : sources . append ( sub_source ) return sources
Return a flattened representation of the individual sources lists .
72
10
245,616
def get_source_handler ( self , model , source ) : if isinstance ( source , Column ) : return source # Generate a generic handler for the source modelfield = resolve_orm_path ( model , source ) column_class = get_column_for_modelfield ( modelfield ) return column_class ( )
Allow the nested Column source to be its own handler .
69
11
245,617
def dispatch ( self , request , * args , * * kwargs ) : if request . GET . get ( self . xeditable_fieldname_param ) : return self . get_ajax_xeditable_choices ( request , * args , * * kwargs ) return super ( XEditableMixin , self ) . dispatch ( request , * args , * * kwargs )
Introduces the ensure_csrf_cookie decorator and handles xeditable choices ajax .
87
21
245,618
def get_ajax_xeditable_choices ( self , request , * args , * * kwargs ) : field_name = request . GET . get ( self . xeditable_fieldname_param ) if not field_name : return HttpResponseBadRequest ( "Field name must be given" ) queryset = self . get_queryset ( ) if not self . model : self . model = queryset . model # Sani...
AJAX GET handler for xeditable queries asking for field choice lists .
313
16
245,619
def post ( self , request , * args , * * kwargs ) : self . object_list = None form = self . get_xeditable_form ( self . get_xeditable_form_class ( ) ) if form . is_valid ( ) : obj = self . get_update_object ( form ) if obj is None : data = json . dumps ( { 'status' : 'error' , 'message' : "Object does not exist." } ) r...
Builds a dynamic form that targets only the field in question and saves the modification .
194
17
245,620
def get_xeditable_form_kwargs ( self ) : kwargs = { 'model' : self . get_queryset ( ) . model , } if self . request . method in ( 'POST' , 'PUT' ) : kwargs . update ( { 'data' : self . request . POST , } ) return kwargs
Returns a dict of keyword arguments to be sent to the xeditable form class .
77
17
245,621
def get_update_object ( self , form ) : pk = form . cleaned_data [ 'pk' ] queryset = self . get_queryset ( ) try : obj = queryset . get ( pk = pk ) except queryset . model . DoesNotExist : obj = None return obj
Retrieves the target object based on the update form s pk and the table s queryset .
72
22
245,622
def update_object ( self , form , obj ) : field_name = form . cleaned_data [ 'name' ] value = form . cleaned_data [ 'value' ] setattr ( obj , field_name , value ) save_kwargs = { } if CAN_UPDATE_FIELDS : save_kwargs [ 'update_fields' ] = [ field_name ] obj . save ( * * save_kwargs ) data = json . dumps ( { 'status' : '...
Saves the new value to the target object .
127
10
245,623
def get_field_choices ( self , field , field_name ) : if self . request . GET . get ( 'select2' ) : names = [ 'id' , 'text' ] else : names = [ 'value' , 'text' ] choices_getter = getattr ( self , 'get_field_%s_choices' , None ) if choices_getter is None : if isinstance ( field , ForeignKey ) : choices_getter = self . _...
Returns the valid choices for field . The field_name argument is given for convenience .
155
17
245,624
def preload_record_data ( self , obj ) : data = { } for orm_path , column_name in self . value_queries . items ( ) : value = obj [ orm_path ] if column_name not in data : data [ column_name ] = value else : if not isinstance ( data [ column_name ] , ( tuple , list ) ) : data [ column_name ] = [ data [ column_name ] ] d...
Modifies the obj values dict to alias the selected values to the column name that asked for its selection .
135
21
245,625
def resolve_virtual_columns ( self , * names ) : from . views . legacy import get_field_definition virtual_columns = { } for name in names : field = get_field_definition ( name ) column = TextColumn ( sources = field . fields , label = field . pretty_name , processor = field . callback ) column . name = field . pretty_...
Assume that all names are legacy - style tuple declarations and generate modern columns instances to match the behavior of the old syntax .
197
25
245,626
def set_value_field ( self , model , field_name ) : fields = fields_for_model ( model , fields = [ field_name ] ) self . fields [ 'value' ] = fields [ field_name ]
Adds a value field to this form that uses the appropriate formfield for the named target field . This will help to ensure that the value is correctly validated .
49
31
245,627
def clean_name ( self ) : field_name = self . cleaned_data [ 'name' ] # get_all_field_names is deprecated in Django 1.8, this also fixes proxied models if hasattr ( self . model . _meta , 'get_fields' ) : field_names = [ field . name for field in self . model . _meta . get_fields ( ) ] else : field_names = self . model...
Validates that the name field corresponds to a field on the model .
140
14
245,628
def get_field_definition ( field_definition ) : if not isinstance ( field_definition , ( tuple , list ) ) : field_definition = [ field_definition ] else : field_definition = list ( field_definition ) if len ( field_definition ) == 1 : field = [ None , field_definition , None ] elif len ( field_definition ) == 2 : field...
Normalizes a field definition into its component parts even if some are missing .
178
15
245,629
def get_cached_data ( datatable , * * kwargs ) : cache_key = '%s%s' % ( CACHE_PREFIX , datatable . get_cache_key ( * * kwargs ) ) data = cache . get ( cache_key ) log . debug ( "Reading data from cache at %r: %r" , cache_key , data ) return data
Returns the cached object list under the appropriate key or None if not set .
89
15
245,630
def cache_data ( datatable , data , * * kwargs ) : cache_key = '%s%s' % ( CACHE_PREFIX , datatable . get_cache_key ( * * kwargs ) ) log . debug ( "Setting data to cache at %r: %r" , cache_key , data ) cache . set ( cache_key , data )
Stores the object list in the cache under the appropriate key .
86
13
245,631
def keyed_helper ( helper ) : @ wraps ( helper ) def wrapper ( instance = None , key = None , attr = None , * args , * * kwargs ) : if set ( ( instance , key , attr ) ) == { None } : # helper was called in place with neither important arg raise ValueError ( "If called directly, helper function '%s' requires either a mo...
Decorator for helper functions that operate on direct values instead of model instances .
258
16
245,632
def itemgetter ( k , ellipsis = False , key = None ) : def helper ( instance , * args , * * kwargs ) : default_value = kwargs . get ( 'default_value' ) if default_value is None : default_value = instance value = default_value [ k ] if ellipsis and isinstance ( k , slice ) and isinstance ( value , six . string_types ) a...
Looks up k as an index of the column s value .
146
12
245,633
def attrgetter ( attr , key = None ) : def helper ( instance , * args , * * kwargs ) : value = instance for bit in attr . split ( '.' ) : value = getattr ( value , bit ) if callable ( value ) : value = value ( ) return value if key : helper = keyed_helper ( helper ) ( key = key ) return helper
Looks up attr on the target value . If the result is a callable it will be called in place without arguments .
87
25
245,634
def make_processor ( func , arg = None ) : def helper ( instance , * args , * * kwargs ) : value = kwargs . get ( 'default_value' ) if value is None : value = instance if arg is not None : extra_arg = [ arg ] else : extra_arg = [ ] return func ( value , * extra_arg ) return helper
A pre - called processor that wraps the execution of the target callable func .
82
16
245,635
def upload_kitten ( client ) : # Here's the metadata for the upload. All of these are optional, including # this config dict itself. config = { 'album' : album , 'name' : 'Catastrophe!' , 'title' : 'Catastrophe!' , 'description' : 'Cute kitten being cute on {0}' . format ( datetime . now ( ) ) } print ( "Uploading imag...
Upload a picture of a kitten . We don t ship one so get creative!
129
16
245,636
def _isdst ( dt ) : if type ( dt ) == datetime . date : dt = datetime . datetime . combine ( dt , datetime . datetime . min . time ( ) ) dtc = dt . replace ( year = datetime . datetime . now ( ) . year ) if time . localtime ( dtc . timestamp ( ) ) . tm_isdst == 1 : return True return False
Check if date is in dst .
95
7
245,637
def _mktime ( time_struct ) : try : return time . mktime ( time_struct ) except OverflowError : dt = datetime . datetime ( * time_struct [ : 6 ] ) ep = datetime . datetime ( 1970 , 1 , 1 ) diff = dt - ep ts = diff . days * 24 * 3600 + diff . seconds + time . timezone if time_struct . tm_isdst == 1 : ts -= 3600 # Guess ...
Custom mktime because Windows can t be arsed to properly do pre - Epoch dates probably because it s busy counting all its chromosomes .
140
28
245,638
def _strftime ( pattern , time_struct = time . localtime ( ) ) : try : return time . strftime ( pattern , time_struct ) except OSError : dt = datetime . datetime . fromtimestamp ( _mktime ( time_struct ) ) # This is incredibly hacky and will probably break with leap # year overlaps and shit. Any complaints should go he...
Custom strftime because Windows is shit again .
182
9
245,639
def _gmtime ( timestamp ) : try : return time . gmtime ( timestamp ) except OSError : dt = datetime . datetime ( 1970 , 1 , 1 ) + datetime . timedelta ( seconds = timestamp ) dst = int ( _isdst ( dt ) ) return time . struct_time ( dt . timetuple ( ) [ : 8 ] + tuple ( [ dst ] ) )
Custom gmtime because yada yada .
89
10
245,640
def _dtfromtimestamp ( timestamp ) : try : return datetime . datetime . fromtimestamp ( timestamp ) except OSError : timestamp -= time . timezone dt = datetime . datetime ( 1970 , 1 , 1 ) + datetime . timedelta ( seconds = timestamp ) if _isdst ( dt ) : timestamp += 3600 dt = datetime . datetime ( 1970 , 1 , 1 ) + date...
Custom datetime timestamp constructor . because Windows . again .
105
11
245,641
def _dfromtimestamp ( timestamp ) : try : return datetime . date . fromtimestamp ( timestamp ) except OSError : timestamp -= time . timezone d = datetime . date ( 1970 , 1 , 1 ) + datetime . timedelta ( seconds = timestamp ) if _isdst ( d ) : timestamp += 3600 d = datetime . date ( 1970 , 1 , 1 ) + datetime . timedelta...
Custom date timestamp constructor . ditto
98
7
245,642
def guesstype ( timestr ) : timestr_full = " {} " . format ( timestr ) if timestr_full . find ( " in " ) != - 1 or timestr_full . find ( " ago " ) != - 1 : return Chronyk ( timestr ) comps = [ "second" , "minute" , "hour" , "day" , "week" , "month" , "year" ] for comp in comps : if timestr_full . find ( comp ) != - 1 :...
Tries to guess whether a string represents a time or a time delta and returns the appropriate object .
138
20
245,643
def _round ( num ) : deci = num - math . floor ( num ) if deci > 0.8 : return int ( math . floor ( num ) + 1 ) else : return int ( math . floor ( num ) )
A custom rounding function that s a bit more strict .
50
11
245,644
def datetime ( self , timezone = None ) : if timezone is None : timezone = self . timezone return _dtfromtimestamp ( self . __timestamp__ - timezone )
Returns a datetime object .
42
6
245,645
def ctime ( self , timezone = None ) : if timezone is None : timezone = self . timezone return time . ctime ( self . __timestamp__ - timezone )
Returns a ctime string .
41
6
245,646
def timestring ( self , pattern = "%Y-%m-%d %H:%M:%S" , timezone = None ) : if timezone is None : timezone = self . timezone timestamp = self . __timestamp__ - timezone timestamp -= LOCALTZ return _strftime ( pattern , _gmtime ( timestamp ) )
Returns a time string .
76
5
245,647
def get_ticket ( self , ticket_id ) : url = 'tickets/%d' % ticket_id ticket = self . _api . _get ( url ) return Ticket ( * * ticket )
Fetches the ticket for the given ticket ID
44
10
245,648
def create_outbound_email ( self , subject , description , email , email_config_id , * * kwargs ) : url = 'tickets/outbound_email' priority = kwargs . get ( 'priority' , 1 ) data = { 'subject' : subject , 'description' : description , 'priority' : priority , 'email' : email , 'email_config_id' : email_config_id , } dat...
Creates an outbound email
132
6
245,649
def update_ticket ( self , ticket_id , * * kwargs ) : url = 'tickets/%d' % ticket_id ticket = self . _api . _put ( url , data = json . dumps ( kwargs ) ) return Ticket ( * * ticket )
Updates a ticket from a given ticket ID
61
9
245,650
def get_agent ( self , agent_id ) : url = 'agents/%s' % agent_id return Agent ( * * self . _api . _get ( url ) )
Fetches the agent for the given agent ID
40
10
245,651
def update_agent ( self , agent_id , * * kwargs ) : url = 'agents/%s' % agent_id agent = self . _api . _put ( url , data = json . dumps ( kwargs ) ) return Agent ( * * agent )
Updates an agent
60
4
245,652
def _action ( self , res ) : try : j = res . json ( ) except : res . raise_for_status ( ) j = { } if 'Retry-After' in res . headers : raise HTTPError ( '403 Forbidden: API rate-limit has been reached until {}.' 'See http://freshdesk.com/api#ratelimit' . format ( res . headers [ 'Retry-After' ] ) ) if 'require_login' in...
Returns JSON response or raise exception if errors are present
197
10
245,653
def headTail_breaks ( values , cuts ) : values = np . array ( values ) mean = np . mean ( values ) cuts . append ( mean ) if len ( values ) > 1 : return headTail_breaks ( values [ values >= mean ] , cuts ) return cuts
head tail breaks helper function
60
5
245,654
def quantile ( y , k = 4 ) : w = 100. / k p = np . arange ( w , 100 + w , w ) if p [ - 1 ] > 100.0 : p [ - 1 ] = 100.0 q = np . array ( [ stats . scoreatpercentile ( y , pct ) for pct in p ] ) q = np . unique ( q ) k_q = len ( q ) if k_q < k : Warn ( 'Warning: Not enough unique values in array to form k classes' , User...
Calculates the quantiles for an array
142
9
245,655
def bin1d ( x , bins ) : left = [ - float ( "inf" ) ] left . extend ( bins [ 0 : - 1 ] ) right = bins cuts = list ( zip ( left , right ) ) k = len ( bins ) binIds = np . zeros ( x . shape , dtype = 'int' ) while cuts : k -= 1 l , r = cuts . pop ( - 1 ) binIds += ( x > l ) * ( x <= r ) * k counts = np . bincount ( binId...
Place values of a 1 - d array into bins and determine counts of values in each bin
135
18
245,656
def _kmeans ( y , k = 5 ) : y = y * 1. # KMEANS needs float or double dtype centroids = KMEANS ( y , k ) [ 0 ] centroids . sort ( ) try : class_ids = np . abs ( y - centroids ) . argmin ( axis = 1 ) except : class_ids = np . abs ( y [ : , np . newaxis ] - centroids ) . argmin ( axis = 1 ) uc = np . unique ( class_ids )...
Helper function to do kmeans in one dimension
211
10
245,657
def natural_breaks ( values , k = 5 ) : values = np . array ( values ) uv = np . unique ( values ) uvk = len ( uv ) if uvk < k : Warn ( 'Warning: Not enough unique values in array to form k classes' , UserWarning ) Warn ( 'Warning: setting k to %d' % uvk , UserWarning ) k = uvk kres = _kmeans ( values , k ) sids = kres...
natural breaks helper function
151
4
245,658
def _fit ( y , classes ) : tss = 0 for class_def in classes : yc = y [ class_def ] css = yc - yc . mean ( ) css *= css tss += sum ( css ) return tss
Calculate the total sum of squares for a vector y classified into classes
58
15
245,659
def gadf ( y , method = "Quantiles" , maxk = 15 , pct = 0.8 ) : y = np . array ( y ) adam = ( np . abs ( y - np . median ( y ) ) ) . sum ( ) for k in range ( 2 , maxk + 1 ) : cl = kmethods [ method ] ( y , k ) gadf = 1 - cl . adcm / adam if gadf > pct : break return ( k , cl , gadf )
Evaluate the Goodness of Absolute Deviation Fit of a Classifier Finds the minimum value of k for which gadf > pct
109
29
245,660
def make ( cls , * args , * * kwargs ) : # only flag overrides return flag to_annotate = copy . deepcopy ( kwargs ) return_object = kwargs . pop ( 'return_object' , False ) return_bins = kwargs . pop ( 'return_bins' , False ) return_counts = kwargs . pop ( 'return_counts' , False ) rolling = kwargs . pop ( 'rolling' , ...
Configure and create a classifier that will consume data and produce classifications given the configuration options specified by this function .
478
24
245,661
def get_tss ( self ) : tss = 0 for class_def in self . classes : if len ( class_def ) > 0 : yc = self . y [ class_def ] css = yc - yc . mean ( ) css *= css tss += sum ( css ) return tss
Total sum of squares around class means
72
7
245,662
def get_gadf ( self ) : adam = ( np . abs ( self . y - np . median ( self . y ) ) ) . sum ( ) gadf = 1 - self . adcm / adam return gadf
Goodness of absolute deviation of fit
49
7
245,663
def find_bin ( self , x ) : x = np . asarray ( x ) . flatten ( ) right = np . digitize ( x , self . bins , right = True ) if right . max ( ) == len ( self . bins ) : right [ right == len ( self . bins ) ] = len ( self . bins ) - 1 return right
Sort input or inputs according to the current bin estimate
77
10
245,664
def update ( self , y = None , inplace = False , * * kwargs ) : kwargs . update ( { 'k' : kwargs . pop ( 'k' , self . k ) } ) kwargs . update ( { 'pct' : kwargs . pop ( 'pct' , self . pct ) } ) kwargs . update ( { 'truncate' : kwargs . pop ( 'truncate' , self . _truncated ) } ) if inplace : self . _update ( y , * * kwa...
Add data or change classification parameters .
155
7
245,665
def _ss ( self , class_def ) : yc = self . y [ class_def ] css = yc - yc . mean ( ) css *= css return sum ( css )
calculates sum of squares for a class
46
9
245,666
def _swap ( self , class1 , class2 , a ) : ss1 = self . _ss ( class1 ) ss2 = self . _ss ( class2 ) tss1 = ss1 + ss2 class1c = copy . copy ( class1 ) class2c = copy . copy ( class2 ) class1c . remove ( a ) class2c . append ( a ) ss1 = self . _ss ( class1c ) ss2 = self . _ss ( class2c ) tss2 = ss1 + ss2 if tss1 < tss2 : ...
evaluate cost of moving a from class1 to class2
133
11
245,667
def render_pdf_file_to_image_files ( pdf_file_name , output_filename_root , program_to_use ) : res_x = str ( args . resX ) res_y = str ( args . resY ) if program_to_use == "Ghostscript" : if ex . system_os == "Windows" : # Windows PIL is more likely to know BMP ex . render_pdf_file_to_image_files__ghostscript_bmp ( pdf...
Render all the pages of the PDF file at pdf_file_name to image files with path and filename prefix given by output_filename_root . Any directories must have already been created and the calling program is responsible for deleting any directories or image files . The program program_to_use currently either the string pd...
346
96
245,668
def calculate_bounding_box_from_image ( im , curr_page ) : xMax , y_max = im . size bounding_box = im . getbbox ( ) # note this uses ltrb convention if not bounding_box : #print("\nWarning: could not calculate a bounding box for this page." # "\nAn empty page is assumed.", file=sys.stderr) bounding_box = ( xMax / 2 , y...
This function uses a PIL routine to get the bounding box of the rendered image .
375
18
245,669
def samefile ( path1 , path2 ) : if system_os == "Linux" or system_os == "Cygwin" : return os . path . samefile ( path1 , path2 ) return ( get_canonical_absolute_expanded_path ( path1 ) == get_canonical_absolute_expanded_path ( path2 ) )
Test if paths refer to the same file or directory .
78
11
245,670
def convert_windows_path_to_cygwin ( path ) : if len ( path ) > 2 and path [ 1 ] == ":" and path [ 2 ] == "\\" : newpath = cygwin_full_path_prefix + "/" + path [ 0 ] if len ( path ) > 3 : newpath += "/" + path [ 3 : ] path = newpath path = path . replace ( "\\" , "/" ) return path
Convert a Windows path to a Cygwin path . Just handles the basic case .
99
18
245,671
def remove_program_temp_directory ( ) : if os . path . exists ( program_temp_directory ) : max_retries = 3 curr_retries = 0 time_between_retries = 1 while True : try : shutil . rmtree ( program_temp_directory ) break except IOError : curr_retries += 1 if curr_retries > max_retries : raise # re-raise the exception time ...
Remove the global temp directory and all its contents .
127
10
245,672
def call_external_subprocess ( command_list , stdin_filename = None , stdout_filename = None , stderr_filename = None , env = None ) : if stdin_filename : stdin = open ( stdin_filename , "r" ) else : stdin = None if stdout_filename : stdout = open ( stdout_filename , "w" ) else : stdout = None if stderr_filename : stde...
Run the command and arguments in the command_list . Will search the system PATH for commands to execute but no shell is started . Redirects any selected outputs to the given filename . Waits for command completion .
286
43
245,673
def run_external_subprocess_in_background ( command_list , env = None ) : if system_os == "Windows" : DETACHED_PROCESS = 0x00000008 p = subprocess . Popen ( command_list , shell = False , stdin = None , stdout = None , stderr = None , close_fds = True , creationflags = DETACHED_PROCESS , env = env ) else : p = subproce...
Runs the command and arguments in the list as a background process .
143
14
245,674
def function_call_with_timeout ( fun_name , fun_args , secs = 5 ) : from multiprocessing import Process , Queue p = Process ( target = fun_name , args = tuple ( fun_args ) ) p . start ( ) curr_secs = 0 no_timeout = False if secs == 0 : no_timeout = True else : timeout = secs while p . is_alive ( ) and not no_timeout : ...
Run a Python function with a timeout . No interprocess communication or return values are handled . Setting secs to 0 gives infinite timeout .
162
27
245,675
def fix_pdf_with_ghostscript_to_tmp_file ( input_doc_fname ) : if not gs_executable : init_and_test_gs_executable ( exit_on_fail = True ) temp_file_name = get_temporary_filename ( extension = ".pdf" ) gs_run_command = [ gs_executable , "-dSAFER" , "-o" , temp_file_name , "-dPDFSETTINGS=/prepress" , "-sDEVICE=pdfwrite" ...
Attempt to fix a bad PDF file with a Ghostscript command writing the output PDF to a temporary file and returning the filename . Caller is responsible for deleting the file .
311
33
245,676
def get_bounding_box_list_ghostscript ( input_doc_fname , res_x , res_y , full_page_box ) : if not gs_executable : init_and_test_gs_executable ( exit_on_fail = True ) res = str ( res_x ) + "x" + str ( res_y ) box_arg = "-dUseMediaBox" # should be default, but set anyway if "c" in full_page_box : box_arg = "-dUseCropBox...
Call Ghostscript to get the bounding box list . Cannot set a threshold with this method .
656
19
245,677
def render_pdf_file_to_image_files_pdftoppm_ppm ( pdf_file_name , root_output_file_path , res_x = 150 , res_y = 150 , extra_args = None ) : if extra_args is None : extra_args = [ ] if not pdftoppm_executable : init_and_test_pdftoppm_executable ( prefer_local = False , exit_on_fail = True ) if old_pdftoppm_version : # W...
Use the pdftoppm program to render a PDF file to . png images . The root_output_file_path is prepended to all the output files which have numbers and extensions added . Extra arguments can be passed as a list in extra_args . Return the command output .
239
60
245,678
def render_pdf_file_to_image_files_pdftoppm_pgm ( pdf_file_name , root_output_file_path , res_x = 150 , res_y = 150 ) : comm_output = render_pdf_file_to_image_files_pdftoppm_ppm ( pdf_file_name , root_output_file_path , res_x , res_y , [ "-gray" ] ) return comm_output
Same as renderPdfFileToImageFile_pdftoppm_ppm but with - gray option for pgm .
104
26
245,679
def render_pdf_file_to_image_files__ghostscript_png ( pdf_file_name , root_output_file_path , res_x = 150 , res_y = 150 ) : # For gs commands see # http://ghostscript.com/doc/current/Devices.htm#File_formats # http://ghostscript.com/doc/current/Devices.htm#PNG if not gs_executable : init_and_test_gs_executable ( exit_o...
Use Ghostscript to render a PDF file to . png images . The root_output_file_path is prepended to all the output files which have numbers and extensions added . Return the command output .
218
42
245,680
def show_preview ( viewer_path , pdf_file_name ) : try : cmd = [ viewer_path , pdf_file_name ] run_external_subprocess_in_background ( cmd ) except ( subprocess . CalledProcessError , OSError , IOError ) as e : print ( "\nWarning from pdfCropMargins: The argument to the '--viewer' option:" "\n " , viewer_path , "\nwas ...
Run the PDF viewer at the path viewer_path on the file pdf_file_name .
120
19
245,681
def main ( ) : cleanup_and_exit = sys . exit # Function to do cleanup and exit before the import. exit_code = 0 # Imports are done here inside the try block so some ugly (and useless) # traceback info is avoided on user's ^C (KeyboardInterrupt, EOFError on Windows). try : from . import external_program_calls as ex # Cr...
Run main catching any exceptions and cleaning up the temp directories .
446
12
245,682
def get_full_page_box_list_assigning_media_and_crop ( input_doc , quiet = False ) : full_page_box_list = [ ] rotation_list = [ ] if args . verbose and not quiet : print ( "\nOriginal full page sizes, in PDF format (lbrt):" ) for page_num in range ( input_doc . getNumPages ( ) ) : # Get the current page and find the ful...
Get a list of all the full - page box values for each page . The argument input_doc should be a PdfFileReader object . The boxes on the list are in the simple 4 - float list format used by this program not RectangleObject format .
295
53
245,683
def set_cropped_metadata ( input_doc , output_doc , metadata_info ) : # Setting metadata with pyPdf requires low-level pyPdf operations, see # http://stackoverflow.com/questions/2574676/change-metadata-of-pdf-file-with-pypdf if not metadata_info : # In case it's null, just set values to empty strings. This class just h...
Set the metadata for the output document . Mostly just copied over but Producer has a string appended to indicate that this program modified the file . That allows for the undo operation to make sure that this program cropped the file in the first place .
462
48
245,684
def apply_crop_list ( crop_list , input_doc , page_nums_to_crop , already_cropped_by_this_program ) : if args . restore and not already_cropped_by_this_program : print ( "\nWarning from pdfCropMargins: The Producer string indicates that" "\neither this document was not previously cropped by pdfCropMargins" "\nor else i...
Apply the crop list to the pages of the input PdfFileReader object .
797
16
245,685
def setdefault ( self , key , value ) : try : super ( FlaskConfigStorage , self ) . setdefault ( key , value ) except RuntimeError : self . _defaults . __setitem__ ( key , value )
We may not always be connected to an app but we still need to provide a way to the base environment to set it s defaults .
48
27
245,686
def _app ( self ) : if self . app is not None : return self . app ctx = _request_ctx_stack . top if ctx is not None : return ctx . app try : from flask import _app_ctx_stack app_ctx = _app_ctx_stack . top if app_ctx is not None : return app_ctx . app except ImportError : pass raise RuntimeError ( 'assets instance not b...
The application object to work with ; this is either the app that we have been bound to or the current application .
108
23
245,687
def from_yaml ( self , path ) : bundles = YAMLLoader ( path ) . load_bundles ( ) for name in bundles : self . register ( name , bundles [ name ] )
Register bundles from a YAML configuration file
45
9
245,688
def from_module ( self , path ) : bundles = PythonLoader ( path ) . load_bundles ( ) for name in bundles : self . register ( name , bundles [ name ] )
Register bundles from a Python module
41
6
245,689
def handle_unhandled_exception ( exc_type , exc_value , exc_traceback ) : if issubclass ( exc_type , KeyboardInterrupt ) : # call the default excepthook saved at __excepthook__ sys . __excepthook__ ( exc_type , exc_value , exc_traceback ) return logger = logging . getLogger ( __name__ ) # type: ignore logger . critical...
Handler for unhandled exceptions that will write to the logs
123
11
245,690
def write_transcriptions ( utterances : List [ Utterance ] , tgt_dir : Path , ext : str , lazy : bool ) -> None : tgt_dir . mkdir ( parents = True , exist_ok = True ) for utter in utterances : out_path = tgt_dir / "{}.{}" . format ( utter . prefix , ext ) if lazy and out_path . is_file ( ) : continue with out_path . op...
Write the utterance transcriptions to files in the tgt_dir . Is lazy and checks if the file already exists .
118
25
245,691
def remove_duplicates ( utterances : List [ Utterance ] ) -> List [ Utterance ] : filtered_utters = [ ] utter_set = set ( ) # type: Set[Tuple[int, int, str]] for utter in utterances : if ( utter . start_time , utter . end_time , utter . text ) in utter_set : continue filtered_utters . append ( utter ) utter_set . add (...
Removes utterances with the same start_time end_time and text . Other metadata isn t considered .
118
22
245,692
def make_speaker_utters ( utterances : List [ Utterance ] ) -> Dict [ str , List [ Utterance ] ] : speaker_utters = defaultdict ( list ) # type: DefaultDict[str, List[Utterance]] for utter in utterances : speaker_utters [ utter . speaker ] . append ( utter ) return speaker_utters
Creates a dictionary mapping from speakers to their utterances .
79
12
245,693
def remove_too_short ( utterances : List [ Utterance ] , _winlen = 25 , winstep = 10 ) -> List [ Utterance ] : def is_too_short ( utterance : Utterance ) -> bool : charlen = len ( utterance . text ) if ( duration ( utterance ) / winstep ) < charlen : return True else : return False return [ utter for utter in utterance...
Removes utterances that will probably have issues with CTC because of the number of frames being less than the number of tokens in the transcription . Assuming char tokenization to minimize false negatives .
103
38
245,694
def min_edit_distance ( source : Sequence [ T ] , target : Sequence [ T ] , ins_cost : Callable [ ... , int ] = lambda _x : 1 , del_cost : Callable [ ... , int ] = lambda _x : 1 , sub_cost : Callable [ ... , int ] = lambda x , y : 0 if x == y else 1 ) -> int : # Initialize an m+1 by n+1 array. Note that the strings sta...
Calculates the minimum edit distance between two sequences .
390
11
245,695
def word_error_rate ( ref : Sequence [ T ] , hyp : Sequence [ T ] ) -> float : if len ( ref ) == 0 : raise EmptyReferenceException ( "Cannot calculating word error rate against a length 0 " "reference sequence." ) distance = min_edit_distance ( ref , hyp ) return 100 * float ( distance ) / len ( ref )
Calculate the word error rate of a sequence against a reference .
78
14
245,696
def dense_to_human_readable ( dense_repr : Sequence [ Sequence [ int ] ] , index_to_label : Dict [ int , str ] ) -> List [ List [ str ] ] : transcripts = [ ] for dense_r in dense_repr : non_empty_phonemes = [ phn_i for phn_i in dense_r if phn_i != 0 ] transcript = [ index_to_label [ index ] for index in non_empty_phone...
Converts a dense representation of model decoded output into human readable using a mapping from indices to labels .
121
21
245,697
def decode ( model_path_prefix : Union [ str , Path ] , input_paths : Sequence [ Path ] , label_set : Set [ str ] , * , feature_type : str = "fbank" , #TODO Make this None and infer feature_type from dimension of NN input layer. batch_size : int = 64 , feat_dir : Optional [ Path ] = None , batch_x_name : str = "batch_x...
Use an existing tensorflow model that exists on disk to decode WAV files .
775
17
245,698
def eval ( self , restore_model_path : Optional [ str ] = None ) -> None : saver = tf . train . Saver ( ) with tf . Session ( config = allow_growth_config ) as sess : if restore_model_path : logger . info ( "restoring model from %s" , restore_model_path ) saver . restore ( sess , restore_model_path ) else : assert self...
Evaluates the model on a test set .
544
10
245,699
def output_best_scores ( self , best_epoch_str : str ) -> None : BEST_SCORES_FILENAME = "best_scores.txt" with open ( os . path . join ( self . exp_dir , BEST_SCORES_FILENAME ) , "w" , encoding = ENCODING ) as best_f : print ( best_epoch_str , file = best_f , flush = True )
Output best scores to the filesystem
101
6