idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
236,500 | def allocateFees ( self ) : items = list ( self . invoiceitem_set . all ( ) ) if self . total != sum ( [ x . total for x in items ] ) : msg = _ ( 'Invoice item totals do not match invoice total. Unable to allocate fees.' ) logger . error ( str ( msg ) ) raise ValidationError ( msg ) if self . adjustments != sum ( [ x ... | Fees are allocated across invoice items based on their discounted total price net of adjustments as a proportion of the overall invoice s total price |
236,501 | def applyAndAllocate ( self , allocatedPrices , tieredTuples , payAtDoor = False ) : initial_net_price = sum ( [ x for x in allocatedPrices ] ) if self . discountType == self . DiscountType . flatPrice : applicable_price = self . getFlatPrice ( payAtDoor ) or 0 this_price = applicable_price + sum ( [ x [ 0 ] . event . ... | This method takes an initial allocation of prices across events and an identical length list of allocation tuples . It applies the rule specified by this discount allocates the discount across the listed items and returns both the price and the allocation |
236,502 | def getComponentList ( self ) : component_list = [ ] for x in self . discountcombocomponent_set . all ( ) : for y in range ( 0 , x . quantity ) : component_list += [ x ] component_list . sort ( key = lambda x : x . quantity , reverse = True ) return component_list | This function just returns a list with items that are supposed to be present in the the list multiple times as multiple elements of the list . It simplifies checking whether a discount s conditions are satisfied . |
236,503 | def save ( self , * args , ** kwargs ) : if self . discountType != self . DiscountType . flatPrice : self . onlinePrice = None self . doorPrice = None if self . discountType != self . DiscountType . dollarDiscount : self . dollarDiscount = None if self . discountType != self . DiscountType . percentDiscount : self . pe... | Don t save any passed values related to a type of discount that is not the specified type |
236,504 | def checkVoucherCode ( sender , ** kwargs ) : logger . debug ( 'Signal to check RegistrationContactForm handled by vouchers app.' ) formData = kwargs . get ( 'formData' , { } ) request = kwargs . get ( 'request' , { } ) registration = kwargs . get ( 'registration' , None ) session = getattr ( request , 'session' , { } ... | Check that the given voucher code is valid |
236,505 | def applyVoucherCodeTemporarily ( sender , ** kwargs ) : logger . debug ( 'Signal fired to apply temporary vouchers.' ) reg = kwargs . pop ( 'registration' ) voucherId = reg . data . get ( 'gift' , '' ) try : voucher = Voucher . objects . get ( voucherId = voucherId ) except ObjectDoesNotExist : logger . debug ( 'No ap... | When the core registration system creates a temporary registration with a voucher code the voucher app looks for vouchers that match that code and creates TemporaryVoucherUse objects to keep track of the fact that the voucher may be used . |
236,506 | def applyReferrerVouchersTemporarily ( sender , ** kwargs ) : if not getConstant ( 'referrals__enableReferralProgram' ) : return logger . debug ( 'Signal fired to temporarily apply referrer vouchers.' ) reg = kwargs . pop ( 'registration' ) try : c = Customer . objects . get ( user__email = reg . email ) vouchers = c .... | Unlike voucher codes which have to be manually supplied referrer discounts are automatically applied here assuming that the referral program is enabled . |
236,507 | def applyVoucherCodesFinal ( sender , ** kwargs ) : logger . debug ( 'Signal fired to mark voucher codes as applied.' ) finalReg = kwargs . pop ( 'registration' ) tr = finalReg . temporaryRegistration tvus = TemporaryVoucherUse . objects . filter ( registration = tr ) for tvu in tvus : vu = VoucherUse ( voucher = tvu .... | Once a registration has been completed vouchers are used and referrers are awarded |
236,508 | def provideCustomerReferralCode ( sender , ** kwargs ) : customer = kwargs . pop ( 'customer' ) if getConstant ( 'vouchers__enableVouchers' ) and getConstant ( 'referrals__enableReferralProgram' ) : vrd = ensureReferralVouchersExist ( customer ) return { 'referralVoucherId' : vrd . referreeVoucher . voucherId } | If the vouchers app is installed and referrals are enabled then the customer s profile page can show their voucher referral code . |
236,509 | def get_prep_lookup ( self ) : raise FieldError ( "{} '{}' does not support lookups" . format ( self . lhs . field . __class__ . __name__ , self . lookup_name ) ) | Raise errors for unsupported lookups |
236,510 | def derive_fernet_key ( input_key ) : hkdf = HKDF ( algorithm = hashes . SHA256 ( ) , length = 32 , salt = salt , info = info , backend = backend , ) return base64 . urlsafe_b64encode ( hkdf . derive ( force_bytes ( input_key ) ) ) | Derive a 32 - bit b64 - encoded Fernet key from arbitrary input key . |
236,511 | def reduce_cpu ( f , x , axes , dtype ) : axes = _get_axes ( axes , x . ndim ) if not axes : return x permute = [ n for n in range ( x . ndim ) if n not in axes ] permute = axes + permute T = x . transpose ( permute = permute ) N = len ( axes ) t = T . type . at ( N , dtype = dtype ) acc = x . empty ( t , device = x . ... | NumPy s reduce in terms of fold . |
236,512 | def reduce_cuda ( g , x , axes , dtype ) : if axes != 0 : raise NotImplementedError ( "'axes' keyword is not implemented for CUDA" ) return g ( x , dtype = dtype ) | Reductions in CUDA use the thrust library for speed and have limited functionality . |
236,513 | def maxlevel ( lst ) : maxlev = 0 def f ( lst , level ) : nonlocal maxlev if isinstance ( lst , list ) : level += 1 maxlev = max ( level , maxlev ) for item in lst : f ( item , level ) f ( lst , 0 ) return maxlev | Return maximum nesting depth |
236,514 | def getitem ( lst , indices ) : if not indices : return lst i , indices = indices [ 0 ] , indices [ 1 : ] item = list . __getitem__ ( lst , i ) if isinstance ( i , int ) : return getitem ( item , indices ) if not item : if lst : _ = getitem ( lst , ( slice ( None ) , ) + indices ) elif any ( isinstance ( k , int ) for ... | Definition for multidimensional slicing and indexing on arbitrarily shaped nested lists . |
236,515 | def genslices ( n ) : def range_with_none ( ) : yield None yield from range ( - n , n + 1 ) for t in product ( range_with_none ( ) , range_with_none ( ) , range_with_none ( ) ) : s = slice ( * t ) if s . step != 0 : yield s | Generate all possible slices for a single dimension . |
236,516 | def genslices_ndim ( ndim , shape ) : iterables = [ genslices ( shape [ n ] ) for n in range ( ndim ) ] yield from product ( * iterables ) | Generate all possible slice tuples for shape . |
236,517 | def mutator ( mutate ) : @ functools . wraps ( mutate ) def inspyred_mutator ( random , candidates , args ) : mutants = [ ] for i , cs in enumerate ( candidates ) : mutants . append ( mutate ( random , cs , args ) ) return mutants inspyred_mutator . single_mutation = mutate return inspyred_mutator | Return an inspyred mutator function based on the given function . This function generator takes a function that operates on only one candidate to produce a single mutated candidate . The generator handles the iteration over each candidate in the set to be mutated . |
236,518 | def bit_flip_mutation ( random , candidate , args ) : rate = args . setdefault ( 'mutation_rate' , 0.1 ) mutant = copy . copy ( candidate ) if len ( mutant ) == len ( [ x for x in mutant if x in [ 0 , 1 ] ] ) : for i , m in enumerate ( mutant ) : if random . random ( ) < rate : mutant [ i ] = ( m + 1 ) % 2 return mutan... | Return the mutants produced by bit - flip mutation on the candidates . |
236,519 | def random_reset_mutation ( random , candidate , args ) : bounder = args [ '_ec' ] . bounder try : values = bounder . values except AttributeError : values = None if values is not None : rate = args . setdefault ( 'mutation_rate' , 0.1 ) mutant = copy . copy ( candidate ) for i , m in enumerate ( mutant ) : if random .... | Return the mutants produced by randomly choosing new values . |
236,520 | def scramble_mutation ( random , candidate , args ) : rate = args . setdefault ( 'mutation_rate' , 0.1 ) if random . random ( ) < rate : size = len ( candidate ) p = random . randint ( 0 , size - 1 ) q = random . randint ( 0 , size - 1 ) p , q = min ( p , q ) , max ( p , q ) s = candidate [ p : q + 1 ] random . shuffle... | Return the mutants created by scramble mutation on the candidates . |
236,521 | def gaussian_mutation ( random , candidate , args ) : mut_rate = args . setdefault ( 'mutation_rate' , 0.1 ) mean = args . setdefault ( 'gaussian_mean' , 0.0 ) stdev = args . setdefault ( 'gaussian_stdev' , 1.0 ) bounder = args [ '_ec' ] . bounder mutant = copy . copy ( candidate ) for i , m in enumerate ( mutant ) : i... | Return the mutants created by Gaussian mutation on the candidates . |
236,522 | def nonuniform_mutation ( random , candidate , args ) : bounder = args [ '_ec' ] . bounder num_gens = args [ '_ec' ] . num_generations max_gens = args [ 'max_generations' ] strength = args . setdefault ( 'mutation_strength' , 1 ) exponent = ( 1.0 - num_gens / float ( max_gens ) ) ** strength mutant = copy . copy ( cand... | Return the mutants produced by nonuniform mutation on the candidates . |
236,523 | def crossover ( cross ) : @ functools . wraps ( cross ) def inspyred_crossover ( random , candidates , args ) : if len ( candidates ) % 2 == 1 : candidates = candidates [ : - 1 ] moms = candidates [ : : 2 ] dads = candidates [ 1 : : 2 ] children = [ ] for i , ( mom , dad ) in enumerate ( zip ( moms , dads ) ) : cross .... | Return an inspyred crossover function based on the given function . |
236,524 | def n_point_crossover ( random , mom , dad , args ) : crossover_rate = args . setdefault ( 'crossover_rate' , 1.0 ) num_crossover_points = args . setdefault ( 'num_crossover_points' , 1 ) children = [ ] if random . random ( ) < crossover_rate : num_cuts = min ( len ( mom ) - 1 , num_crossover_points ) cut_points = rand... | Return the offspring of n - point crossover on the candidates . |
236,525 | def uniform_crossover ( random , mom , dad , args ) : ux_bias = args . setdefault ( 'ux_bias' , 0.5 ) crossover_rate = args . setdefault ( 'crossover_rate' , 1.0 ) children = [ ] if random . random ( ) < crossover_rate : bro = copy . copy ( dad ) sis = copy . copy ( mom ) for i , ( m , d ) in enumerate ( zip ( mom , da... | Return the offspring of uniform crossover on the candidates . |
236,526 | def partially_matched_crossover ( random , mom , dad , args ) : crossover_rate = args . setdefault ( 'crossover_rate' , 1.0 ) if random . random ( ) < crossover_rate : size = len ( mom ) points = random . sample ( range ( size ) , 2 ) x , y = min ( points ) , max ( points ) bro = copy . copy ( dad ) bro [ x : y + 1 ] =... | Return the offspring of partially matched crossover on the candidates . |
236,527 | def arithmetic_crossover ( random , mom , dad , args ) : ax_alpha = args . setdefault ( 'ax_alpha' , 0.5 ) ax_points = args . setdefault ( 'ax_points' , None ) crossover_rate = args . setdefault ( 'crossover_rate' , 1.0 ) bounder = args [ '_ec' ] . bounder children = [ ] if random . random ( ) < crossover_rate : bro = ... | Return the offspring of arithmetic crossover on the candidates . |
236,528 | def blend_crossover ( random , mom , dad , args ) : blx_alpha = args . setdefault ( 'blx_alpha' , 0.1 ) blx_points = args . setdefault ( 'blx_points' , None ) crossover_rate = args . setdefault ( 'crossover_rate' , 1.0 ) bounder = args [ '_ec' ] . bounder children = [ ] if random . random ( ) < crossover_rate : bro = c... | Return the offspring of blend crossover on the candidates . |
236,529 | def heuristic_crossover ( random , candidates , args ) : crossover_rate = args . setdefault ( 'crossover_rate' , 1.0 ) bounder = args [ '_ec' ] . bounder if len ( candidates ) % 2 == 1 : candidates = candidates [ : - 1 ] population = list ( args [ '_ec' ] . population ) lookup = dict ( zip ( [ pickle . dumps ( p . cand... | Return the offspring of heuristic crossover on the candidates . |
236,530 | def gravitational_force ( position_a , mass_a , position_b , mass_b ) : distance = distance_between ( position_a , position_b ) angle = math . atan2 ( position_a [ 1 ] - position_b [ 1 ] , position_a [ 0 ] - position_b [ 0 ] ) magnitude = G * mass_a * mass_b / ( distance ** 2 ) sign = - 1 if mass_b > mass_a else 1 x_fo... | Returns the gravitational force between the two bodies a and b . |
236,531 | def force_on_satellite ( position , mass ) : earth_grav_force = gravitational_force ( position , mass , earth_position , earth_mass ) moon_grav_force = gravitational_force ( position , mass , moon_position , moon_mass ) F_x = earth_grav_force [ 0 ] + moon_grav_force [ 0 ] F_y = earth_grav_force [ 1 ] + moon_grav_force ... | Returns the total gravitational force acting on the body from the Earth and Moon . |
236,532 | def acceleration_of_satellite ( position , mass ) : F_x , F_y = force_on_satellite ( position , mass ) return F_x / mass , F_y / mass | Returns the acceleration based on all forces acting upon the body . |
236,533 | def evaluator ( evaluate ) : @ functools . wraps ( evaluate ) def inspyred_evaluator ( candidates , args ) : fitness = [ ] for candidate in candidates : fitness . append ( evaluate ( candidate , args ) ) return fitness inspyred_evaluator . single_evaluation = evaluate return inspyred_evaluator | Return an inspyred evaluator function based on the given function . This function generator takes a function that evaluates only one candidate . The generator handles the iteration over each candidate to be evaluated . |
236,534 | def parallel_evaluation_pp ( candidates , args ) : import pp logger = args [ '_ec' ] . logger try : evaluator = args [ 'pp_evaluator' ] except KeyError : logger . error ( 'parallel_evaluation_pp requires \'pp_evaluator\' be defined in the keyword arguments list' ) raise secret_key = args . setdefault ( 'pp_secret' , 'i... | Evaluate the candidates in parallel using Parallel Python . |
236,535 | def parallel_evaluation_mp ( candidates , args ) : import time import multiprocessing logger = args [ '_ec' ] . logger try : evaluator = args [ 'mp_evaluator' ] except KeyError : logger . error ( 'parallel_evaluation_mp requires \'mp_evaluator\' be defined in the keyword arguments list' ) raise try : nprocs = args [ 'm... | Evaluate the candidates in parallel using multiprocessing . |
236,536 | def allow_ajax ( request ) : if request . META . get ( 'REMOTE_ADDR' , None ) not in settings . INTERNAL_IPS : return False if toolbar_version < LooseVersion ( '1.8' ) and request . get_full_path ( ) . startswith ( DEBUG_TOOLBAR_URL_PREFIX ) and request . GET . get ( 'panel_id' , None ) != 'RequestHistoryPanel' : retur... | Default function to determine whether to show the toolbar on a given page . |
236,537 | def content ( self ) : toolbars = OrderedDict ( ) for id , toolbar in DebugToolbar . _store . items ( ) : content = { } for panel in toolbar . panels : panel_id = None nav_title = '' nav_subtitle = '' try : panel_id = panel . panel_id nav_title = panel . nav_title nav_subtitle = panel . nav_subtitle ( ) if isinstance (... | Content of the panel when it s displayed in full screen . |
236,538 | def extract_content ( self , selector = '' , attr = '' , default = '' , connector = '' , * args , ** kwargs ) : try : if selector . lower ( ) == "url" : return self . url if attr . lower ( ) == "text" : tag = self . get_tree_tag ( selector = selector , get_one = True ) content = connector . join ( [ make_ascii ( x ) . ... | Method for performing the content extraction for the particular selector type . \ |
236,539 | def extract_links ( self , selector = '' , * args , ** kwargs ) : try : links = self . get_tree_tag ( selector = selector ) for link in links : next_url = urljoin ( self . url , link . get ( 'href' ) ) yield type ( self ) ( next_url ) except XPathError : raise Exception ( "Invalid %s selector - %s" % ( self . __selecto... | Method for performing the link extraction for the crawler . \ |
236,540 | def extract_tabular ( self , header = '' , prefix = '' , suffix = '' , table_type = '' , * args , ** kwargs ) : if type ( header ) in [ str , unicode ] : try : header_list = self . get_tree_tag ( header ) table_headers = [ prefix + h . text + suffix for h in header_list ] except XPathError : raise Exception ( "Invalid ... | Method for performing the tabular data extraction . \ |
236,541 | def extract_rows ( self , result = { } , selector = '' , table_headers = [ ] , attr = '' , connector = '' , default = '' , verbosity = 0 , * args , ** kwargs ) : result_list = [ ] try : values = self . get_tree_tag ( selector ) if len ( table_headers ) >= len ( values ) : from itertools import izip_longest pairs = izip... | Row data extraction for extract_tabular |
236,542 | def extract_columns ( self , result = { } , selector = '' , table_headers = [ ] , attr = '' , connector = '' , default = '' , verbosity = 0 , * args , ** kwargs ) : result_list = [ ] try : if type ( selector ) in [ str , unicode ] : selectors = [ selector ] elif type ( selector ) == list : selectors = selector [ : ] el... | Column data extraction for extract_tabular |
236,543 | def runCLI ( ) : args = docopt ( __doc__ , version = '0.3.0' ) try : check_arguments ( args ) command_list = [ 'genconfig' , 'run' , 'generate' ] select = itemgetter ( 'genconfig' , 'run' , 'generate' ) selectedCommand = command_list [ select ( args ) . index ( True ) ] cmdClass = get_command_class ( selectedCommand ) ... | The starting point for the execution of the Scrapple command line tool . |
236,544 | def check_arguments ( args ) : projectname_re = re . compile ( r'[^a-zA-Z0-9_]' ) if args [ 'genconfig' ] : if args [ '--type' ] not in [ 'scraper' , 'crawler' ] : raise InvalidType ( "--type has to be 'scraper' or 'crawler'" ) if args [ '--selector' ] not in [ 'xpath' , 'css' ] : raise InvalidSelector ( "--selector ha... | Validates the arguments passed through the CLI commands . |
236,545 | def form_to_json ( form ) : config = dict ( ) if form [ 'project_name' ] == "" : raise Exception ( 'Project name cannot be empty.' ) if form [ 'selector_type' ] not in [ "css" , "xpath" ] : raise Exception ( 'Selector type has to css or xpath' ) config [ 'project_name' ] = form [ 'project_name' ] config [ 'selector_typ... | Takes the form from the POST request in the web interface and generates the JSON config \ file |
236,546 | def execute_command ( self ) : try : self . args [ '--verbosity' ] = int ( self . args [ '--verbosity' ] ) if self . args [ '--verbosity' ] not in [ 0 , 1 , 2 ] : raise ValueError if self . args [ '--verbosity' ] > 0 : print ( Back . GREEN + Fore . BLACK + "Scrapple Run" ) print ( Back . RESET + Fore . RESET ) import j... | The run command implements the web content extractor corresponding to the given \ configuration file . |
236,547 | def traverse_next ( page , nextx , results , tabular_data_headers = [ ] , verbosity = 0 ) : for link in page . extract_links ( selector = nextx [ 'follow_link' ] ) : if verbosity > 0 : print ( '\n' ) print ( Back . YELLOW + Fore . BLUE + "Loading page " , link . url + Back . RESET + Fore . RESET , end = '' ) r = result... | Recursive generator to traverse through the next attribute and \ crawl through the links to be followed . |
236,548 | def validate_config ( config ) : fields = [ f for f in get_fields ( config ) ] if len ( fields ) != len ( set ( fields ) ) : raise InvalidConfigException ( "Invalid configuration file - %d duplicate field names" % len ( fields ) - len ( set ( fields ) ) ) return True | Validates the extractor configuration file . Ensures that there are no duplicate field names etc . |
236,549 | def get_fields ( config ) : for data in config [ 'scraping' ] [ 'data' ] : if data [ 'field' ] != '' : yield data [ 'field' ] if 'next' in config [ 'scraping' ] : for n in config [ 'scraping' ] [ 'next' ] : for f in get_fields ( n ) : yield f | Recursive generator that yields the field names in the config file |
236,550 | def extract_fieldnames ( config ) : fields = [ ] for x in get_fields ( config ) : if x in fields : fields . append ( x + '_' + str ( fields . count ( x ) + 1 ) ) else : fields . append ( x ) return fields | Function to return a list of unique field names from the config file |
236,551 | def run ( self , dag : DAGCircuit ) -> DAGCircuit : circ = dagcircuit_to_tk ( dag , _DROP_CONDS = self . DROP_CONDS , _BOX_UNKNOWN = self . BOX_UNKNOWN ) circ , circlay = self . process_circ ( circ ) newdag = tk_to_dagcircuit ( circ ) newdag . name = dag . name finlay = dict ( ) for i , qi in enumerate ( circlay ) : fi... | Run one pass of optimisation on the circuit and route for the given backend . |
236,552 | def _sort_row_col ( qubits : Iterator [ GridQubit ] ) -> List [ GridQubit ] : return sorted ( qubits , key = lambda x : ( x . row , x . col ) ) | Sort grid qubits first by row then by column |
236,553 | def print_setting ( self ) -> str : ret = "\n" ret += "==================== Setting of {} ============================\n" . format ( self . configuration [ 'name' ] ) ret += "{}" . format ( self . setting ) ret += "===============================================================\n" ret += "{}" . format ( self . _var_for... | Presents the QSE settings as a string . |
236,554 | def _energy_evaluation ( self , operator ) : if self . _quantum_state is not None : input_circuit = self . _quantum_state else : input_circuit = [ self . opt_circuit ] if operator . _paulis : mean_energy , std_energy = operator . evaluate_with_result ( self . _operator_mode , input_circuit , self . _quantum_instance . ... | Evaluate the energy of the current input circuit with respect to the given operator . |
236,555 | def _run ( self ) -> dict : if not self . _quantum_instance . is_statevector : raise AquaError ( "Can only calculate state for QSE with statevector backends" ) ret = self . _quantum_instance . execute ( self . opt_circuit ) self . ret = ret self . _eval_count = 0 self . _solve ( ) self . _ret [ 'eval_count' ] = self . ... | Runs the QSE algorithm to compute the eigenvalues of the Hamiltonian . |
236,556 | def whooshee_search ( self , search_string , group = whoosh . qparser . OrGroup , whoosheer = None , match_substrings = True , limit = None , order_by_relevance = 10 ) : if not whoosheer : entities = set ( ) for cd in self . column_descriptions : entities . add ( cd [ 'type' ] ) if self . _join_entities and isinstance ... | Do a fulltext search on the query . Returns a query filtered with results of the fulltext search . |
236,557 | def search ( cls , search_string , values_of = '' , group = whoosh . qparser . OrGroup , match_substrings = True , limit = None ) : index = Whooshee . get_or_create_index ( _get_app ( cls ) , cls ) prepped_string = cls . prep_search_string ( search_string , match_substrings ) with index . searcher ( ) as searcher : par... | Searches the fields for given search_string . Returns the found records if values_of is left empty else the values of the given columns . |
236,558 | def create_index ( cls , app , wh ) : if app . extensions [ 'whooshee' ] [ 'memory_storage' ] : storage = RamStorage ( ) index = storage . create_index ( wh . schema ) assert index return index else : index_path = os . path . join ( app . extensions [ 'whooshee' ] [ 'index_path_root' ] , getattr ( wh , 'index_subdir' ,... | Creates and opens an index for the given whoosheer and app . If the index already exists it just opens it otherwise it creates it first . |
236,559 | def get_or_create_index ( cls , app , wh ) : if wh in app . extensions [ 'whooshee' ] [ 'whoosheers_indexes' ] : return app . extensions [ 'whooshee' ] [ 'whoosheers_indexes' ] [ wh ] index = cls . create_index ( app , wh ) app . extensions [ 'whooshee' ] [ 'whoosheers_indexes' ] [ wh ] = index return index | Gets a previously cached index or creates a new one for the given app and whoosheer . |
236,560 | def on_commit ( self , changes ) : if _get_config ( self ) [ 'enable_indexing' ] is False : return None for wh in self . whoosheers : if not wh . auto_update : continue writer = None for change in changes : if change [ 0 ] . __class__ in wh . models : method_name = '{0}_{1}' . format ( change [ 1 ] , change [ 0 ] . __c... | Method that gets called when a model is changed . This serves to do the actual index writing . |
236,561 | def reindex ( self ) : for wh in self . whoosheers : index = type ( self ) . get_or_create_index ( _get_app ( self ) , wh ) writer = index . writer ( timeout = _get_config ( self ) [ 'writer_timeout' ] ) for model in wh . models : method_name = "{0}_{1}" . format ( UPDATE_KWD , model . __name__ . lower ( ) ) for item i... | Reindex all data |
236,562 | def dump_info ( ) : vultr = Vultr ( API_KEY ) try : logging . info ( 'Listing account info:\n%s' , dumps ( vultr . account . info ( ) , indent = 2 ) ) logging . info ( 'Listing apps:\n%s' , dumps ( vultr . app . list ( ) , indent = 2 ) ) logging . info ( 'Listing backups:\n%s' , dumps ( vultr . backup . list ( ) , inde... | Shows various details about the account & servers |
236,563 | def update_params ( params , updates ) : params = params . copy ( ) if isinstance ( params , dict ) else dict ( ) params . update ( updates ) return params | Merges updates into params |
236,564 | def _request_get_helper ( self , url , params = None ) : if not isinstance ( params , dict ) : params = dict ( ) if self . api_key : params [ 'api_key' ] = self . api_key return requests . get ( url , params = params , timeout = 60 ) | API GET request helper |
236,565 | def _request_post_helper ( self , url , params = None ) : if self . api_key : query = { 'api_key' : self . api_key } return requests . post ( url , params = query , data = params , timeout = 60 ) | API POST helper |
236,566 | def _request_helper ( self , url , params , method ) : try : if method == 'POST' : return self . _request_post_helper ( url , params ) elif method == 'GET' : return self . _request_get_helper ( url , params ) raise VultrError ( 'Unsupported method %s' % method ) except requests . RequestException as ex : raise RuntimeE... | API request helper method |
236,567 | def halt_running ( ) : vultr = Vultr ( API_KEY ) try : serverList = vultr . server . list ( ) except VultrError as ex : logging . error ( 'VultrError: %s' , ex ) for serverID in serverList : if serverList [ serverID ] [ 'power_status' ] == 'running' : logging . info ( serverList [ serverID ] [ 'label' ] + " will be gra... | Halts all running servers |
236,568 | def tag_arxiv ( line ) : def tagger ( match ) : groups = match . groupdict ( ) if match . group ( 'suffix' ) : groups [ 'suffix' ] = ' ' + groups [ 'suffix' ] else : groups [ 'suffix' ] = '' return u'<cds.REPORTNUMBER>arXiv:%(year)s' u'%(month)s.%(num)s%(suffix)s' u'</cds.REPORTNUMBER>' % groups line = re_arxiv_5digits... | Tag arxiv report numbers |
236,569 | def tag_arxiv_more ( line ) : line = RE_ARXIV_CATCHUP . sub ( ur"\g<suffix>/\g<year>\g<month>\g<num>" , line ) for report_re , report_repl in RE_OLD_ARXIV : report_number = report_repl + ur"/\g<num>" line = report_re . sub ( u'<cds.REPORTNUMBER>' + report_number + u'</cds.REPORTNUMBER>' , line ) return line | Tag old arxiv report numbers |
236,570 | def tag_pos_volume ( line ) : def tagger ( match ) : groups = match . groupdict ( ) try : year = match . group ( 'year' ) except IndexError : g = re . search ( re_pos_year_num , match . group ( 'volume_num' ) , re . UNICODE ) year = g . group ( 0 ) if year : groups [ 'year' ] = ' <cds.YR>(%s)</cds.YR>' % year . strip (... | Tag POS volume number |
236,571 | def find_numeration_more ( line ) : patterns = ( re_correct_numeration_2nd_try_ptn1 , re_correct_numeration_2nd_try_ptn2 , re_correct_numeration_2nd_try_ptn3 , re_correct_numeration_2nd_try_ptn4 , ) for pattern in patterns : match = pattern . search ( line ) if match : info = match . groupdict ( ) series = extract_seri... | Look for other numeration in line . |
236,572 | def identify_ibids ( line ) : ibid_match_txt = { } for m_ibid in re_ibid . finditer ( line ) : ibid_match_txt [ m_ibid . start ( ) ] = m_ibid . group ( 0 ) line = line [ 0 : m_ibid . start ( ) ] + "_" * len ( m_ibid . group ( 0 ) ) + line [ m_ibid . end ( ) : ] return ibid_match_txt , line | Find IBIDs within the line record their position and length and replace them with underscores . |
236,573 | def find_numeration ( line ) : patterns = ( re_numeration_vol_page_yr , re_numeration_vol_nucphys_page_yr , re_numeration_nucphys_vol_page_yr , re_numeration_vol_subvol_nucphys_yr_page , re_numeration_vol_nucphys_yr_subvol_page , re_numeration_vol_yr_page , re_numeration_nucphys_vol_yr_page , re_numeration_vol_nucphys_... | Given a reference line attempt to locate instances of citation numeration in the line . |
236,574 | def remove_reference_line_marker ( line ) : marker_patterns = get_reference_line_numeration_marker_patterns ( ) line = line . lstrip ( ) marker_match = regex_match_list ( line , marker_patterns ) if marker_match is not None : marker_val = marker_match . group ( u'mark' ) line = line [ marker_match . end ( ) : ] . lstri... | Trim a reference line s marker from the beginning of the line . |
236,575 | def roman2arabic ( num ) : t = 0 p = 0 for r in num : n = 10 ** ( 205558 % ord ( r ) % 7 ) % 9995 t += n - 2 * p % n p = n return t | Convert numbers from roman to arabic |
236,576 | def format_report_number ( citation_elements ) : re_report = re . compile ( ur'^(?P<name>[A-Z-]+)(?P<nums>[\d-]+)$' , re . UNICODE ) for el in citation_elements : if el [ 'type' ] == 'REPORTNUMBER' : m = re_report . match ( el [ 'report_num' ] ) if m : name = m . group ( 'name' ) if not name . endswith ( '-' ) : el [ '... | Format report numbers that are missing a dash |
236,577 | def format_hep ( citation_elements ) : prefixes = ( 'astro-ph-' , 'hep-th-' , 'hep-ph-' , 'hep-ex-' , 'hep-lat-' , 'math-ph-' ) for el in citation_elements : if el [ 'type' ] == 'REPORTNUMBER' : for p in prefixes : if el [ 'report_num' ] . startswith ( p ) : el [ 'report_num' ] = el [ 'report_num' ] [ : len ( p ) - 1 ]... | Format hep - th report numbers with a dash |
236,578 | def look_for_books ( citation_elements , kbs ) : title = None for el in citation_elements : if el [ 'type' ] == 'QUOTED' : title = el break if title : normalized_title = title [ 'title' ] . upper ( ) if normalized_title in kbs [ 'books' ] : line = kbs [ 'books' ] [ normalized_title ] el = { 'type' : 'BOOK' , 'misc_txt'... | Look for books in our kb |
236,579 | def split_volume_from_journal ( citation_elements ) : for el in citation_elements : if el [ 'type' ] == 'JOURNAL' and ';' in el [ 'title' ] : el [ 'title' ] , series = el [ 'title' ] . rsplit ( ';' , 1 ) el [ 'volume' ] = series + el [ 'volume' ] return citation_elements | Split volume from journal title |
236,580 | def remove_b_for_nucl_phys ( citation_elements ) : for el in citation_elements : if el [ 'type' ] == 'JOURNAL' and el [ 'title' ] == 'Nucl.Phys.Proc.Suppl.' and 'volume' in el and ( el [ 'volume' ] . startswith ( 'b' ) or el [ 'volume' ] . startswith ( 'B' ) ) : el [ 'volume' ] = el [ 'volume' ] [ 1 : ] return citation... | Removes b from the volume of some journals |
236,581 | def mangle_volume ( citation_elements ) : volume_re = re . compile ( ur"(\d+)([A-Z])" , re . U | re . I ) for el in citation_elements : if el [ 'type' ] == 'JOURNAL' : matches = volume_re . match ( el [ 'volume' ] ) if matches : el [ 'volume' ] = matches . group ( 2 ) + matches . group ( 1 ) return citation_elements | Make sure the volume letter is before the volume number |
236,582 | def split_citations ( citation_elements ) : splitted_citations = [ ] new_elements = [ ] current_recid = None current_doi = None def check_ibid ( current_elements , trigger_el ) : for el in new_elements : if el [ 'type' ] == 'AUTH' : return if trigger_el . get ( 'is_ibid' , False ) : if splitted_citations : els = chain ... | Split a citation line in multiple citations |
236,583 | def look_for_hdl ( citation_elements ) : for el in list ( citation_elements ) : matched_hdl = re_hdl . finditer ( el [ 'misc_txt' ] ) for match in reversed ( list ( matched_hdl ) ) : hdl_el = { 'type' : 'HDL' , 'hdl_id' : match . group ( 'hdl_id' ) , 'misc_txt' : el [ 'misc_txt' ] [ match . end ( ) : ] } el [ 'misc_txt... | Looks for handle identifiers in the misc txt of the citation elements |
236,584 | def look_for_hdl_urls ( citation_elements ) : for el in citation_elements : if el [ 'type' ] == 'URL' : match = re_hdl . match ( el [ 'url_string' ] ) if match : el [ 'type' ] = 'HDL' el [ 'hdl_id' ] = match . group ( 'hdl_id' ) del el [ 'url_desc' ] del el [ 'url_string' ] | Looks for handle identifiers that have already been identified as urls |
236,585 | def parse_reference_line ( ref_line , kbs , bad_titles_count = { } , linker_callback = None ) : line_marker , ref_line = remove_reference_line_marker ( ref_line ) ref_line , identified_dois = identify_and_tag_DOI ( ref_line ) ref_line , identified_urls = identify_and_tag_URLs ( ref_line ) tagged_line , bad_titles_count... | Parse one reference line |
236,586 | def search_for_book_in_misc ( citation , kbs ) : citation_year = year_from_citation ( citation ) for citation_element in citation : LOGGER . debug ( u"Searching for book title in: %s" , citation_element [ 'misc_txt' ] ) for title in kbs [ 'books' ] : startIndex = find_substring_ignore_special_chars ( citation_element [... | Searches for books in the misc_txt field if the citation is not recognized as anything like a journal book etc . |
236,587 | def map_tag_to_subfield ( tag_type , line , cur_misc_txt , dest ) : closing_tag = '</cds.%s>' % tag_type idx_closing_tag = line . find ( closing_tag ) if idx_closing_tag == - 1 : identified_citation_element = None line = line [ len ( '<cds.%s>' % tag_type ) : ] else : tag_content = line [ : idx_closing_tag ] identified... | Create a new reference element |
236,588 | def remove_leading_garbage_lines_from_reference_section ( ref_sectn ) : p_email = re . compile ( ur'^\s*e\-?mail' , re . UNICODE ) while ref_sectn and ( ref_sectn [ 0 ] . isspace ( ) or p_email . match ( ref_sectn [ 0 ] ) ) : ref_sectn . pop ( 0 ) return ref_sectn | Sometimes the first lines of the extracted references are completely blank or email addresses . These must be removed as they are not references . |
236,589 | def get_plaintext_document_body ( fpath , keep_layout = False ) : textbody = [ ] mime_type = magic . from_file ( fpath , mime = True ) if mime_type == "text/plain" : with open ( fpath , "r" ) as f : textbody = [ line . decode ( "utf-8" ) for line in f . readlines ( ) ] elif mime_type == "application/pdf" : textbody = c... | Given a file - path to a full - text return a list of unicode strings whereby each string is a line of the fulltext . In the case of a plain - text document this simply means reading the contents in from the file . In the case of a PDF however this means converting the document to plaintext . It raises UnknownDocumentT... |
236,590 | def parse_references ( reference_lines , recid = None , override_kbs_files = None , reference_format = u"{title} {volume} ({year}) {page}" , linker_callback = None ) : kbs = get_kbs ( custom_kbs_files = override_kbs_files ) processed_references , counts , dummy_bad_titles_count = parse_references_elements ( reference_l... | Parse a list of references |
236,591 | def build_stats ( counts ) : stats = { 'status' : 0 , 'reportnum' : counts [ 'reportnum' ] , 'title' : counts [ 'title' ] , 'author' : counts [ 'auth_group' ] , 'url' : counts [ 'url' ] , 'doi' : counts [ 'doi' ] , 'misc' : counts [ 'misc' ] , } stats_str = "%(status)s-%(reportnum)s-%(title)s-%(author)s-%(url)s-%(doi)s... | Return stats information from counts structure . |
236,592 | def replace_undesirable_characters ( line ) : for bad_string , replacement in UNDESIRABLE_STRING_REPLACEMENTS : line = line . replace ( bad_string , replacement ) for bad_char , replacement in iteritems ( UNDESIRABLE_CHAR_REPLACEMENTS ) : line = line . replace ( bad_char , replacement ) return line | Replace certain bad characters in a text line . |
236,593 | def convert_PDF_to_plaintext ( fpath , keep_layout = False ) : if not os . path . isfile ( CFG_PATH_PDFTOTEXT ) : raise IOError ( 'Missing pdftotext executable' ) if keep_layout : layout_option = "-layout" else : layout_option = "-raw" doclines = [ ] p_break_in_line = re . compile ( ur'^\s*\f(.+)$' , re . UNICODE ) cmd... | Convert PDF to txt using pdftotext |
236,594 | def get_author_affiliation_numeration_str ( punct = None ) : re_number = r'(?:\d\d?)' re_chained_numbers = r"(?:(?:[,;]\s*%s\.?\s*))*" % re_number if punct is None : re_punct = r"(?:[\{\(\[]?)" else : re_punct = re . escape ( punct ) numeration_str = r % { 'num' : re_number , 'num_chain' : re_chained_numbers , 'punct' ... | The numeration which can be applied to author names . Numeration is sometimes found next to authors of papers . |
236,595 | def make_auth_regex_str ( etal , initial_surname_author = None , surname_initial_author = None ) : if not initial_surname_author : initial_surname_author = get_initial_surname_author_pattern ( ) if not surname_initial_author : surname_initial_author = get_surname_initial_author_pattern ( ) return ur % { 'etal' : etal ,... | Returns a regular expression to be used to identify groups of author names in a citation . This method contains patterns for default authors so no arguments are needed for the most reliable form of matching . |
236,596 | def find_reference_section ( docbody ) : ref_details = None title_patterns = get_reference_section_title_patterns ( ) for title_pattern in title_patterns : for reversed_index , line in enumerate ( reversed ( docbody ) ) : title_match = title_pattern . match ( line ) if title_match : title = title_match . group ( 'title... | Search in document body for its reference section . |
236,597 | def find_numeration ( docbody , title ) : ref_details , found_title = find_numeration_in_title ( docbody , title ) if not ref_details : ref_details , found_title = find_numeration_in_body ( docbody ) return ref_details , found_title | Find numeration pattern |
236,598 | def get_reference_lines ( docbody , ref_sect_start_line , ref_sect_end_line , ref_sect_title , ref_line_marker_ptn , title_marker_same_line ) : start_idx = ref_sect_start_line if title_marker_same_line : title_start = docbody [ start_idx ] . find ( ref_sect_title ) if title_start != - 1 : docbody [ start_idx ] = docbod... | After the reference section of a document has been identified and the first and last lines of the reference section have been recorded this function is called to take the reference lines out of the document body . The document s reference lines are returned in a list of strings whereby each string is a reference line .... |
236,599 | def match_pagination ( ref_line ) : pattern = ur'\(?\[?(\d{1,4})\]?\)?\.?\s*$' re_footer = re . compile ( pattern , re . UNICODE ) match = re_footer . match ( ref_line ) if match : return int ( match . group ( 1 ) ) return None | Remove footer pagination from references lines |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.