idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
238,000 | def _remove_remote_data_bags ( ) : data_bags_path = os . path . join ( env . node_work_path , 'data_bags' ) if exists ( data_bags_path ) : sudo ( "rm -rf {0}" . format ( data_bags_path ) ) | Remove remote data bags so it won t leak any sensitive information |
238,001 | def _configure_node ( ) : print ( "" ) msg = "Cooking..." if env . parallel : msg = "[{0}]: {1}" . format ( env . host_string , msg ) print ( msg ) with settings ( hide ( 'stdout' , 'warnings' , 'running' ) , warn_only = True ) : sudo ( "mv {0} {0}.1" . format ( LOGFILE ) ) cmd = "RUBYOPT=-Ku chef-solo" if whyrun : cmd... | Exectutes chef - solo to apply roles and recipes to a node |
238,002 | def _resolve_hostname ( name ) : if env . ssh_config is None : return name elif not os . path . exists ( os . path . join ( "nodes" , name + ".json" ) ) : resolved_name = env . ssh_config . lookup ( name ) [ 'hostname' ] if os . path . exists ( os . path . join ( "nodes" , resolved_name + ".json" ) ) : name = resolved_... | Returns resolved hostname using the ssh config |
238,003 | def get_environment ( name ) : if name == "_default" : return env_from_template ( name ) filename = os . path . join ( "environments" , name + ".json" ) try : with open ( filename ) as f : try : return json . loads ( f . read ( ) ) except ValueError as e : msg = 'LittleChef found the following error in' msg += ' "{0}":... | Returns a JSON environment file as a dictionary |
238,004 | def get_environments ( ) : envs = [ ] for root , subfolders , files in os . walk ( 'environments' ) : for filename in files : if filename . endswith ( ".json" ) : path = os . path . join ( root [ len ( 'environments' ) : ] , filename [ : - len ( '.json' ) ] ) envs . append ( get_environment ( path ) ) return sorted ( e... | Gets all environments found in the environments directory |
238,005 | def get_node ( name , merged = False ) : if merged : node_path = os . path . join ( "data_bags" , "node" , name . replace ( '.' , '_' ) + ".json" ) else : node_path = os . path . join ( "nodes" , name + ".json" ) if os . path . exists ( node_path ) : with open ( node_path , 'r' ) as f : try : node = json . loads ( f . ... | Returns a JSON node file as a dictionary |
238,006 | def get_nodes_with_role ( role_name , environment = None ) : prefix_search = role_name . endswith ( "*" ) if prefix_search : role_name = role_name . rstrip ( "*" ) for n in get_nodes ( environment ) : roles = get_roles_in_node ( n , recursive = True ) if prefix_search : if any ( role . startswith ( role_name ) for role... | Get all nodes which include a given role prefix - searches are also supported |
238,007 | def get_nodes_with_tag ( tag , environment = None , include_guests = False ) : nodes = get_nodes ( environment ) nodes_mapping = dict ( ( n [ 'name' ] , n ) for n in nodes ) for n in nodes : if tag in n . get ( 'tags' , [ ] ) : try : del nodes_mapping [ n [ 'fqdn' ] ] except KeyError : pass yield n if include_guests an... | Get all nodes which include a given tag |
238,008 | def get_nodes_with_recipe ( recipe_name , environment = None ) : prefix_search = recipe_name . endswith ( "*" ) if prefix_search : recipe_name = recipe_name . rstrip ( "*" ) for n in get_nodes ( environment ) : recipes = get_recipes_in_node ( n ) for role in get_roles_in_node ( n , recursive = True ) : recipes . extend... | Get all nodes which include a given recipe prefix - searches are also supported |
238,009 | def print_node ( node , detailed = False ) : nodename = node [ 'name' ] print ( colors . yellow ( "\n" + nodename ) ) if detailed : for role in get_roles_in_node ( node ) : print_role ( _get_role ( role ) , detailed = False ) else : print ( ' Roles: {0}' . format ( ", " . join ( get_roles_in_node ( node ) ) ) ) if det... | Pretty prints the given node |
238,010 | def print_nodes ( nodes , detailed = False ) : found = 0 for node in nodes : found += 1 print_node ( node , detailed = detailed ) print ( "\nFound {0} node{1}" . format ( found , "s" if found != 1 else "" ) ) | Prints all the given nodes |
238,011 | def _generate_metadata ( path , cookbook_path , name ) : global knife_installed if not knife_installed : return metadata_path_rb = os . path . join ( path , 'metadata.rb' ) metadata_path_json = os . path . join ( path , 'metadata.json' ) if ( os . path . exists ( metadata_path_rb ) and ( not os . path . exists ( metada... | Checks whether metadata . rb has changed and regenerate metadata . json |
238,012 | def get_recipes_in_cookbook ( name ) : recipes = { } path = None cookbook_exists = False metadata_exists = False for cookbook_path in cookbook_paths : path = os . path . join ( cookbook_path , name ) path_exists = os . path . exists ( path ) cookbook_exists = cookbook_exists or path_exists if not path_exists : continue... | Gets the name of all recipes present in a cookbook Returns a list of dictionaries |
238,013 | def get_recipes_in_node ( node ) : recipes = [ ] for elem in node . get ( 'run_list' , [ ] ) : if elem . startswith ( "recipe" ) : recipe = elem . split ( '[' ) [ 1 ] . split ( ']' ) [ 0 ] recipes . append ( recipe ) return recipes | Gets the name of all recipes present in the run_list of a node |
238,014 | def get_recipes ( ) : dirnames = set ( ) for path in cookbook_paths : dirnames . update ( [ d for d in os . listdir ( path ) if os . path . isdir ( os . path . join ( path , d ) ) and not d . startswith ( '.' ) ] ) recipes = [ ] for dirname in dirnames : recipes . extend ( get_recipes_in_cookbook ( dirname ) ) return s... | Gets all recipes found in the cookbook directories |
238,015 | def print_recipe ( recipe ) : print ( colors . yellow ( "\n{0}" . format ( recipe [ 'name' ] ) ) ) print " description: {0}" . format ( recipe [ 'description' ] ) print " version: {0}" . format ( recipe [ 'version' ] ) print " dependencies: {0}" . format ( ", " . join ( recipe [ 'dependencies' ] ) ) print " a... | Pretty prints the given recipe |
238,016 | def _get_role ( rolename ) : path = os . path . join ( 'roles' , rolename + '.json' ) if not os . path . exists ( path ) : abort ( "Couldn't read role file {0}" . format ( path ) ) with open ( path , 'r' ) as f : try : role = json . loads ( f . read ( ) ) except ValueError as e : msg = "Little Chef found the following ... | Reads and parses a file containing a role |
238,017 | def get_roles ( ) : roles = [ ] for root , subfolders , files in os . walk ( 'roles' ) : for filename in files : if filename . endswith ( ".json" ) : path = os . path . join ( root [ len ( 'roles' ) : ] , filename [ : - len ( '.json' ) ] ) roles . append ( _get_role ( path ) ) return sorted ( roles , key = lambda x : x... | Gets all roles found in the roles directory |
238,018 | def print_role ( role , detailed = True ) : if detailed : print ( colors . yellow ( role . get ( 'fullname' ) ) ) else : print ( " Role: {0}" . format ( role . get ( 'fullname' ) ) ) if detailed : print ( " description: {0}" . format ( role . get ( 'description' ) ) ) if 'default_attributes' in role : print ( " ... | Pretty prints the given role |
238,019 | def import_plugin ( name ) : path = os . path . join ( "plugins" , name + ".py" ) try : with open ( path , 'rb' ) as f : try : plugin = imp . load_module ( "p_" + name , f , name + '.py' , ( '.py' , 'rb' , imp . PY_SOURCE ) ) except SyntaxError as e : error = "Found plugin '{0}', but it seems" . format ( name ) error +... | Imports plugin python module |
238,020 | def get_cookbook_path ( cookbook_name ) : for cookbook_path in cookbook_paths : path = os . path . join ( cookbook_path , cookbook_name ) if os . path . exists ( path ) : return path raise IOError ( 'Can\'t find cookbook with name "{0}"' . format ( cookbook_name ) ) | Returns path to the cookbook for the given cookbook name |
238,021 | def global_confirm ( question , default = True ) : if env . abort_on_prompts : return True original_parallel = env . parallel env . parallel = False result = confirm ( question , default ) env . parallel = original_parallel return result | Shows a confirmation that applies to all hosts by temporarily disabling parallel execution in Fabric |
238,022 | def _pprint ( dic ) : for key , value in dic . items ( ) : print ( " {0}: {1}" . format ( key , value ) ) | Prints a dictionary with one indentation level |
238,023 | def get_margin ( length ) : if length > 23 : margin_left = "\t" chars = 1 elif length > 15 : margin_left = "\t\t" chars = 2 elif length > 7 : margin_left = "\t\t\t" chars = 3 else : margin_left = "\t\t\t\t" chars = 4 return margin_left | Add enough tabs to align in two columns |
238,024 | def configure ( current_node = None ) : current_node = current_node or { } cache_dir = "{0}/cache" . format ( env . node_work_path ) try : cache_exists = exists ( cache_dir ) except EOFError as e : abort ( "Could not login to node, got: {0}" . format ( e ) ) if not cache_exists : with settings ( hide ( 'running' , 'std... | Deploy chef - solo specific files |
238,025 | def execute ( node ) : with hide ( 'everything' ) : virt = json . loads ( sudo ( 'ohai virtualization' ) ) if not len ( virt ) or virt [ 0 ] [ 1 ] != "host" : print ( "This node is not a Xen host, doing nothing" ) return node [ 'virtualization' ] = { 'role' : 'host' , 'system' : 'xen' , 'vms' : [ ] , } with hide ( 'eve... | Uses ohai to get virtualization information which is then saved to then node file |
238,026 | def nodes_with_role ( rolename ) : nodes = [ n [ 'name' ] for n in lib . get_nodes_with_role ( rolename , env . chef_environment ) ] if not len ( nodes ) : print ( "No nodes found with role '{0}'" . format ( rolename ) ) sys . exit ( 0 ) return node ( * nodes ) | Configures a list of nodes that have the given role in their run list |
238,027 | def nodes_with_recipe ( recipename ) : nodes = [ n [ 'name' ] for n in lib . get_nodes_with_recipe ( recipename , env . chef_environment ) ] if not len ( nodes ) : print ( "No nodes found with recipe '{0}'" . format ( recipename ) ) sys . exit ( 0 ) return node ( * nodes ) | Configures a list of nodes that have the given recipe in their run list |
238,028 | def node ( * nodes ) : chef . build_node_data_bag ( ) if not len ( nodes ) or nodes [ 0 ] == '' : abort ( 'No node was given' ) elif nodes [ 0 ] == 'all' : for node in lib . get_nodes ( env . chef_environment ) : env . hosts . append ( node [ 'name' ] ) if not len ( env . hosts ) : abort ( 'No nodes found in /nodes/' )... | Selects and configures a list of nodes . all configures all nodes |
238,029 | def _node_runner ( ) : env . host_string = lib . get_env_host_string ( ) node = lib . get_node ( env . host_string ) _configure_fabric_for_platform ( node . get ( "platform" ) ) if __testing__ : print "TEST: would now configure {0}" . format ( env . host_string ) else : lib . print_header ( "Configuring {0}" . format (... | This is only used by node so that we can execute in parallel |
238,030 | def deploy_chef ( ask = "yes" , version = "11" ) : env . host_string = lib . get_env_host_string ( ) if ask == "no" or littlechef . noninteractive : print ( "Deploying Chef using omnibus installer version: ..." . format ( version ) ) else : message = ( '\nAre you sure you want to install Chef version:' '{0} on node {1}... | Install chef - solo on a node |
238,031 | def plugin ( name ) : env . host_string = lib . get_env_host_string ( ) plug = lib . import_plugin ( name ) lib . print_header ( "Executing plugin '{0}' on " "{1}" . format ( name , env . host_string ) ) node = lib . get_node ( env . host_string ) if node == { 'run_list' : [ ] } : node [ 'name' ] = env . host_string pl... | Executes the selected plugin Plugins are expected to be found in the kitchen s plugins directory |
238,032 | def list_envs ( ) : for env in lib . get_environments ( ) : margin_left = lib . get_margin ( len ( env [ 'name' ] ) ) print ( "{0}{1}{2}" . format ( env [ 'name' ] , margin_left , env . get ( 'description' , '(no description)' ) ) ) | List all environments |
238,033 | def list_nodes_with_tag ( tag ) : lib . print_nodes ( lib . get_nodes_with_tag ( tag , env . chef_environment , littlechef . include_guests ) ) | Show all nodes which have assigned a given tag |
238,034 | def list_recipes ( ) : for recipe in lib . get_recipes ( ) : margin_left = lib . get_margin ( len ( recipe [ 'name' ] ) ) print ( "{0}{1}{2}" . format ( recipe [ 'name' ] , margin_left , recipe [ 'description' ] ) ) | Show a list of all available recipes |
238,035 | def list_roles ( ) : for role in lib . get_roles ( ) : margin_left = lib . get_margin ( len ( role [ 'fullname' ] ) ) print ( "{0}{1}{2}" . format ( role [ 'fullname' ] , margin_left , role . get ( 'description' , '(no description)' ) ) ) | Show a list of all available roles |
238,036 | def _check_appliances ( ) : filenames = os . listdir ( os . getcwd ( ) ) missing = [ ] for dirname in [ 'nodes' , 'environments' , 'roles' , 'cookbooks' , 'data_bags' ] : if ( dirname not in filenames ) or ( not os . path . isdir ( dirname ) ) : missing . append ( dirname ) return ( not bool ( missing ) ) , missing | Looks around and return True or False based on whether we are in a kitchen |
238,037 | def create_ticket_str ( self , prefix = None ) : if not prefix : prefix = self . model . TICKET_PREFIX return "%s-%d-%s" % ( prefix , int ( time . time ( ) ) , get_random_string ( length = self . model . TICKET_RAND_LEN ) ) | Generate a sufficiently opaque ticket string to ensure the ticket is not guessable . If a prefix is provided prepend it to the string . |
238,038 | def validate_ticket ( self , ticket , service , renew = False , require_https = False ) : if not ticket : raise InvalidRequest ( "No ticket string provided" ) if not self . model . TICKET_RE . match ( ticket ) : raise InvalidTicket ( "Ticket string %s is invalid" % ticket ) try : t = self . get ( ticket = ticket ) exce... | Given a ticket string and service identifier validate the corresponding Ticket . If validation succeeds return the Ticket . If validation fails raise an appropriate error . |
238,039 | def delete_invalid_tickets ( self ) : for ticket in self . filter ( Q ( consumed__isnull = False ) | Q ( expires__lte = now ( ) ) ) . order_by ( '-expires' ) : try : ticket . delete ( ) except models . ProtectedError : pass | Delete consumed or expired Ticket s that are not referenced by other Ticket s . Invalid tickets are no longer valid for authentication and can be safely deleted . |
238,040 | def consume_tickets ( self , user ) : for ticket in self . filter ( user = user , consumed__isnull = True , expires__gt = now ( ) ) : ticket . consume ( ) | Consume all valid Ticket s for a specified user . This is run when the user logs out to ensure all issued tickets are no longer valid for future authentication attempts . |
238,041 | def request_sign_out ( self , user ) : session = Session ( ) for ticket in self . filter ( user = user , consumed__gte = user . last_login ) : ticket . request_sign_out ( session = session ) | Send a single logout request to each service accessed by a specified user . This is called at logout when single logout is enabled . |
238,042 | def request_sign_out ( self , session = requests ) : if logout_allowed ( self . service ) : request = SingleSignOutRequest ( context = { 'ticket' : self } ) url = get_logout_url ( self . service ) or self . service session . post ( url , data = { 'logoutRequest' : request . render_content ( ) } ) logger . info ( "Singl... | Send a POST request to the ServiceTicket s logout URL to request sign - out . |
238,043 | def validate_callback ( self , service , pgturl , pgtid , pgtiou ) : if not proxy_allowed ( service ) : raise UnauthorizedServiceProxy ( "%s is not authorized to use proxy authentication" % service ) if not is_scheme_https ( pgturl ) : raise InvalidProxyCallback ( "Proxy callback %s is not HTTPS" % pgturl ) if not prox... | Verify the provided proxy callback URL . |
238,044 | def _get_backends ( ) : backends = [ ] backend_paths = getattr ( settings , 'MAMA_CAS_SERVICE_BACKENDS' , [ 'mama_cas.services.backends.SettingsBackend' ] ) for backend_path in backend_paths : backend = import_string ( backend_path ) ( ) backends . append ( backend ) return backends | Retrieve the list of configured service backends . |
238,045 | def _is_allowed ( attr , * args ) : for backend in _get_backends ( ) : try : if getattr ( backend , attr ) ( * args ) : return True except AttributeError : raise NotImplementedError ( "%s.%s.%s() not implemented" % ( backend . __class__ . __module__ , backend . __class__ . __name__ , attr ) ) return False | Test if a given attribute is allowed according to the current set of configured service backends . |
238,046 | def _is_valid_service_url ( url ) : valid_services = getattr ( settings , 'MAMA_CAS_VALID_SERVICES' , ( ) ) if not valid_services : return True warnings . warn ( 'The MAMA_CAS_VALID_SERVICES setting is deprecated. Services ' 'should be configured using MAMA_CAS_SERVICES.' , DeprecationWarning ) for service in [ re . co... | Access services list from MAMA_CAS_VALID_SERVICES . |
238,047 | def get_backend_path ( service ) : for backend in _get_backends ( ) : try : if backend . service_allowed ( service ) : return "%s.%s" % ( backend . __class__ . __module__ , backend . __class__ . __name__ ) except AttributeError : raise NotImplementedError ( "%s.%s.service_allowed() not implemented" % ( backend . __clas... | Return the dotted path of the matching backend . |
238,048 | def get_callbacks ( service ) : callbacks = list ( getattr ( settings , 'MAMA_CAS_ATTRIBUTE_CALLBACKS' , [ ] ) ) if callbacks : warnings . warn ( 'The MAMA_CAS_ATTRIBUTE_CALLBACKS setting is deprecated. Service callbacks ' 'should be configured using MAMA_CAS_SERVICES.' , DeprecationWarning ) for backend in _get_backen... | Get configured callbacks list for a given service identifier . |
238,049 | def get_logout_url ( service ) : for backend in _get_backends ( ) : try : return backend . get_logout_url ( service ) except AttributeError : raise NotImplementedError ( "%s.%s.get_logout_url() not implemented" % ( backend . __class__ . __module__ , backend . __class__ . __name__ ) ) return None | Get the configured logout URL for a given service identifier if any . |
238,050 | def logout_allowed ( service ) : if hasattr ( settings , 'MAMA_CAS_SERVICES' ) : return _is_allowed ( 'logout_allowed' , service ) if hasattr ( settings , 'MAMA_CAS_ENABLE_SINGLE_SIGN_OUT' ) : warnings . warn ( 'The MAMA_CAS_ENABLE_SINGLE_SIGN_OUT setting is deprecated. SLO ' 'should be configured using MAMA_CAS_SERVIC... | Check if a given service identifier should be sent a logout request . |
238,051 | def proxy_callback_allowed ( service , pgturl ) : if hasattr ( settings , 'MAMA_CAS_SERVICES' ) : return _is_allowed ( 'proxy_callback_allowed' , service , pgturl ) return _is_valid_service_url ( service ) | Check if a given proxy callback is allowed for the given service identifier . |
238,052 | def clean ( self ) : username = self . cleaned_data . get ( 'username' ) password = self . cleaned_data . get ( 'password' ) if username and password : try : self . user = authenticate ( request = self . request , username = username , password = password ) except Exception : logger . exception ( "Error authenticating ... | Pass the provided username and password to the active authentication backends and verify the user account is not disabled . If authentication succeeds the User object is assigned to the form so it can be accessed in the view . |
238,053 | def ns ( self , prefix , tag ) : return etree . QName ( self . prefixes [ prefix ] , tag ) | Given a prefix and an XML tag output the qualified name for proper namespace handling on output . |
238,054 | def validate_service_ticket ( service , ticket , pgturl = None , renew = False , require_https = False ) : logger . debug ( "Service validation request received for %s" % ticket ) if ticket and ticket . startswith ( ProxyTicket . TICKET_PREFIX ) : raise InvalidTicketSpec ( 'Proxy tickets cannot be validated with /servi... | Validate a service ticket string . Return a triplet containing a ServiceTicket and an optional ProxyGrantingTicket or a ValidationError if ticket validation failed . |
238,055 | def validate_proxy_ticket ( service , ticket , pgturl = None ) : logger . debug ( "Proxy validation request received for %s" % ticket ) pt = ProxyTicket . objects . validate_ticket ( ticket , service ) attributes = get_attributes ( pt . user , pt . service ) proxies = [ pt . service ] prior_pt = pt . granted_by_pgt . g... | Validate a proxy ticket string . Return a 4 - tuple containing a ProxyTicket an optional ProxyGrantingTicket and a list of proxies through which authentication proceeded or a ValidationError if ticket validation failed . |
238,056 | def validate_proxy_granting_ticket ( pgt , target_service ) : logger . debug ( "Proxy ticket request received for %s using %s" % ( target_service , pgt ) ) pgt = ProxyGrantingTicket . objects . validate_ticket ( pgt , target_service ) pt = ProxyTicket . objects . create_ticket ( service = target_service , user = pgt . ... | Validate a proxy granting ticket string . Return an ordered pair containing a ProxyTicket or a ValidationError if ticket validation failed . |
238,057 | def get_attributes ( user , service ) : attributes = { } for path in get_callbacks ( service ) : callback = import_string ( path ) attributes . update ( callback ( user , service ) ) return attributes | Return a dictionary of user attributes from the set of configured callback functions . |
238,058 | def logout_user ( request ) : logger . debug ( "Logout request received for %s" % request . user ) if is_authenticated ( request . user ) : ServiceTicket . objects . consume_tickets ( request . user ) ProxyTicket . objects . consume_tickets ( request . user ) ProxyGrantingTicket . objects . consume_tickets ( request . ... | End a single sign - on session for the current user . |
238,059 | def user_name_attributes ( user , service ) : attributes = { } attributes [ 'username' ] = user . get_username ( ) attributes [ 'full_name' ] = user . get_full_name ( ) attributes [ 'short_name' ] = user . get_short_name ( ) return attributes | Return all available user name related fields and methods . |
238,060 | def user_model_attributes ( user , service ) : ignore_fields = [ 'id' , 'password' ] attributes = { } for field in user . _meta . fields : if field . name not in ignore_fields : attributes [ field . name ] = getattr ( user , field . name ) return attributes | Return all fields on the user object that are not in the list of fields to ignore . |
238,061 | def add_query_params ( url , params ) : def encode ( s ) : return force_bytes ( s , settings . DEFAULT_CHARSET ) params = dict ( [ ( encode ( k ) , encode ( v ) ) for k , v in params . items ( ) if v ] ) parts = list ( urlparse ( url ) ) query = dict ( parse_qsl ( parts [ 4 ] ) ) query . update ( params ) parts [ 4 ] =... | Inject additional query parameters into an existing URL . If parameters already exist with the same name they will be overwritten . Parameters with empty values are ignored . Return the modified URL as a string . |
238,062 | def match_service ( service1 , service2 ) : s1 , s2 = urlparse ( service1 ) , urlparse ( service2 ) try : return ( s1 . scheme , s1 . netloc , s1 . path ) == ( s2 . scheme , s2 . netloc , s2 . path ) except ValueError : return False | Compare two service URLs . Return True if the scheme hostname optional port and path match . |
238,063 | def redirect ( to , * args , ** kwargs ) : params = kwargs . pop ( 'params' , { } ) try : to = reverse ( to , args = args , kwargs = kwargs ) except NoReverseMatch : if '/' not in to and '.' not in to : to = reverse ( 'cas_login' ) elif not service_allowed ( to ) : raise PermissionDenied ( ) if params : to = add_query_... | Similar to the Django redirect shortcut but with altered functionality . If an optional params argument is provided the dictionary items will be injected as query parameters on the redirection URL . |
238,064 | def get_config ( self , service , setting ) : try : return self . get_service ( service ) [ setting ] except KeyError : return getattr ( self , setting + '_DEFAULT' ) | Access the configuration for a given service and setting . If the service is not found return a default value . |
238,065 | def get_status ( self , status_value , message = None ) : status = etree . Element ( 'Status' ) status_code = etree . SubElement ( status , 'StatusCode' ) status_code . set ( 'Value' , 'samlp:' + status_value ) if message : status_message = etree . SubElement ( status , 'StatusMessage' ) status_message . text = message... | Build a Status XML block for a SAML 1 . 1 Response . |
238,066 | def get_assertion ( self , ticket , attributes ) : assertion = etree . Element ( 'Assertion' ) assertion . set ( 'xmlns' , 'urn:oasis:names:tc:SAML:1.0:assertion' ) assertion . set ( 'AssertionID' , self . generate_id ( ) ) assertion . set ( 'IssueInstant' , self . instant ( ) ) assertion . set ( 'Issuer' , 'localhost'... | Build a SAML 1 . 1 Assertion XML block . |
238,067 | def get_conditions ( self , service_id ) : conditions = etree . Element ( 'Conditions' ) conditions . set ( 'NotBefore' , self . instant ( ) ) conditions . set ( 'NotOnOrAfter' , self . instant ( offset = 30 ) ) restriction = etree . SubElement ( conditions , 'AudienceRestrictionCondition' ) audience = etree . SubEleme... | Build a Conditions XML block for a SAML 1 . 1 Assertion . |
238,068 | def get_attribute_statement ( self , subject , attributes ) : attribute_statement = etree . Element ( 'AttributeStatement' ) attribute_statement . append ( subject ) for name , value in attributes . items ( ) : attribute = etree . SubElement ( attribute_statement , 'Attribute' ) attribute . set ( 'AttributeName' , name... | Build an AttributeStatement XML block for a SAML 1 . 1 Assertion . |
238,069 | def get_authentication_statement ( self , subject , ticket ) : authentication_statement = etree . Element ( 'AuthenticationStatement' ) authentication_statement . set ( 'AuthenticationInstant' , self . instant ( instant = ticket . consumed ) ) authentication_statement . set ( 'AuthenticationMethod' , self . authn_metho... | Build an AuthenticationStatement XML block for a SAML 1 . 1 Assertion . |
238,070 | def get_subject ( self , identifier ) : subject = etree . Element ( 'Subject' ) name = etree . SubElement ( subject , 'NameIdentifier' ) name . text = identifier subject_confirmation = etree . SubElement ( subject , 'SubjectConfirmation' ) method = etree . SubElement ( subject_confirmation , 'ConfirmationMethod' ) meth... | Build a Subject XML block for a SAML 1 . 1 AuthenticationStatement or AttributeStatement . |
238,071 | def is_bytes ( string ) : if six . PY3 and isinstance ( string , ( bytes , memoryview , bytearray ) ) : return True elif six . PY2 and isinstance ( string , ( buffer , bytearray ) ) : return True return False | Check if a string is a bytes instance |
238,072 | def partialclass ( cls , * args , ** kwargs ) : name_attrs = [ n for n in ( getattr ( cls , name , str ( cls ) ) for name in ( "__name__" , "__qualname__" ) ) if n is not None ] name_attrs = name_attrs [ 0 ] type_ = type ( name_attrs , ( cls , ) , { "__init__" : partialmethod ( cls . __init__ , * args , ** kwargs ) } )... | Returns a partially instantiated class |
238,073 | def replace_with_text_stream ( stream_name ) : new_stream = TEXT_STREAMS . get ( stream_name ) if new_stream is not None : new_stream = new_stream ( ) setattr ( sys , stream_name , new_stream ) return None | Given a stream name replace the target stream with a text - converted equivalent |
238,074 | def _sanitize_params ( prefix , suffix , dir ) : output_type = _infer_return_type ( prefix , suffix , dir ) if suffix is None : suffix = output_type ( ) if prefix is None : if output_type is str : prefix = "tmp" else : prefix = os . fsencode ( "tmp" ) if dir is None : if output_type is str : dir = gettempdir ( ) else :... | Common parameter processing for most APIs in this module . |
238,075 | def fromdict ( model , data , exclude = None , exclude_underscore = None , allow_pk = None , follow = None , include = None , only = None ) : follow = arg_to_dict ( follow ) info = inspect ( model ) columns = [ c . key for c in info . mapper . column_attrs ] synonyms = [ c . key for c in info . mapper . synonyms ] rela... | Update a model from a dict |
238,076 | def make_class_dictable ( cls , exclude = constants . default_exclude , exclude_underscore = constants . default_exclude_underscore , fromdict_allow_pk = constants . default_fromdict_allow_pk , include = None , asdict_include = None , fromdict_include = None ) : setattr ( cls , 'dictalchemy_exclude' , exclude ) setattr... | Make a class dictable |
238,077 | def parse_GFF_attribute_string ( attrStr , extra_return_first_value = False ) : if attrStr . endswith ( "\n" ) : attrStr = attrStr [ : - 1 ] d = { } first_val = "_unnamed_" for ( i , attr ) in itertools . izip ( itertools . count ( ) , _HTSeq . quotesafe_split ( attrStr ) ) : if _re_attr_empty . match ( attr ) : contin... | Parses a GFF attribute string and returns it as a dictionary . |
238,078 | def pair_SAM_alignments ( alignments , bundle = False , primary_only = False ) : mate_missing_count = [ 0 ] def process_list ( almnt_list ) : while len ( almnt_list ) > 0 : a1 = almnt_list . pop ( 0 ) for a2 in almnt_list : if a1 . pe_which == a2 . pe_which : continue if a1 . aligned != a2 . mate_aligned or a1 . mate_a... | Iterate over SAM aligments name - sorted paired - end |
238,079 | def pair_SAM_alignments_with_buffer ( alignments , max_buffer_size = 30000000 , primary_only = False ) : almnt_buffer = { } ambiguous_pairing_counter = 0 for almnt in alignments : if not almnt . paired_end : raise ValueError ( "Sequence of paired-end alignments expected, but got single-end alignment." ) if almnt . pe_w... | Iterate over SAM aligments with buffer position - sorted paired - end |
238,080 | def ensure_v8_src ( ) : path = local_path ( 'v8' ) if not os . path . isdir ( path ) : fetch_v8 ( path ) else : update_v8 ( path ) checkout_v8_version ( local_path ( "v8/v8" ) , V8_VERSION ) dependencies_sync ( path ) | Ensure that v8 src are presents and up - to - date |
238,081 | def get_filenames ( directory ) : for filename in os . listdir ( directory ) : if re . search ( r"cp\d{2}mu?-manylinux1_\S+\.whl" , filename ) : yield filename | Get all the file to copy |
238,082 | def copy_file ( filename ) : print ( "Updating file %s" % filename ) out_dir = os . path . abspath ( DIRECTORY ) tags = filename [ : - 4 ] . split ( "-" ) tags [ - 2 ] = tags [ - 2 ] . replace ( "m" , "" ) new_name = "-" . join ( tags ) + ".whl" wheel_flag = "-" . join ( tags [ 2 : ] ) with InWheelCtx ( os . path . joi... | Copy the file and put the correct tag |
238,083 | def is_unicode ( value ) : python_version = sys . version_info [ 0 ] if python_version == 2 : return isinstance ( value , unicode ) elif python_version == 3 : return isinstance ( value , str ) else : raise NotImplementedError ( ) | Check if a value is a valid unicode string compatible with python 2 and python 3 |
238,084 | def execute ( self , js_str , timeout = 0 , max_memory = 0 ) : wrapped = "(function(){return (%s)})()" % js_str return self . eval ( wrapped , timeout , max_memory ) | Exec the given JS value |
238,085 | def eval ( self , js_str , timeout = 0 , max_memory = 0 ) : if is_unicode ( js_str ) : bytes_val = js_str . encode ( "utf8" ) else : bytes_val = js_str res = None self . lock . acquire ( ) try : res = self . ext . mr_eval_context ( self . ctx , bytes_val , len ( bytes_val ) , ctypes . c_ulong ( timeout ) , ctypes . c_s... | Eval the JavaScript string |
238,086 | def call ( self , identifier , * args , ** kwargs ) : encoder = kwargs . get ( 'encoder' , None ) timeout = kwargs . get ( 'timeout' , 0 ) max_memory = kwargs . get ( 'max_memory' , 0 ) json_args = json . dumps ( args , separators = ( ',' , ':' ) , cls = encoder ) js = "{identifier}.apply(this, {json_args})" return sel... | Call the named function with provided arguments You can pass a custom JSON encoder by passing it in the encoder keyword only argument . |
238,087 | def heap_stats ( self ) : self . lock . acquire ( ) res = self . ext . mr_heap_stats ( self . ctx ) self . lock . release ( ) python_value = res . contents . to_python ( ) self . free ( res ) return python_value | Return heap statistics |
238,088 | def heap_snapshot ( self ) : self . lock . acquire ( ) res = self . ext . mr_heap_snapshot ( self . ctx ) self . lock . release ( ) python_value = res . contents . to_python ( ) self . free ( res ) return python_value | Return heap snapshot |
238,089 | def to_python ( self ) : result = None if self . type == PythonTypes . null : result = None elif self . type == PythonTypes . bool : result = self . value == 1 elif self . type == PythonTypes . integer : if self . value is None : result = 0 else : result = ctypes . c_int32 ( self . value ) . value elif self . type == P... | Return an object as native Python |
238,090 | def libv8_object ( object_name ) : filename = join ( V8_LIB_DIRECTORY , 'out.gn/x64.release/obj/{}' . format ( object_name ) ) if not isfile ( filename ) : filename = join ( local_path ( 'vendor/v8/out.gn/libv8/obj/{}' . format ( object_name ) ) ) if not isfile ( filename ) : filename = join ( V8_LIB_DIRECTORY , 'out.g... | Return a path for object_name which is OS independent |
238,091 | def get_static_lib_paths ( ) : libs = [ ] is_linux = sys . platform . startswith ( 'linux' ) if is_linux : libs += [ '-Wl,--start-group' ] libs += get_raw_static_lib_path ( ) if is_linux : libs += [ '-Wl,--end-group' ] return libs | Return the required static libraries path |
238,092 | def get_dag_params ( self ) -> Dict [ str , Any ] : try : dag_params : Dict [ str , Any ] = utils . merge_configs ( self . dag_config , self . default_config ) except Exception as e : raise Exception ( f"Failed to merge config with default config, err: {e}" ) dag_params [ "dag_id" ] : str = self . dag_name try : dag_pa... | Merges default config with dag config sets dag_id and extropolates dag_start_date |
238,093 | def make_task ( operator : str , task_params : Dict [ str , Any ] ) -> BaseOperator : try : operator_obj : Callable [ ... , BaseOperator ] = import_string ( operator ) except Exception as e : raise Exception ( f"Failed to import operator: {operator}. err: {e}" ) try : task : BaseOperator = operator_obj ( ** task_params... | Takes an operator and params and creates an instance of that operator . |
238,094 | def build ( self ) -> Dict [ str , Union [ str , DAG ] ] : dag_params : Dict [ str , Any ] = self . get_dag_params ( ) dag : DAG = DAG ( dag_id = dag_params [ "dag_id" ] , schedule_interval = dag_params [ "schedule_interval" ] , description = dag_params . get ( "description" , "" ) , max_active_runs = dag_params . get ... | Generates a DAG from the DAG parameters . |
238,095 | def merge_configs ( config : Dict [ str , Any ] , default_config : Dict [ str , Any ] ) -> Dict [ str , Any ] : for key in default_config : if key in config : if isinstance ( config [ key ] , dict ) and isinstance ( default_config [ key ] , dict ) : merge_configs ( config [ key ] , default_config [ key ] ) else : confi... | Merges a default config with DAG config . Used to set default values for a group of DAGs . |
238,096 | def _load_config ( config_filepath : str ) -> Dict [ str , Any ] : try : config : Dict [ str , Any ] = yaml . load ( stream = open ( config_filepath , "r" ) ) except Exception as e : raise Exception ( f"Invalid DAG Factory config file; err: {e}" ) return config | Loads YAML config file to dictionary |
238,097 | def get_dag_configs ( self ) -> Dict [ str , Dict [ str , Any ] ] : return { dag : self . config [ dag ] for dag in self . config . keys ( ) if dag != "default" } | Returns configuration for each the DAG in factory |
238,098 | def generate_dags ( self , globals : Dict [ str , Any ] ) -> None : dag_configs : Dict [ str , Dict [ str , Any ] ] = self . get_dag_configs ( ) default_config : Dict [ str , Any ] = self . get_default_config ( ) for dag_name , dag_config in dag_configs . items ( ) : dag_builder : DagBuilder = DagBuilder ( dag_name = d... | Generates DAGs from YAML config |
238,099 | def attributes ( self ) : attr = { 'name' : self . name , 'id' : self . sync_id , 'network_id' : self . network_id , 'serial' : self . serial , 'status' : self . status , 'region' : self . region , 'region_id' : self . region_id , } return attr | Return sync attributes . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.