idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
248,800 | def get_by_symbol ( self , symbol : str ) -> Commodity : # handle namespace. Accept GnuCash and Yahoo-style symbols. full_symbol = self . __parse_gc_symbol ( symbol ) query = ( self . query . filter ( Commodity . mnemonic == full_symbol [ "mnemonic" ] ) ) if full_symbol [ "namespace" ] : query = query . filter ( Commod... | Returns the commodity with the given symbol . If more are found an exception will be thrown . | 120 | 18 |
248,801 | def get_stocks ( self , symbols : List [ str ] ) -> List [ Commodity ] : query = ( self . query . filter ( Commodity . mnemonic . in_ ( symbols ) ) ) . order_by ( Commodity . namespace , Commodity . mnemonic ) return query . all ( ) | loads stocks by symbol | 71 | 4 |
248,802 | def get_aggregate ( self , security : Commodity ) -> SecurityAggregate : assert security is not None assert isinstance ( security , Commodity ) return SecurityAggregate ( self . book , security ) | Returns the aggregate for the entity | 45 | 6 |
248,803 | def get_aggregate_for_symbol ( self , symbol : str ) -> SecurityAggregate : security = self . get_by_symbol ( symbol ) if not security : raise ValueError ( f"Security not found in GC book: {symbol}!" ) return self . get_aggregate ( security ) | Returns the aggregate for the security found by full symbol | 68 | 10 |
248,804 | def query ( self ) : query = ( self . book . session . query ( Commodity ) . filter ( Commodity . namespace != "CURRENCY" , Commodity . namespace != "template" ) ) return query | Returns the base query which filters out data for all queries . | 49 | 12 |
248,805 | def book ( self ) -> Book : if not self . __book : # Create/open the book. book_uri = self . settings . database_path self . __book = Database ( book_uri ) . open_book ( for_writing = self . __for_writing ) return self . __book | GnuCash Book . Opens the book or creates an database based on settings . | 65 | 17 |
248,806 | def accounts ( self ) -> AccountsAggregate : if not self . __accounts_aggregate : self . __accounts_aggregate = AccountsAggregate ( self . book ) return self . __accounts_aggregate | Returns the Accounts aggregate | 47 | 4 |
248,807 | def currencies ( self ) -> CurrenciesAggregate : if not self . __currencies_aggregate : self . __currencies_aggregate = CurrenciesAggregate ( self . book ) return self . __currencies_aggregate | Returns the Currencies aggregate | 49 | 5 |
248,808 | def securities ( self ) : if not self . __securities_aggregate : self . __securities_aggregate = SecuritiesAggregate ( self . book ) return self . __securities_aggregate | Returns securities aggregate | 43 | 3 |
248,809 | def get_currency_symbols ( self ) -> List [ str ] : result = [ ] currencies = self . currencies . get_book_currencies ( ) for cur in currencies : result . append ( cur . mnemonic ) return result | Returns the used currencies symbols as an array | 52 | 8 |
248,810 | def load_jinja_template ( file_name ) : original_script_path = sys . argv [ 0 ] #script_path = os.path.dirname(os.path.realpath(__file__)) script_dir = os . path . dirname ( original_script_path ) # file_path = os.path.join(script_path, file_name) # with open(file_path, 'r') as template_file: # return template_file.rea... | Loads the jinja2 HTML template from the given file . Assumes that the file is in the same directory as the script . | 149 | 28 |
248,811 | def get_days_in_month ( year : int , month : int ) -> int : month_range = calendar . monthrange ( year , month ) return month_range [ 1 ] | Returns number of days in the given month . 1 - based numbers as arguments . i . e . November = 11 | 40 | 23 |
248,812 | def get_from_gnucash26_date ( date_str : str ) -> date : date_format = "%Y%m%d" result = datetime . strptime ( date_str , date_format ) . date ( ) return result | Creates a datetime from GnuCash 2 . 6 date string | 55 | 14 |
248,813 | def parse_period ( period : str ) : period = period . split ( " - " ) date_from = Datum ( ) if len ( period [ 0 ] ) == 10 : date_from . from_iso_date_string ( period [ 0 ] ) else : date_from . from_iso_long_date ( period [ 0 ] ) date_from . start_of_day ( ) date_to = Datum ( ) if len ( period [ 1 ] ) == 10 : date_to . ... | parses period from date range picker . The received values are full ISO date | 164 | 17 |
248,814 | def get_period ( date_from : date , date_to : date ) -> str : assert isinstance ( date_from , date ) assert isinstance ( date_to , date ) str_from : str = date_from . isoformat ( ) str_to : str = date_to . isoformat ( ) return str_from + " - " + str_to | Returns the period string from the given dates | 80 | 8 |
248,815 | def load_json_file_contents ( path : str ) -> str : assert isinstance ( path , str ) content = None file_path = os . path . abspath ( path ) content = fileutils . read_text_from_file ( file_path ) json_object = json . loads ( content ) content = json . dumps ( json_object , sort_keys = True , indent = 4 ) return conten... | Loads contents from a json file | 90 | 7 |
248,816 | def validate_json ( data : str ) : result = None try : result = json . loads ( data ) except ValueError as error : log ( ERROR , "invalid json: %s" , error ) return result | Validate JSON by parsing string data . Returns the json dict . | 46 | 13 |
248,817 | def get_sql ( query ) : sql = str ( query . statement . compile ( dialect = sqlite . dialect ( ) , compile_kwargs = { "literal_binds" : True } ) ) return sql | Returns the sql query | 47 | 4 |
248,818 | def save_to_temp ( content , file_name = None ) : #output = "results.html" temp_dir = tempfile . gettempdir ( ) #tempfile.TemporaryDirectory() #tempfile.NamedTemporaryFile(mode='w+t') as f: out_file = os . path . join ( temp_dir , file_name ) #if os.path.exists(output) and os.path.isfile(output): file = open ( out_file... | Save the contents into a temp file . | 157 | 8 |
248,819 | def read_book_uri_from_console ( ) : db_path : str = input ( "Enter book_url or leave blank for the default settings value: " ) if db_path : # sqlite if db_path . startswith ( "sqlite://" ) : db_path_uri = db_path else : # TODO: check if file exists. db_path_uri = "file:///" + db_path else : cfg = settings . Settings (... | Prompts the user to enter book url in console | 123 | 11 |
248,820 | def run_report_from_console ( output_file_name , callback ) : print ( "The report uses a read-only access to the book." ) print ( "Now enter the data or ^Z to continue:" ) #report_method = kwargs["report_method"] result = callback ( ) #output_file_name = kwargs["output_file_name"] output = save_to_temp ( result , outpu... | Runs the report from the command line . Receives the book url from the console . | 106 | 18 |
248,821 | def get_dividend_sum_for_symbol ( book : Book , symbol : str ) : svc = SecuritiesAggregate ( book ) security = svc . get_by_symbol ( symbol ) sec_svc = SecurityAggregate ( book , security ) accounts = sec_svc . get_income_accounts ( ) total = Decimal ( 0 ) for account in accounts : # get all dividends. income = get_div... | Calculates all income for a symbol | 110 | 8 |
248,822 | def import_file ( filename ) : #file_path = os.path.relpath(filename) file_path = os . path . abspath ( filename ) log ( DEBUG , "Loading prices from %s" , file_path ) prices = __read_prices_from_file ( file_path ) with BookAggregate ( for_writing = True ) as svc : svc . prices . import_prices ( prices ) print ( "Savin... | Imports the commodity prices from the given . csv file . | 110 | 13 |
248,823 | def generate_report ( book_url ) : # commodity: CommodityOption( # section="Commodity", # sort_tag="a", # documentation_string="This is a stock", # default_value="VTIP"), # commodity_list: CommodityListOption( # section="Commodity", # sort_tag="a", # documentation_string="This is a stock", # default_value="VTIP") #): #... | Generates an HTML report content . | 297 | 7 |
248,824 | def main ( symbol : str ) : print ( "Displaying the balance for" , symbol ) with BookAggregate ( ) as svc : security = svc . book . get ( Commodity , mnemonic = symbol ) #security.transactions, security.prices sec_svc = SecurityAggregate ( svc . book , security ) # Display number of shares shares_no = sec_svc . get_qua... | Displays the balance for the security symbol . | 139 | 9 |
248,825 | def generate_report ( book_url ) : with piecash . open_book ( book_url , readonly = True , open_if_lock = True ) as book : accounts = [ acc . fullname for acc in book . accounts ] return f"""<html> <body> Hello world from python !<br> Book : {book_url}<br> List of accounts : {accounts} </body> </html>""" | Generates the report HTML . | 94 | 6 |
248,826 | def get_project_files ( ) : if is_git_project ( ) : return get_git_project_files ( ) project_files = [ ] for top , subdirs , files in os . walk ( '.' ) : for subdir in subdirs : if subdir . startswith ( '.' ) : subdirs . remove ( subdir ) for f in files : if f . startswith ( '.' ) : continue project_files . append ( os... | Retrieve a list of project files ignoring hidden files . | 118 | 11 |
248,827 | def print_success_message ( message ) : try : import colorama print ( colorama . Fore . GREEN + message + colorama . Fore . RESET ) except ImportError : print ( message ) | Print a message indicating success in green color to STDOUT . | 42 | 12 |
248,828 | def print_failure_message ( message ) : try : import colorama print ( colorama . Fore . RED + message + colorama . Fore . RESET , file = sys . stderr ) except ImportError : print ( message , file = sys . stderr ) | Print a message indicating failure in red color to STDERR . | 59 | 12 |
248,829 | def main ( ) : importer = ExchangeRatesImporter ( ) print ( "####################################" ) latest_rates_json = importer . get_latest_rates ( ) # translate into an array of PriceModels # TODO mapper = currencyrates.FixerioModelMapper() mapper = None rates = mapper . map_to_model ( latest_rates_json ) print ( "... | Default entry point | 170 | 3 |
248,830 | def generate_asset_allocation_report ( book_url ) : model = load_asset_allocation_model ( book_url ) # load display template template = templates . load_jinja_template ( "report_asset_allocation.html" ) # render template result = template . render ( model = model ) # **locals() return result | The otput is generated here . Separated from the generate_report function to allow executing from the command line . | 79 | 24 |
248,831 | def parse_value ( self , value_string : str ) : self . value = Decimal ( value_string ) return self . value | Parses the amount string . | 29 | 7 |
248,832 | def parse ( self , csv_row : str ) : self . date = self . parse_euro_date ( csv_row [ 2 ] ) self . symbol = csv_row [ 0 ] self . value = self . parse_value ( csv_row [ 1 ] ) return self | Parses the . csv row into own values | 64 | 11 |
248,833 | def load_cash_balances_with_children ( self , root_account_fullname : str ) : assert isinstance ( root_account_fullname , str ) svc = AccountsAggregate ( self . book ) root_account = svc . get_by_fullname ( root_account_fullname ) if not root_account : raise ValueError ( "Account not found" , root_account_fullname ) ac... | loads data for cash balances | 342 | 5 |
248,834 | def get_balance ( self ) : on_date = Datum ( ) on_date . today ( ) return self . get_balance_on ( on_date . value ) | Current account balance | 38 | 3 |
248,835 | def get_splits_query ( self ) : query = ( self . book . session . query ( Split ) . filter ( Split . account == self . account ) ) return query | Returns all the splits in the account | 38 | 7 |
248,836 | def get_transactions ( self , date_from : datetime , date_to : datetime ) -> List [ Transaction ] : assert isinstance ( date_from , datetime ) assert isinstance ( date_to , datetime ) # fix up the parameters as we need datetime dt_from = Datum ( ) dt_from . from_datetime ( date_from ) dt_from . start_of_day ( ) dt_to =... | Returns account transactions | 211 | 3 |
248,837 | def __get_all_child_accounts_as_array ( self , account : Account ) -> List [ Account ] : result = [ ] # ignore placeholders ? - what if a brokerage account has cash/stocks division? # if not account.placeholder: # continue result . append ( account ) for child in account . children : sub_accounts = self . __get_all_chi... | Returns the whole tree of child accounts in a list | 102 | 10 |
248,838 | def find_by_name ( self , term : str , include_placeholders : bool = False ) -> List [ Account ] : query = ( self . query . filter ( Account . name . like ( '%' + term + '%' ) ) . order_by ( Account . name ) ) # Exclude placeholder accounts? if not include_placeholders : query = query . filter ( Account . placeholder =... | Search for account by part of the name | 106 | 8 |
248,839 | def get_aggregate_by_id ( self , account_id : str ) -> AccountAggregate : account = self . get_by_id ( account_id ) return self . get_account_aggregate ( account ) | Returns the aggregate for the given id | 49 | 7 |
248,840 | def get_by_fullname ( self , fullname : str ) -> Account : # get all accounts and iterate, comparing the fullname. :S query = ( self . book . session . query ( Account ) ) # generic.get_sql() # print(sql) all_accounts = query . all ( ) for account in all_accounts : if account . fullname == fullname : return account # e... | Loads account by full name | 92 | 6 |
248,841 | def get_account_id_by_fullname ( self , fullname : str ) -> str : account = self . get_by_fullname ( fullname ) return account . guid | Locates the account by fullname | 40 | 7 |
248,842 | def get_all_children ( self , fullname : str ) -> List [ Account ] : # find the account by fullname root_acct = self . get_by_fullname ( fullname ) if not root_acct : raise NameError ( "Account not found in book!" ) acct_agg = self . get_account_aggregate ( root_acct ) result = acct_agg . get_all_child_accounts_as_arra... | Returns the whole child account tree for the account with the given full name | 132 | 14 |
248,843 | def get_all ( self ) -> List [ Account ] : return [ account for account in self . book . accounts if account . parent . name != "Template Root" ] | Returns all book accounts as a list excluding templates . | 36 | 10 |
248,844 | def get_favourite_accounts ( self ) -> List [ Account ] : from gnucash_portfolio . lib . settings import Settings settings = Settings ( ) favourite_accts = settings . favourite_accounts accounts = self . get_list ( favourite_accts ) return accounts | Provides a list of favourite accounts | 64 | 7 |
248,845 | def get_favourite_account_aggregates ( self ) -> List [ AccountAggregate ] : accounts = self . get_favourite_accounts ( ) aggregates = [ ] for account in accounts : aggregate = self . get_account_aggregate ( account ) aggregates . append ( aggregate ) return aggregates | Returns the list of aggregates for favourite accounts | 70 | 9 |
248,846 | def get_by_id ( self , acct_id ) -> Account : return self . book . get ( Account , guid = acct_id ) | Loads an account entity | 33 | 5 |
248,847 | def get_by_name ( self , name : str ) -> List [ Account ] : # return self.query.filter(Account.name == name).all() return self . get_by_name_from ( self . book . root , name ) | Searches accounts by name | 54 | 6 |
248,848 | def get_by_name_from ( self , root : Account , name : str ) -> List [ Account ] : result = [ ] if root . name == name : result . append ( root ) for child in root . children : child_results = self . get_by_name_from ( child , name ) result += child_results return result | Searches child accounts by name starting from the given account | 74 | 12 |
248,849 | def get_list ( self , ids : List [ str ] ) -> List [ Account ] : query = ( self . query . filter ( Account . guid . in_ ( ids ) ) ) return query . all ( ) | Loads accounts by the ids passed as an argument | 48 | 11 |
248,850 | def query ( self ) : query = ( self . book . session . query ( Account ) . join ( Commodity ) . filter ( Commodity . namespace != "template" ) . filter ( Account . type != AccountType . root . value ) ) return query | Main accounts query | 56 | 3 |
248,851 | def search ( self , name : str = None , acc_type : str = None ) : query = self . query if name is not None : query = query . filter ( Account . name == name ) if acc_type is not None : # account type is capitalized acc_type = acc_type . upper ( ) query = query . filter ( Account . type == acc_type ) return query . all ... | Search accounts by passing parameters . name = exact name name_part = part of name parent_id = id of the parent account type = account type | 88 | 30 |
248,852 | def get_price_as_of ( self , stock : Commodity , on_date : datetime ) : # return self.get_price_as_of_query(stock, on_date).first() prices = PriceDbApplication ( ) prices . get_prices_on ( on_date . date ( ) . isoformat ( ) , stock . namespace , stock . mnemonic ) | Gets the latest price on or before the given date . | 86 | 12 |
248,853 | def import_price ( self , price : PriceModel ) : # Handle yahoo-style symbols with extension. symbol = price . symbol if "." in symbol : symbol = price . symbol . split ( "." ) [ 0 ] stock = SecuritiesAggregate ( self . book ) . get_by_symbol ( symbol ) # get_aggregate_for_symbol if stock is None : logging . warning ( ... | Import individual price | 241 | 3 |
248,854 | def __create_price_for ( self , commodity : Commodity , price : PriceModel ) : logging . info ( "Adding a new price for %s, %s, %s" , commodity . mnemonic , price . datetime . strftime ( "%Y-%m-%d" ) , price . value ) # safety check. Compare currencies. sec_svc = SecurityAggregate ( self . book , commodity ) currency =... | Creates a new Price entry in the book for the given commodity | 216 | 13 |
248,855 | def get_splits_query ( self ) : query = ( self . book . session . query ( Split ) # .join(Transaction) . filter ( Split . transaction_guid == self . transaction . guid ) ) return query | Returns the query for related splits | 49 | 6 |
248,856 | def generate_report ( book_url , fund_ids : StringOption ( section = "Funds" , sort_tag = "c" , documentation_string = "Comma-separated list of fund ids." , default_value = "8123,8146,8148,8147" ) ) : return render_report ( book_url , fund_ids ) | Generates the report output | 81 | 5 |
248,857 | def searchAccount ( searchTerm , book ) : print ( "Search results:\n" ) found = False # search for account in book . accounts : # print(account.fullname) # name if searchTerm . lower ( ) in account . fullname . lower ( ) : print ( account . fullname ) found = True if not found : print ( "Search term not found in accoun... | Searches through account names | 84 | 6 |
248,858 | def display_db_info ( self ) : with self . open_book ( ) as book : default_currency = book . default_currency print ( "Default currency is " , default_currency . mnemonic ) | Displays some basic info about the GnuCash book | 46 | 11 |
248,859 | def open_book ( self , for_writing = False ) -> piecash . Book : filename = None # check if the file path is already a URL. file_url = urllib . parse . urlparse ( self . filename ) if file_url . scheme == "file" or file_url . scheme == "sqlite" : filename = file_url . path [ 1 : ] else : filename = self . filename if n... | Opens the database . Call this using with . If database file is not found an in - memory database will be created . | 260 | 25 |
248,860 | def read_text_from_file ( path : str ) -> str : with open ( path ) as text_file : content = text_file . read ( ) return content | Reads text file contents | 37 | 5 |
248,861 | def save_text_to_file ( content : str , path : str ) : with open ( path , mode = 'w' ) as text_file : text_file . write ( content ) | Saves text to file | 42 | 5 |
248,862 | def get_amount_in_base_currency ( self , currency : str , amount : Decimal ) -> Decimal : assert isinstance ( amount , Decimal ) # If this is already the base currency, do nothing. if currency == self . get_default_currency ( ) . mnemonic : return amount agg = self . get_currency_aggregate_by_symbol ( currency ) if not... | Calculates the amount in base currency | 181 | 8 |
248,863 | def get_default_currency ( self ) -> Commodity : result = None if self . default_currency : result = self . default_currency else : def_currency = self . __get_default_currency ( ) self . default_currency = def_currency result = def_currency return result | returns the book default currency | 63 | 6 |
248,864 | def get_book_currencies ( self ) -> List [ Commodity ] : query = ( self . currencies_query . order_by ( Commodity . mnemonic ) ) return query . all ( ) | Returns currencies used in the book | 46 | 6 |
248,865 | def get_currency_aggregate_by_symbol ( self , symbol : str ) -> CurrencyAggregate : currency = self . get_by_symbol ( symbol ) result = self . get_currency_aggregate ( currency ) return result | Creates currency aggregate for the given currency symbol | 52 | 9 |
248,866 | def get_by_symbol ( self , symbol : str ) -> Commodity : assert isinstance ( symbol , str ) query = ( self . currencies_query . filter ( Commodity . mnemonic == symbol ) ) return query . one ( ) | Loads currency by symbol | 55 | 5 |
248,867 | def import_fx_rates ( self , rates : List [ PriceModel ] ) : have_new_rates = False base_currency = self . get_default_currency ( ) for rate in rates : assert isinstance ( rate , PriceModel ) currency = self . get_by_symbol ( rate . symbol ) amount = rate . value # Do not import duplicate prices. # todo: if the price d... | Imports the given prices into database . Write operation! | 368 | 11 |
248,868 | def __get_default_currency ( self ) : # If we are on Windows, read from registry. if sys . platform == "win32" : # read from registry def_curr = self . book [ "default-currency" ] = self . __get_default_currency_windows ( ) else : # return the currency from locale. # todo: Read the preferences on other operating system... | Read the default currency from GnuCash preferences | 117 | 9 |
248,869 | def __get_registry_key ( self , key ) : import winreg root = winreg . OpenKey ( winreg . HKEY_CURRENT_USER , r'SOFTWARE\GSettings\org\gnucash\general' , 0 , winreg . KEY_READ ) [ pathname , regtype ] = ( winreg . QueryValueEx ( root , key ) ) winreg . CloseKey ( root ) return pathname | Read currency from windows registry | 94 | 5 |
248,870 | def get_for_accounts ( self , accounts : List [ Account ] ) : account_ids = [ acc . guid for acc in accounts ] query = ( self . query . filter ( Split . account_guid . in_ ( account_ids ) ) ) splits = query . all ( ) return splits | Get all splits for the given accounts | 65 | 7 |
248,871 | def __get_model_for_portfolio_value ( input_model : PortfolioValueInputModel ) -> PortfolioValueViewModel : result = PortfolioValueViewModel ( ) result . filter = input_model ref_datum = Datum ( ) ref_datum . from_datetime ( input_model . as_of_date ) ref_date = ref_datum . end_of_day ( ) result . stock_rows = [ ] with... | loads the data for portfolio value | 231 | 6 |
248,872 | def __load_settings ( self ) : #file_path = path.relpath(settings_file_path) #file_path = path.abspath(settings_file_path) file_path = self . file_path try : self . data = json . load ( open ( file_path ) ) except FileNotFoundError : print ( "Could not load" , file_path ) | Load settings from . json file | 86 | 6 |
248,873 | def file_exists ( self ) -> bool : cfg_path = self . file_path assert cfg_path return path . isfile ( cfg_path ) | Check if the settings file exists or not | 37 | 8 |
248,874 | def save ( self ) : content = self . dumps ( ) fileutils . save_text_to_file ( content , self . file_path ) | Saves the settings contents | 32 | 5 |
248,875 | def database_path ( self ) : filename = self . database_filename db_path = ":memory:" if filename == ":memory:" else ( path . abspath ( path . join ( __file__ , "../.." , ".." , "data" , filename ) ) ) return db_path | Full database path . Includes the default location + the database filename . | 66 | 13 |
248,876 | def file_path ( self ) -> str : user_dir = self . __get_user_path ( ) file_path = path . abspath ( path . join ( user_dir , self . FILENAME ) ) return file_path | Settings file absolute path | 52 | 4 |
248,877 | def dumps ( self ) -> str : return json . dumps ( self . data , sort_keys = True , indent = 4 ) | Dumps the json content as a string | 27 | 8 |
248,878 | def __copy_template ( self ) : import shutil template_filename = "settings.json.template" template_path = path . abspath ( path . join ( __file__ , ".." , ".." , "config" , template_filename ) ) settings_path = self . file_path shutil . copyfile ( template_path , settings_path ) self . __ensure_file_exists ( ) | Copy the settings template into the user s directory | 92 | 9 |
248,879 | def is_not_empty ( self , value , strict = False ) : value = stringify ( value ) if value is not None : return self . shout ( 'Value %r is empty' , strict , value ) | if value is not empty | 46 | 5 |
248,880 | def is_numeric ( self , value , strict = False ) : value = stringify ( value ) if value is not None : if value . isnumeric ( ) : return self . shout ( 'value %r is not numeric' , strict , value ) | if value is numeric | 54 | 4 |
248,881 | def is_integer ( self , value , strict = False ) : if value is not None : if isinstance ( value , numbers . Number ) : return value = stringify ( value ) if value is not None and value . isnumeric ( ) : return self . shout ( 'value %r is not an integer' , strict , value ) | if value is an integer | 71 | 5 |
248,882 | def match_date ( self , value , strict = False ) : value = stringify ( value ) try : parse ( value ) except Exception : self . shout ( 'Value %r is not a valid date' , strict , value ) | if value is a date | 49 | 5 |
248,883 | def match_regexp ( self , value , q , strict = False ) : value = stringify ( value ) mr = re . compile ( q ) if value is not None : if mr . match ( value ) : return self . shout ( '%r not matching the regexp %r' , strict , value , q ) | if value matches a regexp q | 72 | 7 |
248,884 | def has_length ( self , value , q , strict = False ) : value = stringify ( value ) if value is not None : if len ( value ) == q : return self . shout ( 'Value %r not matching length %r' , strict , value , q ) | if value has a length of q | 59 | 7 |
248,885 | def must_contain ( self , value , q , strict = False ) : if value is not None : if value . find ( q ) != - 1 : return self . shout ( 'Value %r does not contain %r' , strict , value , q ) | if value must contain q | 56 | 5 |
248,886 | def extract ( context , data ) : with context . http . rehash ( data ) as result : file_path = result . file_path content_type = result . content_type extract_dir = random_filename ( context . work_path ) if content_type in ZIP_MIME_TYPES : extracted_files = extract_zip ( file_path , extract_dir ) elif content_type in ... | Extract a compressed file | 274 | 5 |
248,887 | def size ( cls , crawler ) : key = make_key ( 'queue_pending' , crawler ) return unpack_int ( conn . get ( key ) ) | Total operations pending for this crawler | 39 | 7 |
248,888 | def read_word ( image , whitelist = None , chars = None , spaces = False ) : from tesserocr import PyTessBaseAPI api = PyTessBaseAPI ( ) api . SetPageSegMode ( 8 ) if whitelist is not None : api . SetVariable ( "tessedit_char_whitelist" , whitelist ) api . SetImage ( image ) api . Recognize ( ) guess = api . GetUTF8Tex... | OCR a single word from an image . Useful for captchas . Image should be pre - processed to remove noise etc . | 157 | 26 |
248,889 | def read_char ( image , whitelist = None ) : from tesserocr import PyTessBaseAPI api = PyTessBaseAPI ( ) api . SetPageSegMode ( 10 ) if whitelist is not None : api . SetVariable ( "tessedit_char_whitelist" , whitelist ) api . SetImage ( image ) api . Recognize ( ) return api . GetUTF8Text ( ) . strip ( ) | OCR a single character from an image . Useful for captchas . | 95 | 15 |
248,890 | def get ( self , name , default = None ) : value = self . params . get ( name , default ) if isinstance ( value , str ) : value = os . path . expandvars ( value ) return value | Get a configuration value and expand environment variables . | 47 | 9 |
248,891 | def emit ( self , rule = 'pass' , stage = None , data = { } , delay = None , optional = False ) : if stage is None : stage = self . stage . handlers . get ( rule ) if optional and stage is None : return if stage is None or stage not in self . crawler . stages : self . log . info ( "No next stage: %s (%s)" % ( stage , r... | Invoke the next stage either based on a handling rule or by calling the pass rule by default . | 125 | 20 |
248,892 | def recurse ( self , data = { } , delay = None ) : return self . emit ( stage = self . stage . name , data = data , delay = delay ) | Have a stage invoke itself with a modified set of arguments . | 37 | 12 |
248,893 | def execute ( self , data ) : if Crawl . is_aborted ( self . crawler , self . run_id ) : return try : Crawl . operation_start ( self . crawler , self . stage , self . run_id ) self . log . info ( '[%s->%s(%s)]: %s' , self . crawler . name , self . stage . name , self . stage . method_name , self . run_id ) return self ... | Execute the crawler and create a database record of having done so . | 160 | 15 |
248,894 | def skip_incremental ( self , * criteria ) : if not self . incremental : return False # this is pure convenience, and will probably backfire at some point. key = make_key ( * criteria ) if key is None : return False if self . check_tag ( key ) : return True self . set_tag ( key , None ) return False | Perform an incremental check on a set of criteria . | 75 | 11 |
248,895 | def store_data ( self , data , encoding = 'utf-8' ) : path = random_filename ( self . work_path ) try : with open ( path , 'wb' ) as fh : if isinstance ( data , str ) : data = data . encode ( encoding ) if data is not None : fh . write ( data ) return self . store_file ( path ) finally : try : os . unlink ( path ) exce... | Put the given content into a file possibly encoding it as UTF - 8 in the process . | 102 | 18 |
248,896 | def check_due ( self ) : if self . disabled : return False if self . is_running : return False if self . delta is None : return False last_run = self . last_run if last_run is None : return True now = datetime . utcnow ( ) if now > last_run + self . delta : return True return False | Check if the last execution of this crawler is older than the scheduled interval . | 76 | 16 |
248,897 | def flush ( self ) : Queue . flush ( self ) Event . delete ( self ) Crawl . flush ( self ) | Delete all run - time data generated by this crawler . | 26 | 12 |
248,898 | def run ( self , incremental = None , run_id = None ) : state = { 'crawler' : self . name , 'run_id' : run_id , 'incremental' : settings . INCREMENTAL } if incremental is not None : state [ 'incremental' ] = incremental # Cancel previous runs: self . cancel ( ) # Flush out previous events: Event . delete ( self ) Queue... | Queue the execution of a particular crawler . | 104 | 9 |
248,899 | def fetch ( context , data ) : url = data . get ( 'url' ) attempt = data . pop ( 'retry_attempt' , 1 ) try : result = context . http . get ( url , lazy = True ) rules = context . get ( 'rules' , { 'match_all' : { } } ) if not Rule . get_rule ( rules ) . apply ( result ) : context . log . info ( 'Fetch skip: %r' , resul... | Do an HTTP GET on the url specified in the inbound data . | 353 | 14 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.