idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
61,500
def parse ( self , data ) : graph = self . _init_graph ( ) for link in data . get_inner_links ( ) : if link . status != libcnml . libcnml . Status . WORKING : continue interface_a , interface_b = link . getLinkedInterfaces ( ) source = interface_a . ipv4 dest = interface_b . ipv4 graph . add_edge ( source , dest , weig...
Converts a CNML structure to a NetworkX Graph object which is then returned .
61,501
def parse ( self , data ) : graph = self . _init_graph ( ) if 'topology' not in data : raise ParserError ( 'Parse error, "topology" key not found' ) elif 'mid' not in data : raise ParserError ( 'Parse error, "mid" key not found' ) if 'config' in data : version_info = data [ 'config' ] [ 'olsrdVersion' ] . replace ( ' '...
Converts a dict representing an OLSR 0 . 6 . x topology to a NetworkX Graph object which is then returned . Additionally checks for config data in order to determine version and revision .
61,502
def _txtinfo_to_jsoninfo ( self , data ) : data = data . replace ( 'INFINITE' , 'inf' ) lines = data . split ( '\n' ) try : start = lines . index ( 'Table: Topology' ) + 2 end = lines [ start : ] . index ( '' ) + start except ValueError : raise ParserError ( 'Unrecognized format' ) topology_lines = lines [ start : end ...
converts olsr 1 txtinfo format to jsoninfo
61,503
def check_for_launchpad ( old_vendor , name , urls ) : if old_vendor != "pypi" : return '' for url in urls : try : return re . match ( r"https?://launchpad.net/([\w.\-]+)" , url ) . groups ( ) [ 0 ] except AttributeError : continue return ''
Check if the project is hosted on launchpad .
61,504
def check_switch_vendor ( old_vendor , name , urls , _depth = 0 ) : if _depth > 3 : return "" new_name = check_for_launchpad ( old_vendor , name , urls ) if new_name : return "launchpad" , new_name return "" , ""
Check if the project should switch vendors . E . g project pushed on pypi but changelog on launchpad .
61,505
def check_pil ( func ) : def __wrapper ( * args , ** kwargs ) : root = kwargs . get ( 'root' ) if not Image : if root and root . get_opt ( 'warn' ) : warn ( "Images manipulation require PIL" ) return 'none' return func ( * args , ** kwargs ) return __wrapper
PIL module checking decorator .
61,506
def _mix ( color1 , color2 , weight = 0.5 , ** kwargs ) : weight = float ( weight ) c1 = color1 . value c2 = color2 . value p = 0.0 if weight < 0 else 1.0 if weight > 1 else weight w = p * 2 - 1 a = c1 [ 3 ] - c2 [ 3 ] w1 = ( ( w if ( w * a == - 1 ) else ( w + a ) / ( 1 + w * a ) ) + 1 ) / 2.0 w2 = 1 - w1 q = [ w1 , w1...
Mixes two colors together .
61,507
def _hsla ( h , s , l , a , ** kwargs ) : res = colorsys . hls_to_rgb ( float ( h ) , float ( l ) , float ( s ) ) return ColorValue ( [ x * 255.0 for x in res ] + [ float ( a ) ] )
HSL with alpha channel color value .
61,508
def _hue ( color , ** kwargs ) : h = colorsys . rgb_to_hls ( * [ x / 255.0 for x in color . value [ : 3 ] ] ) [ 0 ] return NumberValue ( h * 360.0 )
Get hue value of HSL color .
61,509
def _lightness ( color , ** kwargs ) : l = colorsys . rgb_to_hls ( * [ x / 255.0 for x in color . value [ : 3 ] ] ) [ 1 ] return NumberValue ( ( l * 100 , '%' ) )
Get lightness value of HSL color .
61,510
def _saturation ( color , ** kwargs ) : s = colorsys . rgb_to_hls ( * [ x / 255.0 for x in color . value [ : 3 ] ] ) [ 2 ] return NumberValue ( ( s * 100 , '%' ) )
Get saturation value of HSL color .
61,511
def load ( path , cache = None , precache = False ) : parser = Stylesheet ( cache ) return parser . load ( path , precache = precache )
Parse from file .
61,512
def parse ( self , target ) : if isinstance ( target , ContentNode ) : if target . name : self . parent = target self . name . parse ( self ) self . name += target . name target . ruleset . append ( self ) self . root . cache [ 'rset' ] [ str ( self . name ) . split ( ) [ 0 ] ] . add ( self ) super ( Ruleset , self ) ....
Parse nested rulesets and save it in cache .
61,513
def parse ( self , target ) : if not isinstance ( target , Node ) : parent = ContentNode ( None , None , [ ] ) parent . parse ( target ) target = parent super ( Declaration , self ) . parse ( target ) self . name = str ( self . data [ 0 ] ) while isinstance ( target , Declaration ) : self . name = '-' . join ( ( str ( ...
Parse nested declaration .
61,514
def parse ( self , target ) : super ( VarDefinition , self ) . parse ( target ) if isinstance ( self . parent , ParseNode ) : self . parent . ctx . update ( { self . name : self . expression . value } ) self . root . set_var ( self )
Update root and parent context .
61,515
def set_var ( self , vardef ) : if not ( vardef . default and self . cache [ 'ctx' ] . get ( vardef . name ) ) : self . cache [ 'ctx' ] [ vardef . name ] = vardef . expression . value
Set variable to global stylesheet context .
61,516
def set_opt ( self , name , value ) : self . cache [ 'opts' ] [ name ] = value if name == 'compress' : self . cache [ 'delims' ] = self . def_delims if not value else ( '' , '' , '' )
Set option .
61,517
def update ( self , cache ) : self . cache [ 'delims' ] = cache . get ( 'delims' ) self . cache [ 'opts' ] . update ( cache . get ( 'opts' ) ) self . cache [ 'rset' ] . update ( cache . get ( 'rset' ) ) self . cache [ 'mix' ] . update ( cache . get ( 'mix' ) ) map ( self . set_var , cache [ 'ctx' ] . values ( ) )
Update self cache from other .
61,518
def scan ( src ) : assert isinstance ( src , ( unicode_ , bytes_ ) ) try : nodes = STYLESHEET . parseString ( src , parseAll = True ) return nodes except ParseBaseException : err = sys . exc_info ( ) [ 1 ] print ( err . line , file = sys . stderr ) print ( " " * ( err . column - 1 ) + "^" , file = sys . stderr ) print ...
Scan scss from string and return nodes .
61,519
def loads ( self , src ) : assert isinstance ( src , ( unicode_ , bytes_ ) ) nodes = self . scan ( src . strip ( ) ) self . parse ( nodes ) return '' . join ( map ( str , nodes ) )
Compile css from scss string .
61,520
def load ( self , f , precache = None ) : precache = precache or self . get_opt ( 'cache' ) or False nodes = None if isinstance ( f , file_ ) : path = os . path . abspath ( f . name ) else : path = os . path . abspath ( f ) f = open ( f ) cache_path = os . path . splitext ( path ) [ 0 ] + '.ccss' if precache and os . p...
Compile scss from file . File is string path of file object .
61,521
def load_config ( filename , filepath = '' ) : FILE = path . join ( filepath , filename ) try : cfg . read ( FILE ) global _loaded _loaded = True except : print ( "configfile not found." )
Loads config file
61,522
def emoji ( string ) : __entities = { } __value = [ ] __mean = [ ] __location = [ ] flag = True try : pro_string = str ( string ) for pos , ej in enumerate ( pro_string ) : if ej in emo_unicode . UNICODE_EMO : try : __value . append ( ej ) __mean . append ( emo_unicode . UNICODE_EMO [ ej ] ) __location . append ( [ pos...
emot . emoji is use to detect emoji from text
61,523
def emoticons ( string ) : __entities = [ ] flag = True try : pattern = u'(' + u'|' . join ( k for k in emo_unicode . EMOTICONS ) + u')' __entities = [ ] __value = [ ] __location = [ ] matches = re . finditer ( r"%s" % pattern , str ( string ) ) for et in matches : __value . append ( et . group ( ) . strip ( ) ) __loca...
emot . emoticons is use to detect emoticons from text
61,524
def init_app ( self , app , add_context_processor = True ) : if not hasattr ( app , 'login_manager' ) : self . login_manager . init_app ( app , add_context_processor = add_context_processor ) self . login_manager . login_message = None self . login_manager . needs_refresh_message = None self . login_manager . unauthori...
Initialize with app configuration
61,525
def login_url ( self , params = None , ** kwargs ) : kwargs . setdefault ( 'response_type' , 'code' ) kwargs . setdefault ( 'access_type' , 'online' ) if 'prompt' not in kwargs : kwargs . setdefault ( 'approval_prompt' , 'auto' ) scopes = kwargs . pop ( 'scopes' , self . scopes . split ( ',' ) ) if USERINFO_PROFILE_SCO...
Return login url with params encoded in state
61,526
def unauthorized_callback ( self ) : return redirect ( self . login_url ( params = dict ( next = request . url ) ) )
Redirect to login url with next param set as request . url
61,527
def get_access_token ( self , refresh_token ) : token = requests . post ( GOOGLE_OAUTH2_TOKEN_URL , data = dict ( refresh_token = refresh_token , grant_type = 'refresh_token' , client_id = self . client_id , client_secret = self . client_secret , ) ) . json ( ) if not token or token . get ( 'error' ) : return return to...
Use a refresh token to obtain a new access token
61,528
def oauth2callback ( self , view_func ) : @ wraps ( view_func ) def decorated ( * args , ** kwargs ) : params = { } if 'state' in request . args : params . update ( ** self . parse_state ( request . args . get ( 'state' ) ) ) if params . pop ( 'sig' , None ) != make_secure_token ( ** params ) : return self . login_mana...
Decorator for OAuth2 callback . Calls GoogleLogin . login then passes results to view_func .
61,529
def complete ( text , state ) : for cmd in COMMANDS : if cmd . startswith ( text ) : if not state : return cmd else : state -= 1
Auto complete scss constructions in interactive mode .
61,530
def validate_args ( self ) : from . . mixins import ModelMixin for arg in ( "instance" , "decider" , "identifier" , "fields" , "default_language" ) : if getattr ( self , arg ) is None : raise AttributeError ( "%s must not be None" % arg ) if not isinstance ( self . instance , ( ModelMixin , ) ) : raise ImproperlyConfig...
Validates arguments .
61,531
def active_language ( self ) : if self . _language is not None : return self . _language current = utils . get_language ( ) if current in self . supported_languages : return current return self . default_language
Returns active language .
61,532
def translation_instances ( self ) : return [ instance for k , v in six . iteritems ( self . instance . _linguist_translations ) for instance in v . values ( ) ]
Returns translation instances .
61,533
def get_cache ( self , instance , translation = None , language = None , field_name = None , field_value = None , ) : is_new = bool ( instance . pk is None ) try : cached_obj = instance . _linguist_translations [ field_name ] [ language ] if not cached_obj . field_name : cached_obj . field_name = field_name if not cach...
Returns translation from cache .
61,534
def set_cache ( self , instance = None , translation = None , language = None , field_name = None , field_value = None , ) : if instance is not None and translation is not None : cached_obj = CachedTranslation . from_object ( translation ) instance . _linguist_translations [ translation . field_name ] [ translation . l...
Add a new translation into the cache .
61,535
def _filter_or_exclude ( self , negate , * args , ** kwargs ) : from . models import Translation new_args = self . get_cleaned_args ( args ) new_kwargs = self . get_cleaned_kwargs ( kwargs ) translation_args = self . get_translation_args ( args ) translation_kwargs = self . get_translation_kwargs ( kwargs ) has_linguis...
Overrides default behavior to handle linguist fields .
61,536
def has_linguist_kwargs ( self , kwargs ) : for k in kwargs : if self . is_linguist_lookup ( k ) : return True return False
Parses the given kwargs and returns True if they contain linguist lookups .
61,537
def has_linguist_args ( self , args ) : linguist_args = [ ] for arg in args : condition = self . _get_linguist_condition ( arg ) if condition : linguist_args . append ( condition ) return bool ( linguist_args )
Parses the given args and returns True if they contain linguist lookups .
61,538
def get_translation_args ( self , args ) : translation_args = [ ] for arg in args : condition = self . _get_linguist_condition ( arg , transform = True ) if condition : translation_args . append ( condition ) return translation_args
Returns linguist args from model args .
61,539
def is_linguist_lookup ( self , lookup ) : field = utils . get_field_name_from_lookup ( lookup ) if ( field not in self . concrete_field_names and field in self . linguist_field_names ) : return True return False
Returns true if the given lookup is a valid linguist lookup .
61,540
def _get_linguist_condition ( self , condition , reverse = False , transform = False ) : if isinstance ( condition , Q ) : children = [ ] for child in condition . children : parsed = self . _get_linguist_condition ( condition = child , reverse = reverse , transform = transform ) if parsed is not None : if ( isinstance ...
Parses Q tree and returns linguist lookups or model lookups if reverse is True .
61,541
def get_cleaned_args ( self , args ) : if not args : return args cleaned_args = [ ] for arg in args : condition = self . _get_linguist_condition ( arg , True ) if condition : cleaned_args . append ( condition ) return cleaned_args
Returns positional arguments for related model query .
61,542
def get_cleaned_kwargs ( self , kwargs ) : cleaned_kwargs = kwargs . copy ( ) if kwargs is not None : for k in kwargs : if self . is_linguist_lookup ( k ) : del cleaned_kwargs [ k ] return cleaned_kwargs
Returns concrete field lookups .
61,543
def with_translations ( self , ** kwargs ) : force = kwargs . pop ( "force" , False ) if self . _prefetch_translations_done and force is False : return self self . _prefetched_translations_cache = utils . get_grouped_translations ( self , ** kwargs ) self . _prefetch_translations_done = True return self . _clone ( )
Prefetches translations .
61,544
def available_languages ( self ) : from . models import Translation return ( Translation . objects . filter ( identifier = self . linguist_identifier , object_id = self . pk ) . values_list ( "language" , flat = True ) . distinct ( ) . order_by ( "language" ) )
Returns available languages .
61,545
def delete_translations ( self , language = None ) : from . models import Translation return Translation . objects . delete_translations ( obj = self , language = language )
Deletes related translations .
61,546
def override_language ( self , language ) : previous_language = self . _linguist . language self . _linguist . language = language yield self . _linguist . language = previous_language
Context manager to override the instance language .
61,547
def validate_meta ( meta ) : if not isinstance ( meta , ( dict , ) ) : raise TypeError ( 'Model Meta "linguist" must be a dict' ) required_keys = ( "identifier" , "fields" ) for key in required_keys : if key not in meta : raise KeyError ( 'Model Meta "linguist" dict requires %s to be defined' , key ) if not isinstance ...
Validates Linguist Meta attribute .
61,548
def default_value_setter ( field ) : def default_value_func_setter ( self , value ) : localized_field = utils . build_localized_field_name ( field , self . _linguist . active_language ) setattr ( self , localized_field , value ) return default_value_func_setter
When setting to the name of the field itself the value in the current language will be set .
61,549
def field_factory ( base_class ) : from . fields import TranslationField class TranslationFieldField ( TranslationField , base_class ) : pass TranslationFieldField . __name__ = "Translation%s" % base_class . __name__ return TranslationFieldField
Takes a field base class and wrap it with TranslationField class .
61,550
def create_translation_field ( translated_field , language ) : cls_name = translated_field . __class__ . __name__ if not isinstance ( translated_field , tuple ( SUPPORTED_FIELDS . keys ( ) ) ) : raise ImproperlyConfigured ( "%s is not supported by Linguist." % cls_name ) translation_class = field_factory ( translated_f...
Takes the original field a given language a decider model and return a Field class for model .
61,551
def connect ( self ) : if self . connected : raise RuntimeError ( '{} is connected already' . format ( self . __class__ . __name__ ) ) if self . closed : raise RuntimeError ( '{} is closed already' . format ( self . __class__ . __name__ ) ) self . connected = True self . _connect ( )
Connect to the drone .
61,552
def close ( self ) : if not self . connected : return if self . closed : return self . closed = True self . _close ( )
Exit all threads and disconnect the drone .
61,553
def _set_flags ( self , ** flags ) : self . _flags = enum . IntEnum ( '_flags' , flags ) self . __dict__ . update ( self . _flags . __members__ ) self . _patch_flag_doc ( )
Set the flags of this argument .
61,554
def delete_translations ( sender , instance , ** kwargs ) : if issubclass ( sender , ( ModelMixin , ) ) : instance . _linguist . decider . objects . filter ( identifier = instance . linguist_identifier , object_id = instance . pk ) . delete ( )
Deletes related instance s translations when instance is deleted .
61,555
def draw_tree ( node , child_iter = lambda n : n . children , text_str = str ) : return LeftAligned ( traverse = Traversal ( get_text = text_str , get_children = child_iter ) , draw = LegacyStyle ( ) ) ( node )
Support asciitree 0 . 2 API .
61,556
def get_language ( ) : lang = _get_language ( ) if not lang : return get_fallback_language ( ) langs = [ l [ 0 ] for l in settings . SUPPORTED_LANGUAGES ] if lang not in langs and "-" in lang : lang = lang . split ( "-" ) [ 0 ] if lang in langs : return lang return settings . DEFAULT_LANGUAGE
Returns an active language code that is guaranteed to be in settings . SUPPORTED_LANGUAGES .
61,557
def activate_language ( instances , language ) : language = ( language if language in get_supported_languages ( ) else get_fallback_language ( ) ) for instance in instances : instance . activate_language ( language )
Activates the given language for the given instances .
61,558
def load_class ( class_path , setting_name = None ) : if not isinstance ( class_path , six . string_types ) : try : class_path , app_label = class_path except : if setting_name : raise exceptions . ImproperlyConfigured ( CLASS_PATH_ERROR % ( setting_name , setting_name ) ) else : raise exceptions . ImproperlyConfigured...
Loads a class given a class_path . The setting value may be a string or a tuple . The setting_name parameter is only there for pretty error output and therefore is optional .
61,559
def get_translation_lookup ( identifier , field , value ) : parts = field . split ( "__" ) transformers = parts [ 1 : ] if len ( parts ) > 1 else None field_name = parts [ 0 ] language = get_fallback_language ( ) name_parts = parts [ 0 ] . split ( "_" ) if len ( name_parts ) > 1 : supported_languages = get_supported_la...
Mapper that takes a language field its value and returns the related lookup for Translation model .
61,560
def get_grouped_translations ( instances , ** kwargs ) : grouped_translations = collections . defaultdict ( list ) if not instances : return grouped_translations if not isinstance ( instances , collections . Iterable ) : instances = [ instances ] if isinstance ( instances , QuerySet ) : model = instances . model else :...
Takes instances and returns grouped translations ready to be set in cache .
61,561
def get_free_udp_port ( ) : import socket sock = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) sock . bind ( ( 'localhost' , 0 ) ) addr = sock . getsockname ( ) sock . close ( ) return addr [ 1 ]
Get a free UDP port .
61,562
def get_available_languages ( self , obj ) : return obj . available_languages if obj is not None else self . model . objects . none ( )
Returns available languages for current object .
61,563
def languages_column ( self , obj ) : languages = self . get_available_languages ( obj ) return '<span class="available-languages">{0}</span>' . format ( " " . join ( languages ) )
Adds languages columns .
61,564
def prefetch_translations ( instances , ** kwargs ) : from . mixins import ModelMixin if not isinstance ( instances , collections . Iterable ) : instances = [ instances ] populate_missing = kwargs . get ( "populate_missing" , True ) grouped_translations = utils . get_grouped_translations ( instances , ** kwargs ) if no...
Prefetches translations for the given instances . Can be useful for a list of instances .
61,565
def get_translations ( self , obj , language = None ) : lookup = { "identifier" : obj . linguist_identifier , "object_id" : obj . pk } if language is not None : lookup [ "language" ] = language return self . get_queryset ( ) . filter ( ** lookup )
Shorcut method to retrieve translations for a given object .
61,566
def takeoff ( self ) : self . send ( at . REF ( at . REF . input . start ) )
Sends the takeoff command .
61,567
def emergency ( self ) : self . send ( at . REF ( at . REF . input . select ) )
Sends the emergency command .
61,568
def move ( self , * , forward = 0 , backward = 0 , left = 0 , right = 0 , up = 0 , down = 0 , cw = 0 , ccw = 0 ) : self . _move ( roll = right - left , pitch = backward - forward , gaz = up - down , yaw = cw - ccw )
Moves the drone .
61,569
def encode ( number , checksum = False , split = 0 ) : number = int ( number ) if number < 0 : raise ValueError ( "number '%d' is not a positive integer" % number ) split = int ( split ) if split < 0 : raise ValueError ( "split '%d' is not a positive integer" % split ) check_symbol = '' if checksum : check_symbol = enc...
Encode an integer into a symbol string .
61,570
def decode ( symbol_string , checksum = False , strict = False ) : symbol_string = normalize ( symbol_string , strict = strict ) if checksum : symbol_string , check_symbol = symbol_string [ : - 1 ] , symbol_string [ - 1 ] number = 0 for symbol in symbol_string : number = number * base + decode_symbols [ symbol ] if che...
Decode an encoded symbol string .
61,571
def normalize ( symbol_string , strict = False ) : if isinstance ( symbol_string , string_types ) : if not PY3 : try : symbol_string = symbol_string . encode ( 'ascii' ) except UnicodeEncodeError : raise ValueError ( "string should only contain ASCII characters" ) else : raise TypeError ( "string is of invalid type %s"...
Normalize an encoded symbol string .
61,572
def setup_requires ( ) : from pkg_resources import parse_version required = [ 'cython>=0.24.0' ] numpy_requirement = 'numpy>=1.7.1' try : import numpy except Exception : required . append ( numpy_requirement ) else : if parse_version ( numpy . __version__ ) < parse_version ( '1.7.1' ) : required . append ( numpy_requir...
Return required packages
61,573
def _build_block_context ( template , context ) : if BLOCK_CONTEXT_KEY not in context . render_context : context . render_context [ BLOCK_CONTEXT_KEY ] = BlockContext ( ) block_context = context . render_context [ BLOCK_CONTEXT_KEY ] for node in template . nodelist : if isinstance ( node , ExtendsNode ) : compiled_pare...
Populate the block context with BlockNodes from parent templates .
61,574
def _render_template_block_nodelist ( nodelist , block_name , context ) : for node in nodelist : if isinstance ( node , BlockNode ) : context . render_context [ BLOCK_CONTEXT_KEY ] . push ( node . name , node ) if node . name == block_name : return node . render ( context ) for attr in node . child_nodelists : try : ne...
Recursively iterate over a node to find the wanted block .
61,575
def render_block_to_string ( template_name , block_name , context = None ) : if isinstance ( template_name , ( tuple , list ) ) : t = loader . select_template ( template_name ) else : t = loader . get_template ( template_name ) context = context or { } if isinstance ( t , DjangoTemplate ) : return django_render_block (...
Loads the given template_name and renders the given block with the given dictionary as context . Returns a string .
61,576
def get_host_path ( root , path , instance = None ) : r_val = resolve_value ( path ) if isinstance ( r_val , dict ) : r_instance = instance or 'default' r_path = resolve_value ( r_val . get ( r_instance ) ) if not r_path : raise ValueError ( "No path defined for instance {0}." . format ( r_instance ) ) else : r_path = ...
Generates the host path for a container volume . If the given path is a dictionary uses the entry of the instance name .
61,577
def run_actions ( self , actions ) : policy = self . _policy for action in actions : config_id = action . config_id config_type = config_id . config_type client_config = policy . clients [ action . client_name ] client = client_config . get_client ( ) c_map = policy . container_maps [ config_id . map_name ] if config_t...
Runs the given lists of attached actions and instance actions on the client .
61,578
def from_client ( cls , client ) : if hasattr ( client , 'client_configuration' ) : return client . client_configuration kwargs = { 'client' : client } for attr in cls . init_kwargs : if hasattr ( client , attr ) : kwargs [ attr ] = getattr ( client , attr ) if hasattr ( client , 'api_version' ) : kwargs [ 'version' ] ...
Constructs a configuration object from an existing client instance . If the client has already been created with a configuration object returns that instance .
61,579
def get_init_kwargs ( self ) : init_kwargs = { } for k in self . init_kwargs : if k in self . core_property_set : init_kwargs [ k ] = getattr ( self , k ) elif k in self : init_kwargs [ k ] = self [ k ] return init_kwargs
Generates keyword arguments for creating a new Docker client instance .
61,580
def get_client ( self ) : client = self . _client if not client : self . _client = client = self . client_constructor ( ** self . get_init_kwargs ( ) ) client . client_configuration = self updated_version = getattr ( client , 'api_version' , None ) if updated_version : self . version = updated_version return client
Retrieves or creates a client instance from this configuration object . If instantiated from this configuration the resulting object is also cached in the property client and a reference to this configuration is stored on the client object .
61,581
def exec_commands ( self , action , c_name , run_cmds , ** kwargs ) : client = action . client exec_results = [ ] for run_cmd in run_cmds : cmd = run_cmd . cmd cmd_user = run_cmd . user log . debug ( "Creating exec command in container %s with user %s: %s." , c_name , cmd_user , cmd ) ec_kwargs = self . get_exec_create...
Runs a single command inside a container .
61,582
def exec_container_commands ( self , action , c_name , ** kwargs ) : config_cmds = action . config . exec_commands if not config_cmds : return None return self . exec_commands ( action , c_name , run_cmds = config_cmds )
Runs all configured commands of a container configuration inside the container instance .
61,583
def prepare_path ( path , replace_space , replace_sep , expandvars , expanduser ) : r_path = path if expandvars : r_path = os . path . expandvars ( r_path ) if expanduser : r_path = os . path . expanduser ( r_path ) if replace_sep and os . sep != posixpath . sep : r_path = r_path . replace ( os . path . sep , posixpath...
Performs os . path replacement operations on a path string .
61,584
def format_command ( cmd , shell = False ) : def _split_cmd ( ) : line = None for part in cmd . split ( ' ' ) : line = part if line is None else '{0} {1}' . format ( line , part ) if part [ - 1 ] != '\\' : yield line line = None if line is not None : yield line if cmd in ( [ ] , '' ) : return '[]' if shell : if isinsta...
Converts a command line to the notation as used in a Dockerfile CMD and ENTRYPOINT command . In shell notation this returns a simple string whereas by default it returns a JSON - list format with the command and arguments .
61,585
def format_expose ( expose ) : if isinstance ( expose , six . string_types ) : return expose , elif isinstance ( expose , collections . Iterable ) : return map ( six . text_type , expose ) return six . text_type ( expose ) ,
Converts a port number or multiple port numbers as used in the Dockerfile EXPOSE command to a tuple .
61,586
def add_file ( self , src_path , dst_path = None , ctx_path = None , replace_space = True , expandvars = False , expanduser = False , remove_final = False ) : if dst_path is None : head , tail = os . path . split ( src_path ) if not tail : tail = os . path . split ( head ) [ 1 ] if not tail : ValueError ( "Could not ge...
Adds a file to the Docker build . An ADD command is inserted and the path is stored for later packaging of the context tarball .
61,587
def write ( self , input_str ) : self . check_not_finalized ( ) if isinstance ( input_str , six . binary_type ) : self . fileobj . write ( input_str ) else : self . fileobj . write ( input_str . encode ( 'utf-8' ) )
Adds content to the Dockerfile .
61,588
def merge_dependency ( self , item , resolve_parent , parents ) : dep = [ ] for parent_key in parents : if item == parent_key : raise CircularDependency ( item , True ) if parent_key . config_type == ItemType . CONTAINER : parent_dep = resolve_parent ( parent_key ) if item in parent_dep : raise CircularDependency ( ite...
Merge dependencies of current configuration with further dependencies ; in this instance it means that in case of container configuration first parent dependencies are checked and then immediate dependencies of the current configuration should be added to the list but without duplicating any entries .
61,589
def load_map ( stream , name = None , check_integrity = True , check_duplicates = True ) : map_dict = yaml . safe_load ( stream ) if isinstance ( map_dict , dict ) : map_name = name or map_dict . pop ( 'name' , None ) if not map_name : raise ValueError ( "No map name provided, and none found in YAML stream." ) return C...
Loads a ContainerMap configuration from a YAML document stream .
61,590
def load_clients ( stream , configuration_class = ClientConfiguration ) : client_dict = yaml . safe_load ( stream ) if isinstance ( client_dict , dict ) : return { client_name : configuration_class ( ** client_config ) for client_name , client_config in six . iteritems ( client_dict ) } raise ValueError ( "Valid config...
Loads client configurations from a YAML document stream .
61,591
def load_map_file ( filename , name = None , check_integrity = True ) : if name == '' : base_name = os . path . basename ( filename ) map_name , __ , __ = os . path . basename ( base_name ) . rpartition ( os . path . extsep ) else : map_name = name with open ( filename , 'r' ) as f : return load_map ( f , name = map_na...
Loads a ContainerMap configuration from a YAML file .
61,592
def load_clients_file ( filename , configuration_class = ClientConfiguration ) : with open ( filename , 'r' ) as f : return load_clients ( f , configuration_class = configuration_class )
Loads client configurations from a YAML file .
61,593
def get_state_generator ( self , action_name , policy , kwargs ) : state_generator_cls = self . generators [ action_name ] [ 0 ] state_generator = state_generator_cls ( policy , kwargs ) return state_generator
Returns the state generator to be used for the given action .
61,594
def get_action_generator ( self , action_name , policy , kwargs ) : action_generator_cls = self . generators [ action_name ] [ 1 ] action_generator = action_generator_cls ( policy , kwargs ) return action_generator
Returns the action generator to be used for the given action .
61,595
def get_states ( self , action_name , config_name , instances = None , map_name = None , ** kwargs ) : policy = self . get_policy ( ) _set_forced_update_ids ( kwargs , policy . container_maps , map_name or self . _default_map , instances ) state_generator = self . get_state_generator ( action_name , policy , kwargs ) l...
Returns a generator of states in relation to the indicated action .
61,596
def get_actions ( self , action_name , config_name , instances = None , map_name = None , ** kwargs ) : policy = self . get_policy ( ) action_generator = self . get_action_generator ( action_name , policy , kwargs ) for state in self . get_states ( action_name , config_name , instances = instances , map_name = map_name...
Returns the entire set of actions performed for the indicated action name .
61,597
def create ( self , container , instances = None , map_name = None , ** kwargs ) : return self . run_actions ( 'create' , container , instances = instances , map_name = map_name , ** kwargs )
Creates container instances for a container configuration .
61,598
def start ( self , container , instances = None , map_name = None , ** kwargs ) : return self . run_actions ( 'start' , container , instances = instances , map_name = map_name , ** kwargs )
Starts instances for a container configuration .
61,599
def restart ( self , container , instances = None , map_name = None , ** kwargs ) : return self . run_actions ( 'restart' , container , instances = instances , map_name = map_name , ** kwargs )
Restarts instances for a container configuration .