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 = sender ) self . _do_update_callback ( '{}.{}.{}' . format ( self . cam_id , etype , echid ) )
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 . routing_table . update ( { text_type ( r . virtual_address ) : r for r in self . _parse_fields ( Routing , Status . global_stats . label ) } ) status . global_stats = GlobalStats ( ) status . global_stats . max_bcast_mcast_queue_len = self . expect_tuple ( GlobalStats . max_bcast_mcast_queue_len . label ) self . expect_line ( self . terminator ) return 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 [ 'Version' ] = to_str ( res [ 'Version' ] ) res [ 'Name' ] = ustr ( res [ 'Name' ] ) res [ 'Server' ] = ustr ( res [ 'Server' ] ) res [ 'LocalNameCheck' ] = ustr ( res [ 'LocalNameCheck' ] ) res [ 'UserHostAddress' ] = ustr ( res [ 'UserHostAddress' ] ) return 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' ] ) } return self . last_status
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 strings' ) if fields is not None : if isinstance ( fields , basestring ) : request += '~=' + fields elif isinstance ( fields , list ) and len ( fields ) > 0 : request += '~=' + ',' . join ( fields ) if date is not None : request += '~@' + pd . to_datetime ( date ) . strftime ( '%Y-%m-%d' ) else : if date_from is not None : request += '~' + pd . to_datetime ( date_from ) . strftime ( '%Y-%m-%d' ) if date_to is not None : request += '~:' + pd . to_datetime ( date_to ) . strftime ( '%Y-%m-%d' ) if freq is not None : request += '~' + freq return request
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_to , freq ) raw = self . request ( query ) if static : data , metadata = self . parse_record_static ( raw ) elif isinstance ( tickers , basestring ) or len ( tickers ) == 1 : data , metadata = self . parse_record ( raw ) elif hasattr ( tickers , '__len__' ) : metadata = pd . DataFrame ( ) data = { } for indx in range ( len ( tickers ) ) : dat , meta = self . parse_record ( raw , indx ) data [ tickers [ indx ] ] = dat metadata = metadata . append ( meta , ignore_index = False ) data = pd . concat ( data ) else : raise DatastreamException ( ( 'First argument should be either ticker or ' 'list of tickers' ) ) if only_data : return data else : return data , metadata
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 , metadata = self . parse_record_static ( raw ) return res
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 ( 'Missing required encoding chars' ) values = [ v for k , v in encoding_chars . items ( ) if k in required ] if len ( values ) > len ( set ( values ) ) : raise InvalidEncodingChars ( 'Found duplicate encoding chars' )
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 ( '{0} is not an HL7 valid date value' . format ( value ) ) fmt = '{0}{1}' . format ( date_format , timestamp_form ) dt_value = _datetime_obj_factory ( date_value , fmt ) return dt_value , fmt , offset , microsec
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 . list . insert ( index , child )
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 == child . traversal_parent : try : self . traversal_indexes [ child . name ] . append ( child ) except KeyError : self . traversal_indexes [ child . name ] = [ child ]
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' ] , reference [ 'name' ] ) if isinstance ( value , basestring ) : child = self . element . parse_child ( value , child_name = child_name , reference = child_ref ) elif isinstance ( value , Element ) : child = value elif isinstance ( value , BaseDataType ) : child = self . create_element ( name , False , reference ) child . value = value else : raise ChildNotValid ( value , child_name ) if child . name != child_name : raise ChildNotValid ( value , child_name ) child_to_remove = self . child_at_index ( child_name , index ) if child_to_remove is None : self . append ( child ) else : self . replace_child ( child_to_remove , child ) self . element . set_parent_to_traversal ( )
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 . _find_name ( name ) if child_name != name : child = _finder ( child_name , index ) return child
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' : self . element . validation_level , 'version' : self . element . version } if not traversal_parent : kwargs [ 'parent' ] = self . element else : kwargs [ 'traversal_parent' ] = self . element return cls ( element_name , ** kwargs ) else : raise ChildNotFound ( name )
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 ) : raise Exception return ElementFinder . _parse_structure ( element , reference )
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 c in children : child_name , child_ref , cardinality , cls = c k = child_name if child_name not in structure else '{0}_{1}' . format ( child_name , counters [ child_name ] ) structure [ k ] = { "ref" : child_ref , "name" : k , "cls" : element . child_classes [ cls ] } try : structure_by_longname [ child_ref [ 3 ] ] = structure [ k ] except IndexError : pass counters [ child_name ] += 1 repetitions [ k ] = cardinality ordered_children . append ( k ) data [ 'repetitions' ] = repetitions data [ 'ordered_children' ] = ordered_children data [ 'structure_by_name' ] = structure data [ 'structure_by_longname' ] = structure_by_longname if len ( reference ) > 5 : datatype , long_name , table , max_length = reference [ 2 : ] data [ 'datatype' ] = datatype data [ 'table' ] = table data [ 'long_name' ] = long_name return data
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_prefix ) ) converters = { 'port' : int } convert = lambda arg , value : ( converters [ arg ] ( value ) if arg in converters else value ) key = lambda param : '{0}_{1}' . format ( config_prefix , param ) klass = app . config . get ( key ( 'CLASS' ) , RedisClass ) if isinstance ( klass , string_types ) : klass = import_string ( klass ) url = app . config . get ( key ( 'URL' ) ) if url : urlparse . uses_netloc . append ( 'redis' ) url = urlparse . urlparse ( url ) app . config [ key ( 'HOST' ) ] = url . hostname app . config [ key ( 'PORT' ) ] = url . port or 6379 app . config [ key ( 'USER' ) ] = url . username app . config [ key ( 'PASSWORD' ) ] = url . password db = url . path . replace ( '/' , '' ) app . config [ key ( 'DB' ) ] = db if db . isdigit ( ) else None host = app . config . get ( key ( 'HOST' ) ) if host and ( host . startswith ( 'file://' ) or host . startswith ( '/' ) ) : app . config . pop ( key ( 'HOST' ) ) app . config [ key ( 'UNIX_SOCKET_PATH' ) ] = host args = self . _build_connection_args ( klass ) kwargs = dict ( [ ( arg , convert ( arg , app . config [ key ( arg . upper ( ) ) ] ) ) for arg in args if key ( arg . upper ( ) ) in app . config ] ) connection = klass ( ** kwargs ) app . extensions [ 'redis' ] [ config_prefix ] = connection self . _include_public_methods ( connection )
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 : if arg in all_args : continue all_args . append ( arg ) all_args . remove ( 'self' ) return all_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 = ScubaConfig ( image = None ) except ConfigError as cfgerr : raise ScubaError ( str ( cfgerr ) ) self . add_volume ( top_path , top_path ) self . set_workdir ( os . path . join ( top_path , top_rel ) ) self . add_env ( 'SCUBA_ROOT' , top_path )
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' , 1 ) scubainit_cpath = self . copy_scubadir_file ( 'scubainit' , self . scubainit_path ) for name in ( 'root' , 'user' , ) : self . __generate_hook_script ( name ) if sys . stdout . isatty ( ) and sys . stdin . isatty ( ) : self . add_option ( '--tty' ) try : context = self . config . process_command ( self . user_command ) except ConfigError as cfgerr : raise ScubaError ( str ( cfgerr ) ) if self . image_override : context . image = self . image_override if not context . script : verbose_msg ( 'No user command; getting command from image' ) default_cmd = get_image_command ( context . image ) if not default_cmd : raise ScubaError ( 'No command given and no image-specified command' ) verbose_msg ( '{} Cmd: "{}"' . format ( context . image , default_cmd ) ) context . script = [ shell_quote_cmd ( default_cmd ) ] self . add_option ( '--entrypoint={}' . format ( scubainit_cpath ) ) self . docker_cmd = [ ] if self . entrypoint_override is not None : if self . entrypoint_override != '' : self . docker_cmd = [ self . entrypoint_override ] elif context . entrypoint is not None : if context . entrypoint != '' : self . docker_cmd = [ context . entrypoint ] else : ep = get_image_entrypoint ( context . image ) if ep : self . docker_cmd = ep with self . open_scubadir_file ( 'command.sh' , 'wt' ) as f : self . docker_cmd += [ '/bin/sh' , f . container_path ] writeln ( f , '#!/bin/sh' ) writeln ( f , '# Auto-generated from scuba' ) writeln ( f , 'set -e' ) for cmd in context . script : writeln ( f , cmd ) self . context = context
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 such image' in stderr . lower ( ) : raise NoSuchImageError ( image ) raise DockerError ( 'Failed to inspect image: {}' . format ( stderr . strip ( ) ) ) return json . loads ( stdout ) [ 0 ]
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 point {}' . format ( SCUBA_YML , path ) + '\nStopping at filesystem boundary (SCUBA_DISCOVERY_ACROSS_FILESYSTEM not set).' raise ConfigNotFoundError ( msg ) path , rest = os . path . split ( path ) if not rest : raise ConfigNotFoundError ( '{} not found here or any parent directories' . format ( SCUBA_YML ) ) rel = os . path . join ( rest , rel )
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 ( script , basestring ) : return [ script ] raise ConfigError ( "{}.script: must be a string or list" . format ( name ) ) raise ConfigError ( "{}: must be string or dict" . format ( name ) )
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_cmd ( command ) ] else : if alias . image : result . image = alias . image if alias . entrypoint is not None : result . entrypoint = alias . entrypoint if alias . environment : result . environment . update ( alias . environment ) if len ( alias . script ) > 1 : if len ( command ) > 1 : raise ConfigError ( 'Additional arguments not allowed with multi-line aliases' ) result . script = alias . script else : command . pop ( 0 ) result . script = [ alias . script [ 0 ] + ' ' + shell_quote_cmd ( command ) ] result . script = flatten_list ( result . script ) return result
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 = struct . unpack ( 'B' , self . _f . read ( 1 ) ) [ 0 ] self . _dbday = struct . unpack ( 'B' , self . _f . read ( 1 ) ) [ 0 ] self . _ipv4dbcount = struct . unpack ( '<I' , self . _f . read ( 4 ) ) [ 0 ] self . _ipv4dbaddr = struct . unpack ( '<I' , self . _f . read ( 4 ) ) [ 0 ] self . _ipv6dbcount = struct . unpack ( '<I' , self . _f . read ( 4 ) ) [ 0 ] self . _ipv6dbaddr = struct . unpack ( '<I' , self . _f . read ( 4 ) ) [ 0 ] self . _ipv4indexbaseaddr = struct . unpack ( '<I' , self . _f . read ( 4 ) ) [ 0 ] self . _ipv6indexbaseaddr = struct . unpack ( '<I' , self . _f . read ( 4 ) ) [ 0 ]
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 = variants except Exception : default_variant = "" res = default_value % { 'error' : err , 'value' : default_variant } return res
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 Exception as err : res = default_value % { 'error' : err , 'value' : str ( amount ) } return res
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'\\1\u201d\\3' ) , ) return _sub_patterns ( patterns , x )
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 ) ) except Exception : default_distance = "" res = default_value % { 'error' : err , 'value' : default_distance } return res
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 : default_date = str ( date ) res = default_value % { 'error' : err , 'value' : default_date } return res
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 = ( inflected_day or preposition ) and 2 or 1 if u'%b' in format or u'%B' in format : format = format . replace ( u'%d' , six . text_type ( date . day ) ) format = format . replace ( u'%a' , prepos + DAY_NAMES [ weekday ] [ 0 ] ) format = format . replace ( u'%A' , prepos + DAY_NAMES [ weekday ] [ day_idx ] ) format = format . replace ( u'%b' , MONTH_NAMES [ date . month - 1 ] [ 0 ] ) format = format . replace ( u'%B' , MONTH_NAMES [ date . month - 1 ] [ month_idx ] ) if six . PY2 : s_format = format . encode ( "utf-8" ) s_res = date . strftime ( s_format ) u_res = s_res . decode ( "utf-8" ) else : u_res = date . strftime ( format ) return u_res
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 ] iremainder = int ( remainder ) orig_remainder = remainder factor = len ( str ( remainder ) ) - signs if factor > 0 : iremainder = int ( round ( iremainder / ( 10.0 ** factor ) ) ) format = "%%0%dd" % min ( len ( remainder ) , signs ) remainder = format % iremainder if len ( remainder ) > signs : raise ValueError ( "Signs overflow: I can't round only fractional part \ of %s to fit %s in %d signs" % ( str ( fvalue ) , orig_remainder , signs ) ) return remainder
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 >= 20 ) : variant = 1 else : variant = 2 return variants [ variant ]
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 ) elif isinstance ( amount , ( float , Decimal ) ) : return in_words_float ( * args ) else : raise TypeError ( "amount should be number type (int, long, float, Decimal), got %s" % type ( amount ) )
Numeral in words