idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
19,000 | def publish_changes ( self , etype , echid ) : _LOGGING . debug ( '%s Update: %s, %s' , self . name , etype , self . fetch_attributes ( etype , echid ) ) signal = 'ValueChanged.{}' . format ( self . cam_id ) sender = '{}.{}' . format ( etype , echid ) if dispatcher : dispatcher . send ( signal = signal , sender = sende... | Post updates for specified event type . |
19,001 | def start ( self ) : self . _timer = Timer ( self . time , self . handler ) self . _timer . daemon = True self . _timer . start ( ) return | Starts the watchdog timer . |
19,002 | def flip_motion ( self , value ) : if value : self . cam . enable_motion_detection ( ) else : self . cam . disable_motion_detection ( ) | Toggle motion detection |
19,003 | def update_callback ( self , msg ) : print ( 'Callback: {}' . format ( msg ) ) print ( '{}:{} @ {}' . format ( self . name , self . _sensor_state ( ) , self . _sensor_last_update ( ) ) ) | get updates . |
19,004 | def render ( self , renderer = None , ** kwargs ) : return Markup ( get_renderer ( current_app , renderer ) ( ** kwargs ) . visit ( self ) ) | Render the navigational item using a renderer . |
19,005 | def visit_object ( self , node ) : if current_app . debug : return tags . comment ( 'no implementation in {} to render {}' . format ( self . __class__ . __name__ , node . __class__ . __name__ , ) ) return '' | Fallback rendering for objects . |
19,006 | def register_renderer ( app , id , renderer , force = True ) : renderers = app . extensions . setdefault ( 'nav_renderers' , { } ) if force : renderers [ id ] = renderer else : renderers . setdefault ( id , renderer ) | Registers a renderer on the application . |
19,007 | def get_renderer ( app , id ) : renderer = app . extensions . get ( 'nav_renderers' , { } ) [ id ] if isinstance ( renderer , tuple ) : mod_name , cls_name = renderer mod = import_module ( mod_name ) cls = mod for name in cls_name . split ( '.' ) : cls = getattr ( cls , name ) return cls return renderer | Retrieve a renderer . |
19,008 | def init_app ( self , app ) : if not hasattr ( app , 'extensions' ) : app . extensions = { } app . extensions [ 'nav' ] = self app . add_template_global ( self . elems , 'nav' ) for args in self . _renderers : register_renderer ( app , * args ) | Initialize an application . |
19,009 | def navigation ( self , id = None ) : def wrapper ( f ) : self . register_element ( id or f . __name__ , f ) return f return wrapper | Function decorator for navbar registration . |
19,010 | def renderer ( self , id = None , force = True ) : def _ ( cls ) : name = cls . __name__ sn = name [ 0 ] + re . sub ( r'([A-Z])' , r'_\1' , name [ 1 : ] ) self . _renderers . append ( ( id or sn . lower ( ) , cls , force ) ) return cls return _ | Class decorator for Renderers . |
19,011 | def parse_time ( time ) : if isinstance ( time , datetime . datetime ) : return time return datetime . datetime . strptime ( time , DATETIME_FORMAT_OPENVPN ) | Parses date and time from input string in OpenVPN logging format . |
19,012 | def decrypt ( self , key , dev_addr ) : sequence_counter = int ( self . FCntUp ) return loramac_decrypt ( self . payload_hex , sequence_counter , key , dev_addr ) | Decrypt the actual payload in this LoraPayload . |
19,013 | def parse ( self ) : status = Status ( ) self . expect_line ( Status . client_list . label ) status . updated_at = self . expect_tuple ( Status . updated_at . label ) status . client_list . update ( { text_type ( c . real_address ) : c for c in self . _parse_fields ( Client , Status . routing_table . label ) } ) status... | Parses the status log . |
19,014 | def parse_status ( status_log , encoding = 'utf-8' ) : if isinstance ( status_log , bytes ) : status_log = status_log . decode ( encoding ) parser = LogParser . fromstring ( status_log ) return parser . parse ( ) | Parses the status log of OpenVPN . |
19,015 | def version ( self ) : res = self . client . service . Version ( ) return '.' . join ( [ ustr ( x ) for x in res [ 0 ] ] ) | Return version of the TR DWE . |
19,016 | def system_info ( self ) : res = self . client . service . SystemInfo ( ) res = { ustr ( x [ 0 ] ) : x [ 1 ] for x in res [ 0 ] } to_str = lambda arr : '.' . join ( [ ustr ( x ) for x in arr [ 0 ] ] ) res [ 'OSVersion' ] = to_str ( res [ 'OSVersion' ] ) res [ 'RuntimeVersion' ] = to_str ( res [ 'RuntimeVersion' ] ) res... | Return system information . |
19,017 | def sources ( self ) : res = self . client . service . Sources ( self . userdata , 0 ) return [ ustr ( x [ 0 ] ) for x in res [ 0 ] ] | Return available sources of data . |
19,018 | def status ( self , record = None ) : if record is not None : self . last_status = { 'Source' : ustr ( record [ 'Source' ] ) , 'StatusType' : ustr ( record [ 'StatusType' ] ) , 'StatusCode' : record [ 'StatusCode' ] , 'StatusMessage' : ustr ( record [ 'StatusMessage' ] ) , 'Request' : ustr ( record [ 'Instrument' ] ) }... | Extract status from the retrieved data and save it as a property of an object . If record with data is not specified then the status of previous operation is returned . |
19,019 | def construct_request ( ticker , fields = None , date = None , date_from = None , date_to = None , freq = None ) : if isinstance ( ticker , basestring ) : request = ticker elif hasattr ( ticker , '__len__' ) : request = ',' . join ( ticker ) else : raise ValueError ( 'ticker should be either string or list/array of str... | Construct a request string for querying TR DWE . |
19,020 | def fetch ( self , tickers , fields = None , date = None , date_from = None , date_to = None , freq = 'D' , only_data = True , static = False ) : if static : query = self . construct_request ( tickers , fields , date , freq = 'REP' ) else : query = self . construct_request ( tickers , fields , date , date_from , date_t... | Fetch data from TR DWE . |
19,021 | def get_OHLCV ( self , ticker , date = None , date_from = None , date_to = None ) : data , meta = self . fetch ( ticker + "~OHLCV" , None , date , date_from , date_to , 'D' , only_data = False ) return data | Get Open High Low Close prices and daily Volume for a given ticker . |
19,022 | def get_constituents ( self , index_ticker , date = None , only_list = False ) : if date is not None : str_date = pd . to_datetime ( date ) . strftime ( '%m%y' ) else : str_date = '' fields = '~REP~=NAME' if only_list else '~XREF' query = 'L' + index_ticker + str_date + fields raw = self . request ( query ) res , metad... | Get a list of all constituents of a given index . |
19,023 | def check_encoding_chars ( encoding_chars ) : if not isinstance ( encoding_chars , collections . MutableMapping ) : raise InvalidEncodingChars required = { 'FIELD' , 'COMPONENT' , 'SUBCOMPONENT' , 'REPETITION' , 'ESCAPE' } missing = required - set ( encoding_chars . keys ( ) ) if missing : raise InvalidEncodingChars ( ... | Validate the given encoding chars |
19,024 | def check_validation_level ( validation_level ) : if validation_level not in ( VALIDATION_LEVEL . QUIET , VALIDATION_LEVEL . STRICT , VALIDATION_LEVEL . TOLERANT ) : raise UnknownValidationLevel | Validate the given validation level |
19,025 | def load_library ( version ) : check_version ( version ) module_name = SUPPORTED_LIBRARIES [ version ] lib = sys . modules . get ( module_name ) if lib is None : lib = importlib . import_module ( module_name ) return lib | Load the correct module according to the version |
19,026 | def load_reference ( name , element_type , version ) : lib = load_library ( version ) ref = lib . get ( name , element_type ) return ref | Look for an element of the given type name and version and return its reference structure |
19,027 | def find_reference ( name , element_types , version ) : lib = load_library ( version ) ref = lib . find ( name , element_types ) return ref | Look for an element of the given name and version into the given types and return its reference structure |
19,028 | def get_date_info ( value ) : fmt = _get_date_format ( value ) dt_value = _datetime_obj_factory ( value , fmt ) return dt_value , fmt | Returns the datetime object and the format of the date in input |
19,029 | def get_timestamp_info ( value ) : value , offset = _split_offset ( value ) fmt , microsec = _get_timestamp_format ( value ) dt_value = _datetime_obj_factory ( value , fmt ) return dt_value , fmt , offset , microsec | Returns the datetime object the format the offset and the microsecond of the timestamp in input |
19,030 | def get_datetime_info ( value ) : date_value , offset = _split_offset ( value ) date_format = _get_date_format ( date_value [ : 8 ] ) try : timestamp_form , microsec = _get_timestamp_format ( date_value [ 8 : ] ) except ValueError : if not date_value [ 8 : ] : timestamp_form , microsec = '' , 4 else : raise ValueError ... | Returns the datetime object the format the offset and the microsecond of the datetime in input |
19,031 | def is_base_datatype ( datatype , version = None ) : if version is None : version = get_default_version ( ) lib = load_library ( version ) return lib . is_base_datatype ( datatype ) | Check if the given datatype is a base datatype of the specified version |
19,032 | def get_ordered_children ( self ) : ordered_keys = self . element . ordered_children if self . element . ordered_children is not None else [ ] children = [ self . indexes . get ( k , None ) for k in ordered_keys ] return children | Return the list of children ordered according to the element structure |
19,033 | def insert ( self , index , child , by_name_index = - 1 ) : if self . _can_add_child ( child ) : try : if by_name_index == - 1 : self . indexes [ child . name ] . append ( child ) else : self . indexes [ child . name ] . insert ( by_name_index , child ) except KeyError : self . indexes [ child . name ] = [ child ] self... | Add the child at the given index |
19,034 | def append ( self , child ) : if self . _can_add_child ( child ) : if self . element == child . parent : self . _remove_from_traversal_index ( child ) self . list . append ( child ) try : self . indexes [ child . name ] . append ( child ) except KeyError : self . indexes [ child . name ] = [ child ] elif self . element... | Append the given child |
19,035 | def set ( self , name , value , index = - 1 ) : if isinstance ( value , ElementProxy ) : value = value [ 0 ] . to_er7 ( ) name = name . upper ( ) reference = None if name is None else self . element . find_child_reference ( name ) child_ref , child_name = ( None , None ) if reference is None else ( reference [ 'ref' ] ... | Assign the value to the child having the given name at the index position |
19,036 | def remove ( self , child ) : try : if self . element == child . traversal_parent : self . _remove_from_traversal_index ( child ) else : self . _remove_from_index ( child ) self . list . remove ( child ) except : raise | Remove the given child from both child list and child indexes |
19,037 | def remove_by_name ( self , name , index = 0 ) : child = self . child_at_index ( name , index ) self . remove ( child ) return child | Remove the child having the given name at the given position |
19,038 | def child_at_index ( self , name , index ) : def _finder ( n , i ) : try : return self . indexes [ n ] [ i ] except ( KeyError , IndexError ) : try : return self . traversal_indexes [ n ] [ i ] except ( KeyError , IndexError ) : return None child = _finder ( name , index ) child_name = None if name is None else self . ... | Return the child named name at the given index |
19,039 | def create_element ( self , name , traversal_parent = False , reference = None ) : if reference is None : reference = self . element . find_child_reference ( name ) if reference is not None : cls = reference [ 'cls' ] element_name = reference [ 'name' ] kwargs = { 'reference' : reference [ 'ref' ] , 'validation_level' ... | Create an element having the given name |
19,040 | def _find_name ( self , name ) : name = name . upper ( ) element = self . element . find_child_reference ( name ) return element [ 'name' ] if element is not None else None | Find the reference of a child having the given name |
19,041 | def get_structure ( element , reference = None ) : if reference is None : try : reference = load_reference ( element . name , element . classname , element . version ) except ( ChildNotFound , KeyError ) : raise InvalidName ( element . classname , element . name ) if not isinstance ( reference , collections . Sequence ... | Get the element structure |
19,042 | def _parse_structure ( element , reference ) : data = { 'reference' : reference } content_type = reference [ 0 ] if content_type in ( 'sequence' , 'choice' ) : children = reference [ 1 ] ordered_children = [ ] structure = { } structure_by_longname = { } repetitions = { } counters = collections . defaultdict ( int ) for... | Parse the given reference |
19,043 | def to_mllp ( self , encoding_chars = None , trailing_children = False ) : if encoding_chars is None : encoding_chars = self . encoding_chars return "{0}{1}{2}{3}{2}" . format ( MLLP_ENCODING_CHARS . SB , self . to_er7 ( encoding_chars , trailing_children ) , MLLP_ENCODING_CHARS . CR , MLLP_ENCODING_CHARS . EB ) | Returns the er7 representation of the message wrapped with mllp encoding characters |
19,044 | def get_app ( self ) : ctx = connection_stack . top if ctx is not None : return ctx . app if self . app is not None : return self . app raise RuntimeError ( 'Flask application not registered on Redis instance ' 'and no applcation bound to current context' ) | Get current app from Flast stack to use . |
19,045 | def init_app ( self , app , config_prefix = None ) : if 'redis' not in app . extensions : app . extensions [ 'redis' ] = { } self . config_prefix = config_prefix = config_prefix or 'REDIS' if config_prefix in app . extensions [ 'redis' ] : raise ValueError ( 'Already registered config prefix {0!r}.' . format ( config_p... | Actual method to read redis settings from app configuration initialize Redis connection and copy all public connection methods to current instance . |
19,046 | def _build_connection_args ( self , klass ) : bases = [ base for base in klass . __bases__ if base is not object ] all_args = [ ] for cls in [ klass ] + bases : try : args = inspect . getfullargspec ( cls . __init__ ) . args except AttributeError : args = inspect . getargspec ( cls . __init__ ) . args for arg in args :... | Read connection args spec exclude self from list of possible |
19,047 | def _include_public_methods ( self , connection ) : for attr in dir ( connection ) : value = getattr ( connection , attr ) if attr . startswith ( '_' ) or not callable ( value ) : continue self . __dict__ [ attr ] = self . _wrap_public_method ( attr ) | Include public methods from Redis connection to current instance . |
19,048 | def prepare ( self ) : self . __make_scubadir ( ) if self . is_remote_docker : raise ScubaError ( 'Remote docker not supported (DOCKER_HOST is set)' ) self . __setup_native_run ( ) self . env_vars . update ( self . context . environment ) | Prepare to run the docker command |
19,049 | def add_env ( self , name , val ) : if name in self . env_vars : raise KeyError ( name ) self . env_vars [ name ] = val | Add an environment variable to the docker run invocation |
19,050 | def __locate_scubainit ( self ) : pkg_path = os . path . dirname ( __file__ ) self . scubainit_path = os . path . join ( pkg_path , 'scubainit' ) if not os . path . isfile ( self . scubainit_path ) : raise ScubaError ( 'scubainit not found at "{}"' . format ( self . scubainit_path ) ) | Determine path to scubainit binary |
19,051 | def __load_config ( self ) : try : top_path , top_rel = find_config ( ) self . config = load_config ( os . path . join ( top_path , SCUBA_YML ) ) except ConfigNotFoundError as cfgerr : if not self . image_override : raise ScubaError ( str ( cfgerr ) ) top_path , top_rel = os . getcwd ( ) , '' self . config = ScubaConfi... | Find and load . scuba . yml |
19,052 | def __make_scubadir ( self ) : self . __scubadir_hostpath = tempfile . mkdtemp ( prefix = 'scubadir' ) self . __scubadir_contpath = '/.scuba' self . add_volume ( self . __scubadir_hostpath , self . __scubadir_contpath ) | Make temp directory where all ancillary files are bind - mounted |
19,053 | def __setup_native_run ( self ) : self . vol_opts = [ 'z' ] self . add_env ( 'SCUBAINIT_UMASK' , '{:04o}' . format ( get_umask ( ) ) ) if not self . as_root : self . add_env ( 'SCUBAINIT_UID' , os . getuid ( ) ) self . add_env ( 'SCUBAINIT_GID' , os . getgid ( ) ) if self . verbose : self . add_env ( 'SCUBAINIT_VERBOSE... | Normally if the user provides no command to docker run the image s default CMD is run . Because we set the entrypiont scuba must emulate the default behavior itself . |
19,054 | def open_scubadir_file ( self , name , mode ) : path = os . path . join ( self . __scubadir_hostpath , name ) assert not os . path . exists ( path ) mkdir_p ( os . path . dirname ( path ) ) f = File ( path , mode ) f . container_path = os . path . join ( self . __scubadir_contpath , name ) return f | Opens a file in the scubadir |
19,055 | def copy_scubadir_file ( self , name , source ) : dest = os . path . join ( self . __scubadir_hostpath , name ) assert not os . path . exists ( dest ) shutil . copy2 ( source , dest ) return os . path . join ( self . __scubadir_contpath , name ) | Copies source into the scubadir |
19,056 | def format_cmdline ( args , maxwidth = 80 ) : maxwidth -= 2 def lines ( ) : line = '' for a in ( shell_quote ( a ) for a in args ) : if len ( line ) + len ( a ) + 1 > maxwidth : yield line line = '' if line : line += ' ' + a else : line = a yield line return ' \\\n' . join ( lines ( ) ) | Format args into a shell - quoted command line . |
19,057 | def parse_env_var ( s ) : parts = s . split ( '=' , 1 ) if len ( parts ) == 2 : k , v = parts return ( k , v ) k = parts [ 0 ] return ( k , os . getenv ( k , '' ) ) | Parse an environment variable string |
19,058 | def __wrap_docker_exec ( func ) : def call ( * args , ** kwargs ) : try : return func ( * args , ** kwargs ) except OSError as e : if e . errno == errno . ENOENT : raise DockerExecuteError ( 'Failed to execute docker. Is it installed?' ) raise return call | Wrap a function to raise DockerExecuteError on ENOENT |
19,059 | def docker_inspect ( image ) : args = [ 'docker' , 'inspect' , '--type' , 'image' , image ] p = Popen ( args , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) stdout , stderr = p . communicate ( ) stdout = stdout . decode ( 'utf-8' ) stderr = stderr . decode ( 'utf-8' ) if not p . returncode == 0 : if 'no suc... | Inspects a docker image |
19,060 | def docker_pull ( image ) : args = [ 'docker' , 'pull' , image ] ret = call ( args ) if ret != 0 : raise DockerError ( 'Failed to pull image "{}"' . format ( image ) ) | Pulls an image |
19,061 | def get_image_command ( image ) : info = docker_inspect_or_pull ( image ) try : return info [ 'Config' ] [ 'Cmd' ] except KeyError as ke : raise DockerError ( 'Failed to inspect image: JSON result missing key {}' . format ( ke ) ) | Gets the default command for an image |
19,062 | def get_image_entrypoint ( image ) : info = docker_inspect_or_pull ( image ) try : return info [ 'Config' ] [ 'Entrypoint' ] except KeyError as ke : raise DockerError ( 'Failed to inspect image: JSON result missing key {}' . format ( ke ) ) | Gets the image entrypoint |
19,063 | def make_vol_opt ( hostdir , contdir , options = None ) : vol = '--volume={}:{}' . format ( hostdir , contdir ) if options != None : if isinstance ( options , str ) : options = ( options , ) vol += ':' + ',' . join ( options ) return vol | Generate a docker volume option |
19,064 | def find_config ( ) : cross_fs = 'SCUBA_DISCOVERY_ACROSS_FILESYSTEM' in os . environ path = os . getcwd ( ) rel = '' while True : if os . path . exists ( os . path . join ( path , SCUBA_YML ) ) : return path , rel if not cross_fs and os . path . ismount ( path ) : msg = '{} not found here or any parent up to mount poin... | Search up the diretcory hierarchy for . scuba . yml |
19,065 | def _process_script_node ( node , name ) : if isinstance ( node , basestring ) : return [ node ] if isinstance ( node , dict ) : script = node . get ( 'script' ) if not script : raise ConfigError ( "{}: must have a 'script' subkey" . format ( name ) ) if isinstance ( script , list ) : return script if isinstance ( scri... | Process a script - type node |
19,066 | def process_command ( self , command ) : result = ScubaContext ( ) result . script = None result . image = self . image result . entrypoint = self . entrypoint result . environment = self . environment . copy ( ) if command : alias = self . aliases . get ( command [ 0 ] ) if not alias : result . script = [ shell_quote_... | Processes a user command using aliases |
19,067 | def open ( self , filename ) : self . close ( ) self . _f = open ( filename , 'rb' ) self . _dbtype = struct . unpack ( 'B' , self . _f . read ( 1 ) ) [ 0 ] self . _dbcolumn = struct . unpack ( 'B' , self . _f . read ( 1 ) ) [ 0 ] self . _dbyear = struct . unpack ( 'B' , self . _f . read ( 1 ) ) [ 0 ] self . _dbmonth =... | Opens a database file |
19,068 | def _parse_addr ( self , addr ) : ipv = 0 try : socket . inet_pton ( socket . AF_INET6 , addr ) if addr . lower ( ) . startswith ( '::ffff:' ) : try : socket . inet_pton ( socket . AF_INET , addr ) ipv = 4 except : ipv = 6 else : ipv = 6 except : socket . inet_pton ( socket . AF_INET , addr ) ipv = 4 return ipv | Parses address and returns IP version . Raises exception on invalid argument |
19,069 | def rates_for_location ( self , postal_code , location_deets = None ) : request = self . _get ( "rates/" + postal_code , location_deets ) return self . responder ( request ) | Shows the sales tax rates for a given location . |
19,070 | def tax_for_order ( self , order_deets ) : request = self . _post ( 'taxes' , order_deets ) return self . responder ( request ) | Shows the sales tax that should be collected for a given order . |
19,071 | def list_orders ( self , params = None ) : request = self . _get ( 'transactions/orders' , params ) return self . responder ( request ) | Lists existing order transactions . |
19,072 | def show_order ( self , order_id ) : request = self . _get ( 'transactions/orders/' + str ( order_id ) ) return self . responder ( request ) | Shows an existing order transaction . |
19,073 | def create_order ( self , order_deets ) : request = self . _post ( 'transactions/orders' , order_deets ) return self . responder ( request ) | Creates a new order transaction . |
19,074 | def update_order ( self , order_id , order_deets ) : request = self . _put ( "transactions/orders/" + str ( order_id ) , order_deets ) return self . responder ( request ) | Updates an existing order transaction . |
19,075 | def delete_order ( self , order_id ) : request = self . _delete ( "transactions/orders/" + str ( order_id ) ) return self . responder ( request ) | Deletes an existing order transaction . |
19,076 | def list_refunds ( self , params = None ) : request = self . _get ( 'transactions/refunds' , params ) return self . responder ( request ) | Lists existing refund transactions . |
19,077 | def show_refund ( self , refund_id ) : request = self . _get ( 'transactions/refunds/' + str ( refund_id ) ) return self . responder ( request ) | Shows an existing refund transaction . |
19,078 | def create_refund ( self , refund_deets ) : request = self . _post ( 'transactions/refunds' , refund_deets ) return self . responder ( request ) | Creates a new refund transaction . |
19,079 | def update_refund ( self , refund_id , refund_deets ) : request = self . _put ( 'transactions/refunds/' + str ( refund_id ) , refund_deets ) return self . responder ( request ) | Updates an existing refund transaction . |
19,080 | def delete_refund ( self , refund_id ) : request = self . _delete ( 'transactions/refunds/' + str ( refund_id ) ) return self . responder ( request ) | Deletes an existing refund transaction . |
19,081 | def list_customers ( self , params = None ) : request = self . _get ( 'customers' , params ) return self . responder ( request ) | Lists existing customers . |
19,082 | def show_customer ( self , customer_id ) : request = self . _get ( 'customers/' + str ( customer_id ) ) return self . responder ( request ) | Shows an existing customer . |
19,083 | def create_customer ( self , customer_deets ) : request = self . _post ( 'customers' , customer_deets ) return self . responder ( request ) | Creates a new customer . |
19,084 | def update_customer ( self , customer_id , customer_deets ) : request = self . _put ( "customers/" + str ( customer_id ) , customer_deets ) return self . responder ( request ) | Updates an existing customer . |
19,085 | def delete_customer ( self , customer_id ) : request = self . _delete ( "customers/" + str ( customer_id ) ) return self . responder ( request ) | Deletes an existing customer . |
19,086 | def validate_address ( self , address_deets ) : request = self . _post ( 'addresses/validate' , address_deets ) return self . responder ( request ) | Validates a customer address and returns back a collection of address matches . |
19,087 | def validate ( self , vat_deets ) : request = self . _get ( 'validation' , vat_deets ) return self . responder ( request ) | Validates an existing VAT identification number against VIES . |
19,088 | def choose_plural ( amount , variants ) : try : if isinstance ( variants , six . string_types ) : uvariants = smart_text ( variants , encoding ) else : uvariants = [ smart_text ( v , encoding ) for v in variants ] res = numeral . choose_plural ( amount , uvariants ) except Exception as err : try : default_variant = var... | Choose proper form for plural . |
19,089 | def in_words ( amount , gender = None ) : try : res = numeral . in_words ( amount , getattr ( numeral , str ( gender ) , None ) ) except Exception as err : res = default_value % { 'error' : err , 'value' : str ( amount ) } return res | In - words representation of amount . |
19,090 | def sum_string ( amount , gender , items ) : try : if isinstance ( items , six . string_types ) : uitems = smart_text ( items , encoding , default_uvalue ) else : uitems = [ smart_text ( i , encoding ) for i in items ] res = numeral . sum_string ( amount , getattr ( numeral , str ( gender ) , None ) , uitems ) except E... | in_words and choose_plural in a one flask Makes in - words representation of value with choosing correct form of noun . |
19,091 | def rl_cleanspaces ( x ) : patterns = ( ( r' +([\.,?!\)]+)' , r'\1' ) , ( r'([\.,?!\)]+)([^\.!,?\)]+)' , r'\1 \2' ) , ( r'(\S+)\s*(\()\s*(\S+)' , r'\1 (\3' ) , ) return os . linesep . join ( ' ' . join ( part for part in line . split ( ' ' ) if part ) for line in _sub_patterns ( patterns , x ) . split ( os . linesep ) ... | Clean double spaces trailing spaces heading spaces spaces before punctuations |
19,092 | def rl_quotes ( x ) : patterns = ( ( re . compile ( r'((?:^|\s))(")((?u))' , re . UNICODE ) , u'\\1\xab\\3' ) , ( re . compile ( r'(\S)(")((?u))' , re . UNICODE ) , u'\\1\xbb\\3' ) , ( re . compile ( r'((?:^|\s))(\')((?u))' , re . UNICODE ) , u'\\1\u201c\\3' ) , ( re . compile ( r'(\S)(\')((?u))' , re . UNICODE ) , u'\... | Replace quotes by typographic quotes |
19,093 | def distance_of_time ( from_time , accuracy = 1 ) : try : to_time = None if conf . settings . USE_TZ : to_time = utils . timezone . now ( ) res = dt . distance_of_time_in_words ( from_time , accuracy , to_time ) except Exception as err : try : default_distance = "%s seconds" % str ( int ( time . time ( ) - from_time ) ... | Display distance of time from current time . |
19,094 | def ru_strftime ( date , format = "%d.%m.%Y" , inflected_day = False , preposition = False ) : try : res = dt . ru_strftime ( format , date , inflected = True , inflected_day = inflected_day , preposition = preposition ) except Exception as err : try : default_date = date . strftime ( format ) except Exception : defaul... | Russian strftime formats date with given format . |
19,095 | def ru_strftime ( format = u"%d.%m.%Y" , date = None , inflected = False , inflected_day = False , preposition = False ) : if date is None : date = datetime . datetime . today ( ) weekday = date . weekday ( ) prepos = preposition and DAY_NAMES [ weekday ] [ 3 ] or u"" month_idx = inflected and 2 or 1 day_idx = ( inflec... | Russian strftime without locale |
19,096 | def _get_float_remainder ( fvalue , signs = 9 ) : check_positive ( fvalue ) if isinstance ( fvalue , six . integer_types ) : return "0" if isinstance ( fvalue , Decimal ) and fvalue . as_tuple ( ) [ 2 ] == 0 : return "0" signs = min ( signs , len ( FRACTIONS ) ) remainder = str ( fvalue ) . split ( '.' ) [ 1 ] iremaind... | Get remainder of float i . e . 2 . 05 - > 05 |
19,097 | def choose_plural ( amount , variants ) : if isinstance ( variants , six . text_type ) : variants = split_values ( variants ) check_length ( variants , 3 ) amount = abs ( amount ) if amount % 10 == 1 and amount % 100 != 11 : variant = 0 elif amount % 10 >= 2 and amount % 10 <= 4 and ( amount % 100 < 10 or amount % 100 ... | Choose proper case depending on amount |
19,098 | def get_plural ( amount , variants , absence = None ) : if amount or absence is None : return u"%d %s" % ( amount , choose_plural ( amount , variants ) ) else : return absence | Get proper case with value |
19,099 | def in_words ( amount , gender = None ) : check_positive ( amount ) if isinstance ( amount , Decimal ) and amount . as_tuple ( ) [ 2 ] == 0 : amount = int ( amount ) if gender is None : args = ( amount , ) else : args = ( amount , gender ) if isinstance ( amount , six . integer_types ) : return in_words_int ( * args ) ... | Numeral in words |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.