Open a connection with the server_url and creds, and
        enumerate instances defined by the functions namespace and
        classname arguments.
        Displays either the error return or the mof for instances
        returned.
11647
def execute_request(server_url, creds, namespace, classname):
    

    print('Requesting url=%s, ns=%s, class=%s' % \
        (server_url, namespace, classname))

    try:
        # Create a connection
        CONN = WBEMConnection(server_url, creds,
                              default_namespace=namespace,
                              no_verification=True)

        #Issue the request to EnumerateInstances on the defined class
        INSTANCES = CONN.EnumerateInstances(classname)

        #Display of characteristics of the result object
        print('instances type=%s len=%s' % (type(INSTANCES),
                                            len(INSTANCES)))
        #display the mof output
        for inst in INSTANCES:
            print('path=%s\n' % inst.path)
            print(inst.tomof())

    # handle any exception
    except Error as err:
        # If CIMError, display CIMError attributes
        if isinstance(err, CIMError):
            print('Operation Failed: CIMError: code=%s, Description=%s' % \
                  (err.status_code_name, err.status_description))
        else:
            print ("Operation failed: %s" % err)
        sys.exit(1)
341473
def scoped_connection(func):
  '''
  
  '''
  def _with(series, *args, **kwargs):
    connection = None
    try:
      connection = series._connection()
      return func(series, connection, *args, **kwargs)
    finally:
      series._return( connection )
  return _with
84276
def _fake_openreferenceinstancepaths(self, namespace, **params):
        # pylint: disable=invalid-name
        
        self._validate_namespace(namespace)
        self._validate_open_params(**params)
        params['ObjectName'] = params['InstanceName']
        del params['InstanceName']

        result = self._fake_referencenames(namespace, **params)

        objects = [] if result is None else [x[2] for x in result[0][2]]

        return self._open_response(objects, namespace,
                                   'PullInstancePaths', **params)
848036
def is_connection_error(e):
    
    return (isinstance(e, err.InterfaceError) and e.args[0] == "(0, '')") or\
        (isinstance(e, err.OperationalError) and e.args[0] in operation_error_codes.values())
744871
def check_for_error(func):
    

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        try:
            response = func(*args, **kwargs)
            status_code = response.status_code
            if status_code in range(200, 204):
                return response
            if status_code == 204:
                return
            data = response.json()
            e = {
                400: BadRequest,
                401: Unauthorized,
                403: Forbidden,
                404: NotFound,
                405: MethodNotAllowed,
                408: RequestTimeout,
                409: Conflict,
                429: TooManyRequests,
                500: ServerError,
                503: ServiceUnavailable,
            }.get(status_code, SbgError)()
            if 'message' in data:
                e.message = data['message']
            if 'code' in data:
                e.code = data['code']
            if 'status' in data:
                e.status = data['status']
            if 'more_info' in data:
                e.more_info = data['more_info']
            raise e
        except requests.RequestException as e:
            raise SbgError(message=six.text_type(e))
        except JSONDecodeError:
            message = (
                'Service might be unavailable. Can also occur by providing '
                'too many query parameters.'
            )
            raise_from(
                ServiceUnavailable(message=six.text_type(message)), None
            )
        except ValueError as e:
            raise SbgError(message=six.text_type(e))

    return wrapper
1292775
def _get_instances(cls, path, context=None, site=None, language=None):
        
        backend_context = {'view_context': context }

        for model in cls._meta.models.values():
            for instance in model.objects.get_instances(path, site, language, backend_context) or []:
                if hasattr(instance, '_process_context'):
                    instance._process_context(backend_context)
                yield instance
542346
def instanceOf(cls, expected_instance): #pylint: disable=no-self-argument,invalid-name,no-self-use
        
        if not inspect.isclass(expected_instance):
            options = {}
            options["target_type"] = expected_instance
            return Matcher("__INSTANCE__", options)
        ErrorHandler.matcher_instance_error(expected_instance)
742475
function listInstances(search_opts, callback) {
    if (arguments.length === 1) {
        callback = search_opts;
        search_opts = {};
    }

    var uri = '/instances?' + qs.stringify(search_opts);
    return (this.get(uri, callback));
}
451114
def hello(self):
        
        for env in self.args.environment:
            juicer.utils.Log.log_info("Trying to open a connection to %s, %s ...",
                                      env, self.connectors[env].base_url)
            try:
                _r = self.connectors[env].get()
                juicer.utils.Log.log_info("OK")
            except JuicerError:
                juicer.utils.Log.log_info("FAILED")
                continue

            juicer.utils.Log.log_info("Attempting to authenticate as %s",
                                      self.connectors[env].auth[0])

            _r = self.connectors[env].get('/repositories/')

            if _r.status_code == Constants.PULP_GET_OK:
                juicer.utils.Log.log_info("OK")
            else:
                juicer.utils.Log.log_info("FAILED")
                juicer.utils.Log.log_info("Server said: %s", _r.content)
                continue
        return True
911327
def handle_url_build_error(self, error: Exception, endpoint: str, values: dict) -> str:
        
        for handler in self.url_build_error_handlers:
            result = handler(error, endpoint, values)
            if result is not None:
                return result
        raise error
406064
def process_parsed_args(opts: Namespace, error_fun: Optional[Callable], connect: bool=True) -> Namespace:
    
    def setdefault(vn: str, default: object) -> None:
        assert vn in opts, "Unknown option"
        if not getattr(opts, vn):
            setattr(opts, vn, default)

    if error_fun and \
            (getattr(opts, 'dburl') is None or getattr(opts, 'user') is None or getattr(opts, 'password') is None):
        error_fun("db url, user id and password must be supplied")
    setdefault('crcdb', opts.dburl)
    setdefault('crcuser', opts.user)
    setdefault('crcpassword', opts.password)
    setdefault('ontodb', opts.dburl)
    setdefault('ontouser', opts.user)
    setdefault('ontopassword', opts.password)
    if connect:
        opts.tables = I2B2Tables(opts)

    # TODO: This approach needs to be re-thought.  As i2b2tablenames is a singleton, any changes here
    # impact the entire testing harness
    if opts.onttable:
        i2b2tablenames.ontology_table = opts.onttable
    return opts
1181148
function(fn) {
            asyncjs.each(modelNames, function(name, _fn) {
                // get model definition
                var modelDefinition = modelDefinitions[name];
                modelDefinition.__name = name;

                // get connection info
                var connectionInfo = lib.findConnection(mycro, name);
                if (!connectionInfo) {
                    mycro.log('silly', '[models] Unable to find explicit adapter for model (' + name + ')');
                    if (!defaultConnection ) {
                        return _fn('Unable to find adapter for model (' + name + ')');
                    } else {
                        connectionInfo = defaultConnection;
                    }
                }

                // validate handler exists
                var adapter = connectionInfo.adapter;
                if (!adapter.registerModel || !_.isFunction(adapter.registerModel) || adapter.registerModel.length < 3) {
                    return _fn('Invalid adapter api: adapters should define a `registerModel` method that accepts a connection object, model definition object, and a callback');
                }

                // hand off to adapter
                var registerModelCallback = function(err, model) {
                    if (err) {
                        return _fn(err);
                    }
                    if (!model) {
                        return _fn('No model (' + name + ') returned from `adapter.registerModel`');
                    }
                    mycro.models[name] = model;
                    _fn();
                };
                if (adapter.registerModel.length === 3) {
                    return adapter.registerModel(connectionInfo.connection, modelDefinition, registerModelCallback);
                } else if (adapter.registerModel.length === 4) {
                    return adapter.registerModel(connectionInfo.connection, modelDefinition, name, registerModelCallback);
                } else {
                    return adapter.registerModel(connectionInfo.connection, modelDefinition, name, mycro, registerModelCallback);
                }
            }, fn);
        }
876559
def connect(nickname, server_def, debug=None, timeout=10):
    
    url = server_def.url
    conn = pywbem.WBEMConnection(
        url,
        (server_def.user, server_def.password),
        default_namespace=server_def.implementation_namespace,
        no_verification=server_def.no_verification,
        timeout=timeout)
    if debug:
        conn.debug = True

    ns = server_def.implementation_namespace if \
        server_def.implementation_namespace \
        else 'interop'
    try:
        conn.GetQualifier('Association', namespace=ns)
        return conn
    except pywbem.ConnectionError as exc:
        print("Test server {0} at {1!r} cannot be reached. {2}: {3}".
              format(nickname, url, exc.__class__.__name__, exc))
        return None
    except pywbem.AuthError as exc:
        print("Test server {0} at {1!r} cannot be authenticated with. "
              "{2}: {3}". format(nickname, url,
                                 exc.__class__.__name__, exc))
        return None
    except pywbem.CIMError as ce:
        if ce.status_code == pywbem.CIM_ERR_NAMESPACE_NOT_FOUND or \
                ce.status.code == pywbem.CIM_ERR_NOT_FOUND:
            return conn
        else:
            return None
    except pywbem.Error as exc:
        print("Test server {0} at {1!r} returned exception. {2}: {3}".
              format(nickname, url, exc.__class__.__name__, exc))
    return None
1357006
def main():
    

    # if less than required arguments, use the defaults
    if len(sys.argv) < 8:
        print("Usage: %s server_url username password namespace classname "
              "max_open, max_pull" %  sys.argv[0])
        server_url = SERVER_URL
        username = USERNAME
        password = PASSWORD
        namespace = TEST_NAMESPACE
        classname = TEST_CLASS
        max_open = 0
        max_pull = 100
    else:
        server_url = sys.argv[1]
        username = sys.argv[2]
        password = sys.argv[3]
        namespace = sys.argv[4]
        classname = sys.argv[5]
        max_open = sys.argv[6]
        max_pull = sys.argv[7]

    print('Parameters: server_url=%s\n username=%s\n namespace=%s\n' \
          ' classname=%s\n max_open=%s,\n max_pull=%s' % \
          (server_url, username, namespace, classname, max_open, max_pull))

    # connect to the server
    conn = WBEMConnection(server_url, (username, password),
                          default_namespace=namespace,
                          no_verification=True)

    #Call method to execute the enumeration sequence and return instances
    try:
        instances = execute_request(conn, classname, max_open, max_pull)

        # print the resulting instances
        for instance in instances:
            print('\npath=%s\n%s' % (instance.path, instance.tomof()))

    # handle exceptions
    except CIMError as ce:
        print('Operation Failed: CIMError: code=%s, Description=%s' % \
              (ce.status_code_name, ce.status_description))
        sys.exit(1)
    except Error as err:
        print ("Operation failed: %s" % err)
        sys.exit(1)

    return 0
745107
def each_instance( namespace_or_objectpath, classname = nil )
    op = if namespace_or_objectpath.is_a? Sfcc::Cim::ObjectPath
      namespace_or_objectpath
    else
      objectpath namespace_or_objectpath, classname
    end
    begin
      @client.instances(op).each do |inst|
        yield inst
      end
    rescue Sfcc::Cim::ErrorInvalidClass, Sfcc::Cim::ErrorInvalidNamespace
    end
  end
693573
def calling_code(f, f_name=None, raise_for_missing=True):
    
    import inspect
    from ambry.dbexceptions import ConfigurationError

    if inspect.isclass(f):
        try:
            args = inspect.getargspec(f.__init__).args
        except TypeError as e:
            raise TypeError("Failed to inspect {}: {}".format(f, e))

    else:
        args = inspect.getargspec(f).args

    if len(args) > 1 and args[0] == 'self':
        args = args[1:]

    for a in args:
        if a not in all_args + ('exception',):  # exception arg is only for exception handlers
            if raise_for_missing:
                raise ConfigurationError('Caster code {} has unknown argument '
                                         'name: \'{}\'. Must be one of: {} '.format(f, a, ','.join(all_args)))

    arg_map = {e: e for e in var_args}

    args = [arg_map.get(a, a) for a in args]

    return "{}({})".format(f_name if f_name else f.__name__, ','.join(args))
544672
def show_service(kwargs=None, conn=None, call=None):
    '''
    
    '''
    if call != 'function':
        raise SaltCloudSystemExit(
            'The show_service function must be called with -f or --function.'
        )

    if not conn:
        conn = get_conn()

    if kwargs is None:
        kwargs = {}

    if 'name' not in kwargs:
        raise SaltCloudSystemExit('A name must be specified as "name"')

    data = conn.get_hosted_service_properties(
        kwargs['name'],
        kwargs.get('details', False)
    )
    ret = object_to_dict(data)
    return ret