idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
61,700 | def get_container_remove_kwargs ( self , action , container_name , kwargs = None ) : c_kwargs = dict ( container = container_name ) update_kwargs ( c_kwargs , kwargs ) return c_kwargs | Generates keyword arguments for the Docker client to remove a container . |
61,701 | def get_network_create_kwargs ( self , action , network_name , kwargs = None ) : config = action . config c_kwargs = dict ( name = network_name , driver = config . driver , options = config . driver_options , ) if config . internal : c_kwargs [ 'internal' ] = True driver_opts = init_options ( config . driver_options ) if driver_opts : c_kwargs [ 'options' ] = { option_name : resolve_value ( option_value ) for option_name , option_value in iteritems ( driver_opts ) } update_kwargs ( c_kwargs , init_options ( config . create_options ) , kwargs ) return c_kwargs | Generates keyword arguments for the Docker client to create a network . |
61,702 | def get_network_remove_kwargs ( self , action , network_name , kwargs = None ) : c_kwargs = dict ( net_id = network_name ) update_kwargs ( c_kwargs , kwargs ) return c_kwargs | Generates keyword arguments for the Docker client to remove a network . |
61,703 | def get_network_connect_kwargs ( self , action , network_name , container_name , endpoint_config = None , kwargs = None ) : c_kwargs = dict ( container = container_name , net_id = network_name , ) if endpoint_config : c_kwargs . update ( self . get_network_create_endpoint_kwargs ( action , endpoint_config ) ) update_kwargs ( c_kwargs , kwargs ) return c_kwargs | Generates keyword arguments for the Docker client to add a container to a network . |
61,704 | def get_network_disconnect_kwargs ( self , action , network_name , container_name , kwargs = None ) : c_kwargs = dict ( container = container_name , net_id = network_name , ) update_kwargs ( c_kwargs , kwargs ) return c_kwargs | Generates keyword arguments for the Docker client to remove a container from a network . |
61,705 | def get_volume_create_kwargs ( self , action , volume_name , kwargs = None ) : config = action . config c_kwargs = dict ( name = volume_name ) if config : c_kwargs [ 'driver' ] = config . driver driver_opts = init_options ( config . driver_options ) if driver_opts : c_kwargs [ 'driver_opts' ] = { option_name : resolve_value ( option_value ) for option_name , option_value in iteritems ( driver_opts ) } update_kwargs ( c_kwargs , init_options ( config . create_options ) , kwargs ) else : update_kwargs ( c_kwargs , kwargs ) return c_kwargs | Generates keyword arguments for the Docker client to create a volume . |
61,706 | def get_volume_remove_kwargs ( self , action , volume_name , kwargs = None ) : c_kwargs = dict ( name = volume_name ) update_kwargs ( c_kwargs , kwargs ) return c_kwargs | Generates keyword arguments for the Docker client to remove a volume . |
61,707 | def cname ( cls , map_name , container , instance = None ) : if instance : return '{0}.{1}.{2}' . format ( map_name , container , instance ) return '{0}.{1}' . format ( map_name , container ) | Generates a container name that should be used for creating new containers and checking the status of existing containers . |
61,708 | def aname ( cls , map_name , attached_name , parent_name = None ) : if parent_name : return '{0}.{1}.{2}' . format ( map_name , parent_name , attached_name ) return '{0}.{1}' . format ( map_name , attached_name ) | Generates a container name that should be used for creating new attached volume containers and checking the status of existing containers . |
61,709 | def nname ( cls , map_name , network_name ) : if network_name in DEFAULT_PRESET_NETWORKS : return network_name return '{0}.{1}' . format ( map_name , network_name ) | Generates a network name that should be used for creating new networks and checking the status of existing networks on the client . |
61,710 | def get_hostname ( cls , container_name , client_name = None ) : base_name = container_name for old , new in cls . hostname_replace : base_name = base_name . replace ( old , new ) if not client_name or client_name == cls . default_client_name : return base_name client_suffix = client_name for old , new in cls . hostname_replace : client_suffix = client_suffix . replace ( old , new ) return '{0}-{1}' . format ( base_name , client_suffix ) | Determines the host name of a container . In this implementation replaces all dots and underscores of a container name with a dash ; then attaches another dash with the client name unless there is just one default client . |
61,711 | def adduser ( username , uid = None , system = False , no_login = True , no_password = False , group = False , gecos = None , ** kwargs ) : return _format_cmd ( 'adduser' , username , __system = bool ( system ) , __uid = uid , __group = bool ( group ) , __gid = uid , no_login = ( no_login , _NO_CREATE_HOME , _NO_LOGIN ) , __disabled_password = no_login or bool ( no_password ) , __gecos = gecos , ** kwargs ) | Formats an adduser command . |
61,712 | def mkdir ( path , create_parent = True , check_if_exists = False ) : cmd = _format_cmd ( 'mkdir' , path , _p = create_parent ) if check_if_exists : return 'if [[ ! -d {0} ]]; then {1}; fi' . format ( path , cmd ) return cmd | Generates a unix command line for creating a directory . |
61,713 | def bind ( self , field_name , parent ) : super ( TranslatedFieldsField , self ) . bind ( field_name , parent ) related_name = self . source or field_name if self . shared_model is not None and self . serializer_class is not None : return if self . serializer_class is None : if self . shared_model is None : from . serializers import TranslatableModelSerializer if not isinstance ( parent , TranslatableModelSerializer ) : raise TypeError ( "Expected 'TranslatableModelSerializer' as serializer base class" ) if not issubclass ( parent . Meta . model , TranslatableModel ) : raise TypeError ( "Expected 'TranslatableModel' for the parent model" ) self . shared_model = parent . Meta . model translated_model = self . shared_model . _parler_meta [ related_name ] self . serializer_class = create_translated_fields_serializer ( self . shared_model , related_name = related_name , meta = { 'fields' : translated_model . get_translated_fields ( ) } ) else : if not issubclass ( self . serializer_class . Meta . model , TranslatedFieldsModel ) : raise TypeError ( "Expected 'TranslatedFieldsModel' for the serializer model" ) | Create translation serializer dynamically . |
61,714 | def to_representation ( self , value ) : if value is None : return serializer = self . serializer_class ( instance = self . parent . instance , context = self . context , partial = self . parent . partial ) if 'language_code' in serializer . fields : raise ImproperlyConfigured ( "Serializer may not have a 'language_code' field" ) translations = value . all ( ) languages = self . context . get ( 'languages' ) if languages : translations = translations . filter ( language_code__in = languages ) result = OrderedDict ( ) for translation in translations : result [ translation . language_code ] = serializer . to_representation ( translation ) return result | Serialize translated fields . |
61,715 | def to_internal_value ( self , data ) : if data is None : return if not isinstance ( data , dict ) : self . fail ( 'invalid' ) if not self . allow_empty and len ( data ) == 0 : self . fail ( 'empty' ) result , errors = { } , { } for lang_code , model_fields in data . items ( ) : serializer = self . serializer_class ( data = model_fields ) if serializer . is_valid ( ) : result [ lang_code ] = serializer . validated_data else : errors [ lang_code ] = serializer . errors if errors : raise serializers . ValidationError ( errors ) return result | Deserialize data from translations fields . |
61,716 | def parse ( self , text , layers = None ) : params = { "text" : text , "key" : self . key , } if layers is not None : if isinstance ( layers , six . string_types ) : params [ "layers" ] = layers elif isinstance ( layers , collections . Iterable ) : params [ "layers" ] = "," . join ( layers ) req = requests . get ( self . NLU_URL , params = params ) return req . json ( ) | Parsing passed text to json . |
61,717 | def generate ( self , text ) : if not text : raise Exception ( "No text to speak" ) if len ( text ) >= self . MAX_CHARS : raise Exception ( "Number of characters must be less than 2000" ) params = self . __params . copy ( ) params [ "text" ] = text self . _data = requests . get ( self . TTS_URL , params = params , stream = False ) . iter_content ( ) | Try to get the generated file . |
61,718 | def save ( self , path = "speech" ) : if self . _data is None : raise Exception ( "There's nothing to save" ) extension = "." + self . __params [ "format" ] if os . path . splitext ( path ) [ 1 ] != extension : path += extension with open ( path , "wb" ) as f : for d in self . _data : f . write ( d ) return path | Save data in file . |
61,719 | def create_translated_fields_serializer ( shared_model , meta = None , related_name = None , ** fields ) : if not related_name : translated_model = shared_model . _parler_meta . root_model else : translated_model = shared_model . _parler_meta [ related_name ] . model if not meta : meta = { } meta [ 'model' ] = translated_model meta . setdefault ( 'fields' , [ 'language_code' ] + translated_model . get_translated_fields ( ) ) attrs = { } attrs . update ( fields ) attrs [ 'Meta' ] = type ( 'Meta' , ( ) , meta ) return type ( '{0}Serializer' . format ( translated_model . __name__ ) , ( serializers . ModelSerializer , ) , attrs ) | Create a Rest Framework serializer class for a translated fields model . |
61,720 | def save ( self , ** kwargs ) : translated_data = self . _pop_translated_data ( ) instance = super ( TranslatableModelSerializer , self ) . save ( ** kwargs ) self . save_translations ( instance , translated_data ) return instance | Extract the translations and save them after main object save . |
61,721 | def _pop_translated_data ( self ) : translated_data = { } for meta in self . Meta . model . _parler_meta : translations = self . validated_data . pop ( meta . rel_name , { } ) if translations : translated_data [ meta . rel_name ] = translations return translated_data | Separate data of translated fields from other data . |
61,722 | def save_translations ( self , instance , translated_data ) : for meta in self . Meta . model . _parler_meta : translations = translated_data . get ( meta . rel_name , { } ) for lang_code , model_fields in translations . items ( ) : translation = instance . _get_translated_model ( lang_code , auto_create = True , meta = meta ) for field , value in model_fields . items ( ) : setattr ( translation , field , value ) instance . save_translations ( ) | Save translation data into translation objects . |
61,723 | def load_conf ( cfg_path ) : global config try : cfg = open ( cfg_path , 'r' ) except Exception as ex : if verbose : print ( "Unable to open {0}" . format ( cfg_path ) ) print ( str ( ex ) ) return False cfg_json = cfg . read ( ) cfg . close ( ) try : config = json . loads ( cfg_json ) except Exception as ex : print ( "Unable to parse configuration file as JSON" ) print ( str ( ex ) ) return False return True | Try to load the given conf file . |
61,724 | def translate_message_tokens ( message_tokens ) : trans_tokens = [ ] if message_tokens [ 0 ] in cv_dict [ channels_key ] : trans_tokens . append ( cv_dict [ channels_key ] [ message_tokens [ 0 ] ] ) else : trans_tokens . append ( int ( message_tokens [ 0 ] ) ) for token in message_tokens [ 1 : ] : if token in cv_dict [ values_key ] : trans_tokens . extend ( cv_dict [ values_key ] [ token ] ) else : trans_tokens . append ( int ( token ) ) return trans_tokens | Translates alias references to their defined values . The first token is a channel alias . The remaining tokens are value aliases . |
61,725 | def parse_headers ( cls , msg ) : return list ( email . parser . Parser ( ) . parsestr ( msg ) . items ( ) ) | Parse HTTP headers . |
61,726 | def parse ( cls , msg ) : lines = msg . splitlines ( ) version , status_code , reason = lines [ 0 ] . split ( ) headers = cls . parse_headers ( '\r\n' . join ( lines [ 1 : ] ) ) return cls ( version = version , status_code = status_code , reason = reason , headers = headers ) | Parse message string to response object . |
61,727 | def parse ( cls , msg ) : lines = msg . splitlines ( ) method , uri , version = lines [ 0 ] . split ( ) headers = cls . parse_headers ( '\r\n' . join ( lines [ 1 : ] ) ) return cls ( version = version , uri = uri , method = method , headers = headers ) | Parse message string to request object . |
61,728 | def sendto ( self , transport , addr ) : msg = bytes ( self ) + b'\r\n' logger . debug ( "%s:%s < %s" , * ( addr + ( self , ) ) ) transport . sendto ( msg , addr ) | Send request to a given address via given transport . |
61,729 | def send_rgb ( dev , red , green , blue , dimmer ) : cv = [ 0 for v in range ( 0 , 512 ) ] cv [ 0 ] = red cv [ 1 ] = green cv [ 2 ] = blue cv [ 6 ] = dimmer sent = dev . send_multi_value ( 1 , cv ) return sent | Send a set of RGB values to the light |
61,730 | def main ( ) : cv = [ 0 for v in range ( 0 , 512 ) ] print ( "Opening DMX controller..." ) dev = pyudmx . uDMXDevice ( ) dev . open ( ) print ( dev . Device ) print ( "Setting to red..." ) cv [ 0 ] = 255 cv [ 6 ] = 128 sent = dev . send_multi_value ( 1 , cv ) print ( "Set to red" ) sleep ( 3.0 ) print ( "Setting to green..." ) cv [ 0 ] = 0 cv [ 1 ] = 255 cv [ 6 ] = 128 sent = dev . send_multi_value ( 1 , cv ) print ( "Set to green" ) sleep ( 3.0 ) print ( "Setting to blue..." ) cv [ 0 ] = 0 cv [ 1 ] = 0 cv [ 2 ] = 255 cv [ 6 ] = 128 sent = dev . send_multi_value ( 1 , cv ) print ( "Set to blue" ) sleep ( 3.0 ) print ( "And, again the easier way" ) send_rgb ( dev , 255 , 0 , 0 , 128 ) sleep ( 3.0 ) send_rgb ( dev , 0 , 255 , 0 , 128 ) sleep ( 3.0 ) send_rgb ( dev , 0 , 0 , 255 , 128 ) sleep ( 3.0 ) print ( "Reset all channels and close.." ) cv = [ 0 for v in range ( 0 , 512 ) ] dev . send_multi_value ( 1 , cv ) dev . close ( ) | How to control a DMX light through an Anyma USB controller |
61,731 | def connect ( self ) : try : context = ssl . SSLContext ( ssl . PROTOCOL_TLSv1_2 ) if self . config [ 'no_ssl_verify' ] : requests . packages . urllib3 . disable_warnings ( ) context . verify_mode = ssl . CERT_NONE self . si = SmartConnectNoSSL ( host = self . config [ 'server' ] , user = self . config [ 'username' ] , pwd = self . config [ 'password' ] , port = int ( self . config [ 'port' ] ) , certFile = None , keyFile = None , ) else : self . si = SmartConnect ( host = self . config [ 'server' ] , user = self . config [ 'username' ] , pwd = self . config [ 'password' ] , port = int ( self . config [ 'port' ] ) , sslContext = context , certFile = None , keyFile = None , ) except Exception as e : print ( 'Unable to connect to vsphere server.' ) print ( e ) sys . exit ( 1 ) atexit . register ( Disconnect , self . si ) self . content = self . si . RetrieveContent ( ) | Connect to vCenter server |
61,732 | def status ( self ) : vm = self . get_vm_failfast ( self . config [ 'name' ] ) extra = self . config [ 'extra' ] parserFriendly = self . config [ 'parserFriendly' ] status_to_print = [ ] if extra : status_to_print = [ [ "vmname" , "powerstate" , "ipaddress" , "hostname" , "memory" , "cpunum" , "uuid" , "guestid" , "uptime" ] ] + [ [ vm . name , vm . runtime . powerState , vm . summary . guest . ipAddress or '' , vm . summary . guest . hostName or '' , str ( vm . summary . config . memorySizeMB ) , str ( vm . summary . config . numCpu ) , vm . summary . config . uuid , vm . summary . guest . guestId , str ( vm . summary . quickStats . uptimeSeconds ) or '0' ] ] else : status_to_print = [ [ vm . name , vm . runtime . powerState ] ] if parserFriendly : self . print_as_lines ( status_to_print ) else : self . print_as_table ( status_to_print ) | Check power status |
61,733 | def shutdown ( self ) : vm = self . get_vm_failfast ( self . config [ 'name' ] ) if vm . runtime . powerState == vim . VirtualMachinePowerState . poweredOff : print ( "%s already poweredOff" % vm . name ) else : if self . guestToolsRunning ( vm ) : timeout_minutes = 10 print ( "waiting for %s to shutdown " "(%s minutes before forced powerOff)" % ( vm . name , str ( timeout_minutes ) ) ) vm . ShutdownGuest ( ) if self . WaitForVirtualMachineShutdown ( vm , timeout_minutes * 60 ) : print ( "shutdown complete" ) print ( "%s poweredOff" % vm . name ) else : print ( "%s has not shutdown after %s minutes:" "will powerOff" % ( vm . name , str ( timeout_minutes ) ) ) self . powerOff ( ) else : print ( "GuestTools not running or not installed: will powerOff" ) self . powerOff ( ) | Shutdown guest fallback to power off if guest tools aren t installed |
61,734 | def get_resource_pool ( self , cluster , pool_name ) : pool_obj = None cluster_pools_list = cluster . resourcePool . resourcePool pool_selections = self . get_obj ( [ vim . ResourcePool ] , pool_name , return_all = True ) if pool_selections : for p in pool_selections : if p in cluster_pools_list : pool_obj = p break return pool_obj | Find a resource pool given a pool name for desired cluster |
61,735 | def get_obj ( self , vimtype , name , return_all = False , path = "" ) : obj = list ( ) if path : obj_folder = self . content . searchIndex . FindByInventoryPath ( path ) container = self . content . viewManager . CreateContainerView ( obj_folder , vimtype , True ) else : container = self . content . viewManager . CreateContainerView ( self . content . rootFolder , vimtype , True ) for c in container . view : if name in [ c . name , c . _GetMoId ( ) ] : if return_all is False : return c break else : obj . append ( c ) if len ( obj ) > 0 : return obj else : return None | Get the vsphere object associated with a given text name or MOID |
61,736 | def get_host_system_failfast ( self , name , verbose = False , host_system_term = 'HS' ) : if verbose : print ( "Finding HostSystem named %s..." % name ) hs = self . get_host_system ( name ) if hs is None : print ( "Error: %s '%s' does not exist" % ( host_system_term , name ) ) sys . exit ( 1 ) if verbose : print ( "Found HostSystem: {0} Name: {1}" % ( hs , hs . name ) ) return hs | Get a HostSystem object fail fast if the object isn t a valid reference |
61,737 | def get_vm ( self , name , path = "" ) : if path : return self . get_obj ( [ vim . VirtualMachine ] , name , path = path ) else : return self . get_obj ( [ vim . VirtualMachine ] , name ) | Get a VirtualMachine object |
61,738 | def get_vm_failfast ( self , name , verbose = False , vm_term = 'VM' , path = "" ) : if verbose : print ( "Finding VirtualMachine named %s..." % name ) if path : vm = self . get_vm ( name , path = path ) else : vm = self . get_vm ( name ) if vm is None : print ( "Error: %s '%s' does not exist" % ( vm_term , name ) ) sys . exit ( 1 ) if verbose : print ( "Found VirtualMachine: %s Name: %s" % ( vm , vm . name ) ) return vm | Get a VirtualMachine object fail fast if the object isn t a valid reference |
61,739 | def WaitForVirtualMachineShutdown ( self , vm_to_poll , timeout_seconds , sleep_period = 5 ) : seconds_waited = 0 while seconds_waited < timeout_seconds : seconds_waited += sleep_period time . sleep ( sleep_period ) vm = self . get_vm ( vm_to_poll . name ) if vm . runtime . powerState == vim . VirtualMachinePowerState . poweredOff : return True return False | Guest shutdown requests do not run a task we can wait for . So we must poll and wait for status to be poweredOff . |
61,740 | def location ( ip = None , key = None , field = None ) : if field and ( field not in field_list ) : return 'Invalid field' if field : if ip : url = 'https://ipapi.co/{}/{}/' . format ( ip , field ) else : url = 'https://ipapi.co/{}/' . format ( field ) else : if ip : url = 'https://ipapi.co/{}/json/' . format ( ip ) else : url = 'https://ipapi.co/json/' if key or API_KEY : url = '{}?key={}' . format ( url , ( key or API_KEY ) ) response = get ( url , headers = headers ) if field : return response . text else : return response . json ( ) | Get geolocation data for a given IP address If field is specified get specific field as text Else get complete location data as JSON |
61,741 | def main ( ) : logging . basicConfig ( stream = sys . stdout , level = logging . DEBUG ) parser = argparse . ArgumentParser ( description = 'Test the SMA webconnect library.' ) parser . add_argument ( 'ip' , type = str , help = 'IP address of the Webconnect module' ) parser . add_argument ( 'user' , help = 'installer/user' ) parser . add_argument ( 'password' , help = 'Installer password' ) args = parser . parse_args ( ) loop = asyncio . get_event_loop ( ) def _shutdown ( * _ ) : VAR [ 'running' ] = False signal . signal ( signal . SIGINT , _shutdown ) loop . run_until_complete ( main_loop ( loop , user = args . user , password = args . password , ip = args . ip ) ) | Main example . |
61,742 | def data ( self ) : if self . _next_update and datetime . now ( ) > self . _next_update : self . update ( ) return self . _data | Get a cached post - processed result of a GitHub API call . Uses Trac cache to avoid constant querying of the remote API . If a previous API call did not succeed automatically retries after a timeout . |
61,743 | def teams ( self ) : teams = self . _teamlist . teams ( ) current_teams = set ( self . _teamobjects . keys ( ) ) new_teams = set ( teams . keys ( ) ) added = new_teams - current_teams removed = current_teams - new_teams for team in removed : del self . _teamobjects [ team ] for team in added : self . _teamobjects [ team ] = GitHubTeam ( self . _api , self . _env , self . _org , teams [ team ] , team ) return self . _teamobjects . values ( ) | Return a sequence of GitHubTeam objects one for each team in this org . |
61,744 | def members ( self ) : allmembers = set ( ) for team in self . teams ( ) : allmembers . update ( team . members ( ) ) return sorted ( allmembers ) | Return a list of all users in this organization . Users are identified by their login name . Note that this is computed from the teams in the organization because GitHub does not currently offer a WebHook for organization membership so converting org membership would lead to stale data . |
61,745 | def update_team ( self , slug ) : if slug not in self . _teamobjects : return False return self . _teamobjects [ slug ] . update ( ) | Trigger an update and cache invalidation for the team identified by the given slug . Returns True on success False otherwise . |
61,746 | def github_api ( self , url , * args ) : import requests import urllib github_api_url = os . environ . get ( "TRAC_GITHUB_API_URL" , "https://api.github.com/" ) formatted_url = github_api_url + url . format ( * ( urllib . quote ( str ( x ) ) for x in args ) ) access_token = _config_secret ( self . access_token ) self . log . debug ( "Hitting GitHub API endpoint %s with user %s" , formatted_url , self . username ) results = [ ] try : has_next = True while has_next : req = requests . get ( formatted_url , auth = ( self . username , access_token ) ) if req . status_code != 200 : try : message = req . json ( ) [ 'message' ] except Exception : message = req . text self . log . error ( "Error communicating with GitHub API at {}: {}" . format ( formatted_url , message ) ) return None results . extend ( req . json ( ) ) has_next = 'next' in req . links if has_next : formatted_url = req . links [ 'next' ] [ 'url' ] except requests . exceptions . ConnectionError as rce : self . log . error ( "Exception while communicating with GitHub API at {}: {}" . format ( formatted_url , rce ) ) return None return results | Connect to the given GitHub API URL template by replacing all placeholders with the given parameters and return the decoded JSON result on success . On error return None . |
61,747 | def update_team ( self , slug ) : if self . _org : if not self . _org . has_team ( slug ) : return self . _org . update ( ) return self . _org . update_team ( slug ) return False | Trigger update and cache invalidation for the team identified by the given slug if any . Returns True if the update was successful False otherwise . |
61,748 | def get_permission_groups ( self , username ) : if not self . organization or not self . username or not self . access_token : return [ ] elif ( self . username_prefix and not username . startswith ( self . username_prefix ) ) : return [ ] data = self . _fetch_groups ( ) if not data : self . log . error ( "No cached groups from GitHub available" ) return [ ] else : return data . get ( username [ len ( self . username_prefix ) : ] , [ ] ) | Return a list of names of the groups that the user with the specified name is a member of . Implements an IPermissionGroupProvider API . |
61,749 | def match_request ( self , req ) : match = self . _request_re . match ( req . path_info ) if match : return True if os . environ . get ( 'TRAC_GITHUB_ENABLE_DEBUGGING' , None ) is not None : debug_match = self . _debug_request_re . match ( req . path_info ) if debug_match : return True | Return whether the handler wants to process the given request . Implements an IRequestHandler API . |
61,750 | def process_debug_request ( self , req ) : req . send ( json . dumps ( self . _fetch_groups ( ) ) . encode ( 'utf-8' ) , 'application/json' , 200 ) | Debgging helper used for testing processes the given request and dumps the internal state of cached user to group mappings . Note that this is only callable if TRAC_GITHUB_ENABLE_DEBUGGING is set in the environment . |
61,751 | def process_request ( self , req ) : if os . environ . get ( 'TRAC_GITHUB_ENABLE_DEBUGGING' , None ) is not None : debug_match = self . _debug_request_re . match ( req . path_info ) if debug_match : self . process_debug_request ( req ) if req . method != 'POST' : msg = u'Endpoint is ready to accept GitHub Organization membership notifications.\n' self . log . warning ( u'Method not allowed (%s)' , req . method ) req . send ( msg . encode ( 'utf-8' ) , 'text/plain' , 405 ) event = req . get_header ( 'X-GitHub-Event' ) supported_events = { 'ping' : self . _handle_ping_ev , 'membership' : self . _handle_membership_ev } if event not in supported_events : msg = u'Event type %s is not supported\n' % event self . log . warning ( msg . rstrip ( '\n' ) ) req . send ( msg . encode ( 'utf-8' ) , 'text/plain' , 400 ) reqdata = req . read ( ) signature = req . get_header ( 'X-Hub-Signature' ) if not self . _verify_webhook_signature ( signature , reqdata ) : msg = u'Webhook signature verification failed\n' self . log . warning ( msg . rstrip ( '\n' ) ) req . send ( msg . encode ( 'utf-8' ) , 'text/plain' , 403 ) try : payload = json . loads ( reqdata ) except ( ValueError , KeyError ) : msg = u'Invalid payload\n' self . log . warning ( msg . rstrip ( '\n' ) ) req . send ( msg . encode ( 'utf-8' ) , 'text/plain' , 400 ) try : supported_events [ event ] ( req , payload ) except RequestDone : raise except Exception : msg = ( u'Exception occurred while handling payload, ' 'possible invalid payload\n%s' % traceback . format_exc ( ) ) self . log . warning ( msg . rstrip ( '\n' ) ) req . send ( msg . encode ( 'utf-8' ) , 'text/plain' , 500 ) | Process the given request req implements an IRequestHandler API . |
61,752 | def get_content_children ( self , content_id , expand = None , parent_version = None , callback = None ) : params = { } if expand : params [ "expand" ] = expand if parent_version : params [ "parentVersion" ] = parent_version return self . _service_get_request ( "rest/api/content/{id}/child" . format ( id = content_id ) , params = params , callback = callback ) | Returns a map of the direct children of a piece of Content . Content can have multiple types of children - for example a Page can have children that are also Pages but it can also have Comments and Attachments . |
61,753 | def get_content_descendants ( self , content_id , expand = None , callback = None ) : params = { } if expand : params [ "expand" ] = expand return self . _service_get_request ( "rest/api/content/{id}/descendant" . format ( id = content_id ) , params = params , callback = callback ) | Returns a map of the descendants of a piece of Content . Content can have multiple types of descendants - for example a Page can have descendants that are also Pages but it can also have Comments and Attachments . |
61,754 | def get_content_descendants_by_type ( self , content_id , child_type , expand = None , start = None , limit = None , callback = None ) : params = { } if expand : params [ "expand" ] = expand if start is not None : params [ "start" ] = int ( start ) if limit is not None : params [ "limit" ] = int ( limit ) return self . _service_get_request ( "rest/api/content/{id}/descendant/{type}" "" . format ( id = content_id , type = child_type ) , params = params , callback = callback ) | Returns the direct descendants of a piece of Content limited to a single descendant type . |
61,755 | def get_content_properties ( self , content_id , expand = None , start = None , limit = None , callback = None ) : params = { } if expand : params [ "expand" ] = expand if start is not None : params [ "start" ] = int ( start ) if limit is not None : params [ "limit" ] = int ( limit ) return self . _service_get_request ( "rest/api/content/{id}/property" . format ( id = content_id ) , params = params , callback = callback ) | Returns a paginated list of content properties . |
61,756 | def create_new_attachment_by_content_id ( self , content_id , attachments , callback = None ) : if isinstance ( attachments , list ) : assert all ( isinstance ( at , dict ) and "file" in list ( at . keys ( ) ) for at in attachments ) elif isinstance ( attachments , dict ) : assert "file" in list ( attachments . keys ( ) ) else : assert False return self . _service_post_request ( "rest/api/content/{id}/child/attachment" . format ( id = content_id ) , headers = { "X-Atlassian-Token" : "nocheck" } , files = attachments , callback = callback ) | Add one or more attachments to a Confluence Content entity with optional comments . |
61,757 | def create_new_space ( self , space_definition , callback = None ) : assert isinstance ( space_definition , dict ) and { "key" , "name" , "description" } <= set ( space_definition . keys ( ) ) return self . _service_post_request ( "rest/api/space" , data = json . dumps ( space_definition ) , headers = { "Content-Type" : "application/json" } , callback = callback ) | Creates a new Space . |
61,758 | def update_content_by_id ( self , content_data , content_id , callback = None ) : assert isinstance ( content_data , dict ) and set ( content_data . keys ( ) ) >= self . UPDATE_CONTENT_REQUIRED_KEYS return self . _service_put_request ( "rest/api/content/{id}" . format ( id = content_id ) , data = json . dumps ( content_data ) , headers = { "Content-Type" : "application/json" } , callback = callback ) | Updates a piece of Content or restores if it is trashed . |
61,759 | def update_attachment_metadata ( self , content_id , attachment_id , new_metadata , callback = None ) : assert isinstance ( new_metadata , dict ) and set ( new_metadata . keys ( ) ) >= self . ATTACHMENT_METADATA_KEYS return self . _service_put_request ( "rest/api/content/{id}/child/attachment/{attachment_id}" "" . format ( id = content_id , attachment_id = attachment_id ) , data = json . dumps ( new_metadata ) , headers = { "Content-Type" : "application/json" } , callback = callback ) | Update the non - binary data of an Attachment . |
61,760 | def update_attachment ( self , content_id , attachment_id , attachment , callback = None ) : if isinstance ( attachment , dict ) : assert "file" in list ( attachment . keys ( ) ) else : assert False return self . _service_post_request ( "rest/api/content/{content_id}/child/attachment/{attachment_id}/data" "" . format ( content_id = content_id , attachment_id = attachment_id ) , headers = { "X-Atlassian-Token" : "nocheck" } , files = attachment , callback = callback ) | Update the binary data of an Attachment and optionally the comment and the minor edit field . |
61,761 | def update_property ( self , content_id , property_key , new_property_data , callback = None ) : assert isinstance ( new_property_data , dict ) and { "key" , "value" , "version" } <= set ( new_property_data . keys ( ) ) return self . _service_put_request ( "rest/api/content/{id}/property/{key}" . format ( id = content_id , key = property_key ) , data = json . dumps ( new_property_data ) , headers = { "Content-Type" : "application/json" } , callback = callback ) | Updates a content property . |
61,762 | def update_space ( self , space_key , space_definition , callback = None ) : assert isinstance ( space_definition , dict ) and { "key" , "name" , "description" } <= set ( space_definition . keys ( ) ) return self . _service_put_request ( "rest/api/space/{key}" . format ( key = space_key ) , data = json . dumps ( space_definition ) , headers = { "Content-Type" : "application/json" } , callback = callback ) | Updates a Space . |
61,763 | def convert_contentbody_to_new_type ( self , content_data , old_representation , new_representation , callback = None ) : assert { old_representation , new_representation } < { "storage" , "editor" , "view" , "export_view" } request_data = { "value" : str ( content_data ) , "representation" : old_representation } return self . _service_post_request ( "rest/api/contentbody/convert/{to}" . format ( to = new_representation ) , data = json . dumps ( request_data ) , headers = { "Content-Type" : "application/json" } , callback = callback ) | Converts between content body representations . |
61,764 | def delete_label_by_id ( self , content_id , label_name , callback = None ) : params = { "name" : label_name } return self . _service_delete_request ( "rest/api/content/{id}/label" . format ( id = content_id ) , params = params , callback = callback ) | Deletes a labels to the specified content . |
61,765 | def delete_space ( self , space_key , callback = None ) : return self . _service_delete_request ( "rest/api/space/{key}" . format ( key = space_key ) , callback = callback ) | Deletes a Space . |
61,766 | def add ( self , sensor ) : if isinstance ( sensor , ( list , tuple ) ) : for sss in sensor : self . add ( sss ) return if not isinstance ( sensor , Sensor ) : raise TypeError ( "pysma.Sensor expected" ) if sensor . name in self : old = self [ sensor . name ] self . __s . remove ( old ) _LOGGER . warning ( "Replacing sensor %s with %s" , old , sensor ) if sensor . key in self : _LOGGER . warning ( "Duplicate SMA sensor key %s" , sensor . key ) self . __s . append ( sensor ) | Add a sensor warning if it exists . |
61,767 | def _fetch_json ( self , url , payload ) : params = { 'data' : json . dumps ( payload ) , 'headers' : { 'content-type' : 'application/json' } , 'params' : { 'sid' : self . sma_sid } if self . sma_sid else None , } for _ in range ( 3 ) : try : with async_timeout . timeout ( 3 ) : res = yield from self . _aio_session . post ( self . _url + url , ** params ) return ( yield from res . json ( ) ) or { } except asyncio . TimeoutError : continue return { 'err' : "Could not connect to SMA at {} (timeout)" . format ( self . _url ) } | Fetch json data for requests . |
61,768 | def new_session ( self ) : body = yield from self . _fetch_json ( URL_LOGIN , self . _new_session_data ) self . sma_sid = jmespath . search ( 'result.sid' , body ) if self . sma_sid : return True msg = 'Could not start session, %s, got {}' . format ( body ) if body . get ( 'err' ) : if body . get ( 'err' ) == 503 : _LOGGER . error ( "Max amount of sessions reached" ) else : _LOGGER . error ( msg , body . get ( 'err' ) ) else : _LOGGER . error ( msg , "Session ID expected [result.sid]" ) return False | Establish a new session . |
61,769 | def read ( self , sensors ) : payload = { 'destDev' : [ ] , 'keys' : list ( set ( [ s . key for s in sensors ] ) ) } if self . sma_sid is None : yield from self . new_session ( ) if self . sma_sid is None : return False body = yield from self . _fetch_json ( URL_VALUES , payload = payload ) if body . get ( 'err' ) == 401 : _LOGGER . warning ( "401 error detected, closing session to force " "another login attempt" ) self . close_session ( ) return False _LOGGER . debug ( json . dumps ( body ) ) for sen in sensors : if sen . extract_value ( body ) : _LOGGER . debug ( "%s\t= %s %s" , sen . name , sen . value , sen . unit ) return True | Read a set of keys . |
61,770 | def media ( self , uri ) : try : local_path , _ = urllib . request . urlretrieve ( uri ) metadata = mutagen . File ( local_path , easy = True ) if metadata . tags : self . _tags = metadata . tags title = self . _tags . get ( TAG_TITLE , [ ] ) self . _manager [ ATTR_TITLE ] = title [ 0 ] if len ( title ) else '' artist = self . _tags . get ( TAG_ARTIST , [ ] ) self . _manager [ ATTR_ARTIST ] = artist [ 0 ] if len ( artist ) else '' album = self . _tags . get ( TAG_ALBUM , [ ] ) self . _manager [ ATTR_ALBUM ] = album [ 0 ] if len ( album ) else '' local_uri = 'file://{}' . format ( local_path ) except Exception : local_uri = uri self . _player . set_state ( Gst . State . NULL ) self . _player . set_property ( PROP_URI , local_uri ) self . _player . set_state ( Gst . State . PLAYING ) self . state = STATE_PLAYING self . _manager [ ATTR_URI ] = uri self . _manager [ ATTR_DURATION ] = self . _duration ( ) self . _manager [ ATTR_VOLUME ] = self . _player . get_property ( PROP_VOLUME ) _LOGGER . info ( 'playing %s (as %s)' , uri , local_uri ) | Play a media file . |
61,771 | def play ( self ) : if self . state == STATE_PAUSED : self . _player . set_state ( Gst . State . PLAYING ) self . state = STATE_PLAYING | Change state to playing . |
61,772 | def pause ( self ) : if self . state == STATE_PLAYING : self . _player . set_state ( Gst . State . PAUSED ) self . state = STATE_PAUSED | Change state to paused . |
61,773 | def stop ( self ) : urllib . request . urlcleanup ( ) self . _player . set_state ( Gst . State . NULL ) self . state = STATE_IDLE self . _tags = { } | Stop pipeline . |
61,774 | def set_position ( self , position ) : if position > self . _duration ( ) : return position_ns = position * _NANOSEC_MULT self . _manager [ ATTR_POSITION ] = position self . _player . seek_simple ( _FORMAT_TIME , Gst . SeekFlags . FLUSH , position_ns ) | Set media position . |
61,775 | def state ( self , state ) : self . _state = state self . _manager [ ATTR_STATE ] = state _LOGGER . info ( 'state changed to %s' , state ) | Set state . |
61,776 | def _duration ( self ) : duration = 0 if self . state != STATE_IDLE : resp = self . _player . query_duration ( _FORMAT_TIME ) duration = resp [ 1 ] // _NANOSEC_MULT return duration | Get media duration . |
61,777 | def _position ( self ) : position = 0 if self . state != STATE_IDLE : resp = self . _player . query_position ( _FORMAT_TIME ) position = resp [ 1 ] // _NANOSEC_MULT return position | Get media position . |
61,778 | def _on_message ( self , bus , message ) : if message . type == Gst . MessageType . EOS : self . stop ( ) elif message . type == Gst . MessageType . ERROR : self . stop ( ) err , _ = message . parse_error ( ) _LOGGER . error ( '%s' , err ) | When a message is received from Gstreamer . |
61,779 | def get_previous_node ( node ) : if node . prev_sibling : return node . prev_sibling if node . parent : return get_previous_node ( node . parent ) | Return the node before this node . |
61,780 | def casperjs_command_kwargs ( ) : kwargs = { 'stdout' : subprocess . PIPE , 'stderr' : subprocess . PIPE , 'universal_newlines' : True } phantom_js_cmd = app_settings [ 'PHANTOMJS_CMD' ] if phantom_js_cmd : path = '{0}:{1}' . format ( os . getenv ( 'PATH' , '' ) , os . path . dirname ( phantom_js_cmd ) ) kwargs . update ( { 'env' : { 'PATH' : path } } ) return kwargs | will construct kwargs for cmd |
61,781 | def casperjs_capture ( stream , url , method = None , width = None , height = None , selector = None , data = None , waitfor = None , size = None , crop = None , render = 'png' , wait = None ) : if isinstance ( stream , six . string_types ) : output = stream else : with NamedTemporaryFile ( 'wb+' , suffix = '.%s' % render , delete = False ) as f : output = f . name try : cmd = CASPERJS_CMD + [ url , output ] cmd += [ '--format=%s' % render ] if method : cmd += [ '--method=%s' % method ] if width : cmd += [ '--width=%s' % width ] if height : cmd += [ '--height=%s' % height ] if selector : cmd += [ '--selector=%s' % selector ] if data : cmd += [ '--data="%s"' % json . dumps ( data ) ] if waitfor : cmd += [ '--waitfor=%s' % waitfor ] if wait : cmd += [ '--wait=%s' % wait ] logger . debug ( cmd ) proc = subprocess . Popen ( cmd , ** casperjs_command_kwargs ( ) ) stdout = proc . communicate ( ) [ 0 ] process_casperjs_stdout ( stdout ) size = parse_size ( size ) render = parse_render ( render ) if size or ( render and render != 'png' and render != 'pdf' ) : image_postprocess ( output , stream , size , crop , render ) else : if stream != output : with open ( output , 'rb' ) as out : stream . write ( out . read ( ) ) stream . flush ( ) finally : if stream != output : os . unlink ( output ) | Captures web pages using casperjs |
61,782 | def process_casperjs_stdout ( stdout ) : for line in stdout . splitlines ( ) : bits = line . split ( ':' , 1 ) if len ( bits ) < 2 : bits = ( 'INFO' , bits ) level , msg = bits if level == 'FATAL' : logger . fatal ( msg ) raise CaptureError ( msg ) elif level == 'ERROR' : logger . error ( msg ) else : logger . info ( msg ) | Parse and digest capture script output . |
61,783 | def parse_url ( request , url ) : try : validate = URLValidator ( ) validate ( url ) except ValidationError : if url . startswith ( '/' ) : host = request . get_host ( ) scheme = 'https' if request . is_secure ( ) else 'http' url = '{scheme}://{host}{uri}' . format ( scheme = scheme , host = host , uri = url ) else : url = request . build_absolute_uri ( reverse ( url ) ) return url | Parse url URL parameter . |
61,784 | def parse_render ( render ) : formats = { 'jpeg' : guess_all_extensions ( 'image/jpeg' ) , 'png' : guess_all_extensions ( 'image/png' ) , 'gif' : guess_all_extensions ( 'image/gif' ) , 'bmp' : guess_all_extensions ( 'image/x-ms-bmp' ) , 'tiff' : guess_all_extensions ( 'image/tiff' ) , 'xbm' : guess_all_extensions ( 'image/x-xbitmap' ) , 'pdf' : guess_all_extensions ( 'application/pdf' ) } if not render : render = 'png' else : render = render . lower ( ) for k , v in formats . items ( ) : if '.%s' % render in v : render = k break else : render = 'png' return render | Parse render URL parameter . |
61,785 | def parse_size ( size_raw ) : try : width_str , height_str = size_raw . lower ( ) . split ( 'x' ) except AttributeError : size = None except ValueError : size = None else : try : width = int ( width_str ) assert width > 0 except ( ValueError , AssertionError ) : width = None try : height = int ( height_str ) assert height > 0 except ( ValueError , AssertionError ) : height = None size = width , height if not all ( size ) : size = None return size | Parse size URL parameter . |
61,786 | def build_absolute_uri ( request , url ) : if app_settings . get ( 'CAPTURE_ROOT_URL' ) : return urljoin ( app_settings . get ( 'CAPTURE_ROOT_URL' ) , url ) return request . build_absolute_uri ( url ) | Allow to override printing url not necessarily on the same server instance . |
61,787 | def render_template ( template_name , context , format = 'png' , output = None , using = None , ** options ) : stream = BytesIO ( ) out_f = None with NamedTemporaryFile ( suffix = '.html' ) as render_file : template_content = render_to_string ( template_name , context , using = using , ) static_url = getattr ( settings , 'STATIC_URL' , '' ) if settings . STATIC_ROOT and static_url and not static_url . startswith ( 'http' ) : template_content = template_content . replace ( static_url , 'file://%s' % settings . STATIC_ROOT ) render_file . write ( template_content . encode ( 'utf-8' ) ) render_file . seek ( 0 ) casperjs_capture ( stream , url = 'file://%s' % render_file . name , ** options ) if not output : out_f = NamedTemporaryFile ( ) else : out_f = open ( output , 'wb' ) out_f . write ( stream . getvalue ( ) ) out_f . seek ( 0 ) if not output : return out_f else : out_f . close ( ) | Render a template from django project and return the file object of the result . |
61,788 | def go ( fn , * args , ** kwargs ) : if not callable ( fn ) : raise TypeError ( 'go() requires a function, not %r' % ( fn , ) ) result = [ None ] error = [ ] def target ( ) : try : result [ 0 ] = fn ( * args , ** kwargs ) except Exception : if sys : error . extend ( sys . exc_info ( ) ) t = threading . Thread ( target = target ) t . daemon = True t . start ( ) def get_result ( timeout = 10 ) : t . join ( timeout ) if t . is_alive ( ) : raise AssertionError ( 'timed out waiting for %r' % fn ) if error : reraise ( * error ) return result [ 0 ] return get_result | Launch an operation on a thread and get a handle to its future result . |
61,789 | def going ( fn , * args , ** kwargs ) : future = go ( fn , * args , ** kwargs ) try : yield future except : exc_info = sys . exc_info ( ) try : future ( timeout = 1 ) except : log_message = ( '\nerror in %s:\n' % format_call ( inspect . currentframe ( ) ) ) sys . stderr . write ( log_message ) traceback . print_exc ( ) reraise ( * exc_info ) else : future ( timeout = 10 ) | Launch a thread and wait for its result before exiting the code block . |
61,790 | def _get_c_string ( data , position ) : end = data . index ( b"\x00" , position ) return _utf_8_decode ( data [ position : end ] , None , True ) [ 0 ] , end + 1 | Decode a BSON C string to python unicode string . |
61,791 | def _synchronized ( meth ) : @ functools . wraps ( meth ) def wrapper ( self , * args , ** kwargs ) : with self . _lock : return meth ( self , * args , ** kwargs ) return wrapper | Call method while holding a lock . |
61,792 | def mock_server_receive_request ( client , server ) : header = mock_server_receive ( client , 16 ) length = _UNPACK_INT ( header [ : 4 ] ) [ 0 ] request_id = _UNPACK_INT ( header [ 4 : 8 ] ) [ 0 ] opcode = _UNPACK_INT ( header [ 12 : ] ) [ 0 ] msg_bytes = mock_server_receive ( client , length - 16 ) if opcode not in OPCODES : raise NotImplementedError ( "Don't know how to unpack opcode %d yet" % opcode ) return OPCODES [ opcode ] . unpack ( msg_bytes , client , server , request_id ) | Take a client socket and return a Request . |
61,793 | def mock_server_receive ( sock , length ) : msg = b'' while length : chunk = sock . recv ( length ) if chunk == b'' : raise socket . error ( errno . ECONNRESET , 'closed' ) length -= len ( chunk ) msg += chunk return msg | Receive length bytes from a socket object . |
61,794 | def make_docs ( * args , ** kwargs ) : err_msg = "Can't interpret args: " if not args and not kwargs : return [ ] if not args : return [ kwargs ] if isinstance ( args [ 0 ] , ( int , float , bool ) ) : if args [ 1 : ] : raise_args_err ( err_msg , ValueError ) doc = OrderedDict ( { 'ok' : args [ 0 ] } ) doc . update ( kwargs ) return [ doc ] if isinstance ( args [ 0 ] , ( list , tuple ) ) : if not all ( isinstance ( doc , ( OpReply , Mapping ) ) for doc in args [ 0 ] ) : raise_args_err ( 'each doc must be a dict:' ) if kwargs : raise_args_err ( err_msg , ValueError ) return list ( args [ 0 ] ) if isinstance ( args [ 0 ] , ( string_type , text_type ) ) : if args [ 2 : ] : raise_args_err ( err_msg , ValueError ) if len ( args ) == 2 : doc = OrderedDict ( { args [ 0 ] : args [ 1 ] } ) else : doc = OrderedDict ( { args [ 0 ] : 1 } ) doc . update ( kwargs ) return [ doc ] if kwargs : raise_args_err ( err_msg , ValueError ) if not all ( isinstance ( doc , ( OpReply , Mapping ) ) for doc in args ) : raise_args_err ( 'each doc must be a dict' ) return args | Make the documents for a Request or Reply . |
61,795 | def make_prototype_request ( * args , ** kwargs ) : if args and inspect . isclass ( args [ 0 ] ) and issubclass ( args [ 0 ] , Request ) : request_cls , arg_list = args [ 0 ] , args [ 1 : ] return request_cls ( * arg_list , ** kwargs ) if args and isinstance ( args [ 0 ] , Request ) : if args [ 1 : ] or kwargs : raise_args_err ( "can't interpret args" ) return args [ 0 ] return Request ( * args , ** kwargs ) | Make a prototype Request for a Matcher . |
61,796 | def docs_repr ( * args ) : sio = StringIO ( ) for doc_idx , doc in enumerate ( args ) : if doc_idx > 0 : sio . write ( u', ' ) sio . write ( text_type ( json_util . dumps ( doc ) ) ) return sio . getvalue ( ) | Stringify ordered dicts like a regular ones . |
61,797 | def seq_match ( seq0 , seq1 ) : len_seq1 = len ( seq1 ) if len_seq1 < len ( seq0 ) : return False seq1_idx = 0 for i , elem in enumerate ( seq0 ) : while seq1_idx < len_seq1 : if seq1 [ seq1_idx ] == elem : break seq1_idx += 1 if seq1_idx >= len_seq1 or seq1 [ seq1_idx ] != elem : return False seq1_idx += 1 return True | True if seq0 is a subset of seq1 and their elements are in same order . |
61,798 | def raise_args_err ( message = 'bad arguments' , error_class = TypeError ) : frame = inspect . currentframe ( ) . f_back raise error_class ( message + ': ' + format_call ( frame ) ) | Throw an error with standard message displaying function call . |
61,799 | def interactive_server ( port = 27017 , verbose = True , all_ok = False , name = 'MockupDB' , ssl = False , uds_path = None ) : if uds_path is not None : port = None server = MockupDB ( port = port , verbose = verbose , request_timeout = int ( 1e6 ) , ssl = ssl , auto_ismaster = True , uds_path = uds_path ) if all_ok : server . append_responder ( { } ) server . autoresponds ( 'whatsmyuri' , you = 'localhost:12345' ) server . autoresponds ( { 'getLog' : 'startupWarnings' } , log = [ 'hello from %s!' % name ] ) server . autoresponds ( OpMsg ( 'buildInfo' ) , version = 'MockupDB ' + __version__ ) server . autoresponds ( OpMsg ( 'listCollections' ) ) server . autoresponds ( 'replSetGetStatus' , ok = 0 ) server . autoresponds ( 'getFreeMonitoringStatus' , ok = 0 ) return server | A MockupDB that the mongo shell can connect to . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.