Execute a Mesos API call.
962938
def _get(self, path):
        
        url = self._get_url(path)
        try:
            response = urllib2.urlopen(url)
        except Exception as err:
            self.log.error("%s: %s", url, err)
            return False

        try:
            doc = json.load(response)
        except (TypeError, ValueError):
            self.log.error("Unable to parse response from Mesos as a"
                           " json object")
            return False

        return doc
471221
def run(self):
        """"""
        resp = _wait_until(obj=self.obj, att=self.att,
                desired=self.desired, callback=None,
                interval=self.interval, attempts=self.attempts,
                verbose=False, verbose_atts=None)
        self.callback(resp)
315665
def _call(self, method, url, params):
        """"""
        request_params = {}
        if method == 'GET':
            request_params['params'] = params
        elif method == 'POST':
            request_params['data'] = params
        response = requests.request(method, url, **request_params)
        return response
344206
def run(self, target, payload, instance=None, hook_id=None, **kwargs):
        
        response = requests.post(
            url=target,
            data=json.dumps(payload, cls=DjangoJSONEncoder),
            headers={'Content-Type': 'application/json'}
        )

        if response.status_code == 410 and hook_id:
            HookModel = get_hook_model()
            hook = HookModel.object.get(id=hook_id)
            hook.delete()
999006
def call_api(http_method, path, opts = {})
      request = build_request(http_method, path, opts)
      response = request.run

      if @config.debugging
        @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
      end

      unless response.success?
        if response.timed_out?
          fail ApiError.new('Connection timed out')
        elsif response.code == 0
          # Errors from libcurl will be made visible here
          fail ApiError.new(:code => 0,
                            :message => response.return_message)
        else
          exception_message = nil
          response_json = JSON.parse(response.body) rescue nil
          if response_json.is_a? Hash
            if response_json['errors'].is_a? Array
              response_errors = response_json['errors'].join(', ')
            elsif response_json['error']
              response_errors = response_json['error']
            end
            if response_errors
              exception_message = "#{response.status_message}: #{response_errors}"
            end
          end

          unless exception_message
            exception_message = "#{response.status_message}: [Could not parse errors from response body]"
          end

          fail ApiError.new(:code => response.code,
                            :response_headers => response.headers,
                            :response_body => response.body),
               exception_message
        end
      end

      if opts[:return_type]
        data = deserialize(response, opts[:return_type])
      else
        data = nil
      end
      return data, response.code, response.headers
    end
511938
def _make_call(self, call):
        """"""
        try:
            request = urllib2.Request(self.config.environment, E.tostring(call))
            request.add_header('Content-Type', 'text/xml')
            response = urllib2.urlopen(request).read()
            response = E.fromstring(response)
            response_json = parse_response(response)
        except urllib2.HTTPError:
            raise AuthorizeConnectionError('Error processing XML request.')

        # Exception handling for transaction response errors.
        try:
            error = response_json.transaction_response.errors[0]
            raise AuthorizeResponseError(error.error_code, error.error_text, response_json)
        except (KeyError, AttributeError):  # Attempt to access transaction response errors
            pass

        # Throw an exception for invalid calls. This makes error handling easier.
        if response_json.messages[0].result_code != 'Ok':
            error = response_json.messages[0].message
            raise AuthorizeResponseError(error.code, error.text, response_json)

        return response_json
60065
def execute(self, request_object):
        """"""

        # If the request object is not valid then return a failure response
        if not request_object.is_valid:
            return ResponseFailure.build_from_invalid_request(
                request_object)

        # Try to process the request and handle any errors encountered
        try:
            return self.process_request(request_object)

        except ValidationError as err:
            return ResponseFailure.build_unprocessable_error(err.normalized_messages)

        except ObjectNotFoundError:
            return ResponseFailure.build_not_found(
                [{'identifier': 'Object with this ID does not exist.'}])

        except Exception as exc:
            logger.error(
                f'{self.__class__.__name__} execution failed due to error {exc}',
                exc_info=True)
            return ResponseFailure.build_system_error([{exc.__class__.__name__: exc}])
827118
def make_api_call(self, call, params):
        """"""

        if not isinstance(params, dict):
            raise ValueError("params argument must be a dictionary")
        kw = dict(
            params=params,
            headers={"Origin": BASE_URL, "Referer": f"{BASE_URL}/r/{self.room.name}"},
        )
        return self.get(BASE_REST_URL + call, **kw).json()
88683
def execute(options):
    """"""
    # Load the key in PKCS 12 format that you downloaded from the Google APIs
    # Console when you created your Service account.
    package_name = options['<package>']
    source_directory = options['<output_dir>']

    if options['upload'] is True:
        upstream = True
    else:
        upstream = False

    sub_tasks = {'images': options['--images'], 'listings': options['--listings'], 'inapp': options['--inapp']}
    if sub_tasks == {'images': False, 'listings': False, 'inapp': False}:
        sub_tasks = {'images': True, 'listings': True, 'inapp': True}

    credentials = create_credentials(credentials_file=options['--credentials'],
                                     service_email=options['--service-email'],
                                     service_key=options['--key'])

    command = SyncCommand(
        package_name, source_directory, upstream, credentials, **sub_tasks)
    command.execute()
1238812
public void run() {
    Protos.FrameworkInfo.Builder frameworkInfo = Protos.FrameworkInfo.newBuilder()
        .setName("alluxio").setCheckpoint(true);

    if (ServerConfiguration.isSet(PropertyKey.INTEGRATION_MESOS_ROLE)) {
      frameworkInfo.setRole(ServerConfiguration.get(PropertyKey.INTEGRATION_MESOS_ROLE));
    }
    if (ServerConfiguration.isSet(PropertyKey.INTEGRATION_MESOS_USER)) {
      frameworkInfo.setUser(ServerConfiguration.get(PropertyKey.INTEGRATION_MESOS_USER));
    } else {
      // Setting the user to an empty string will prompt Mesos to set it to the current user.
      frameworkInfo.setUser("");
    }

    if (ServerConfiguration.isSet(PropertyKey.INTEGRATION_MESOS_PRINCIPAL)) {
      frameworkInfo.setPrincipal(ServerConfiguration.get(PropertyKey.INTEGRATION_MESOS_PRINCIPAL));
    }

    // Publish WebUI url to mesos master.
    String masterWebUrl = createMasterWebUrl();
    frameworkInfo.setWebuiUrl(masterWebUrl);

    Scheduler scheduler = new AlluxioScheduler(mAlluxioMasterHostname);

    Protos.Credential cred = createCredential();
    MesosSchedulerDriver driver;
    if (cred == null) {
      driver = new MesosSchedulerDriver(scheduler, frameworkInfo.build(), mMesosMaster);
    } else {
      driver = new MesosSchedulerDriver(scheduler, frameworkInfo.build(), mMesosMaster, cred);
    }

    int status = driver.run() == Protos.Status.DRIVER_STOPPED ? 0 : 1;

    System.exit(status);
  }
780532
def execute(self, fn, *args, **kwargs):
        """"""
        if self.in_executor_context():
            corofn = asyncio.coroutine(lambda: fn(*args, **kwargs))
            return corofn()
        future = self.submit(fn, *args, **kwargs)
        return future.result()
767314
def execute(self, query, *parameters, **kwargs):
        """"""
        cursor = self._cursor()
        try:
            self._execute(cursor, query, parameters, kwargs)

        except:
            raise

        finally:
            cursor.close()
499819
def execute(self, compiled=None, path=None, use_eval=False, allow_show=True):
        """"""
        self.check_runner()
        if compiled is not None:
            if allow_show and self.show:
                print(compiled)
            if path is not None:  # path means header is included, and thus encoding must be removed
                compiled = rem_encoding(compiled)
            self.runner.run(compiled, use_eval=use_eval, path=path, all_errors_exit=(path is not None))
            self.run_mypy(code=self.runner.was_run_code())
712944
def _execute(self, endpoint, database, query, default_timeout, properties=None):
        """"""

        request_payload = {"db": database, "csl": query}
        if properties:
            request_payload["properties"] = properties.to_json()

        request_headers = {
            "Accept": "application/json",
            "Accept-Encoding": "gzip,deflate",
            "Content-Type": "application/json; charset=utf-8",
            "x-ms-client-version": "Kusto.Python.Client:" + VERSION,
            "x-ms-client-request-id": "KPC.execute;" + str(uuid.uuid4()),
        }

        if self._auth_provider:
            request_headers["Authorization"] = self._auth_provider.acquire_authorization_header()

        timeout = self._get_timeout(properties, default_timeout)
        response = self._session.post(endpoint, headers=request_headers, json=request_payload, timeout=timeout.seconds)

        if response.status_code == 200:
            if endpoint.endswith("v2/rest/query"):
                return KustoResponseDataSetV2(response.json())
            return KustoResponseDataSetV1(response.json())

        raise KustoServiceError([response.json()], response)
669546
def call_api(self,
                 action,
                 params=None,
                 method=('API', 'POST', 'application/x-www-form-urlencoded'),
                 **kwargs):
        
        urltype, methodname, content_type = method
        if urltype == 'SMS':
            url = self.sms_host
        else:
            url = self.api_host
        if content_type == 'application/json':
            data = json.dumps(params)
        else:
            data = self._filter_params(params)
        return self._http_call(
            url=url + action,
            method=methodname,
            data=data,
            headers=self._headers(content_type),
            **kwargs)
1185724
def perform_query(self, query, **params):
        """"""
        try:
            return self.engine.execute(query, params)
        except:
            print("Error with query: {}".format(query))
            raise
687483
def execute(self, input_data):
        '''  '''

        # Just a small check to make sure we haven't been called on the wrong file type
        if (input_data['meta']['type_tag'] != 'zip'):
            return {'error': self.__class__.__name__+': called on '+input_data['meta']['type_tag']}

        view = {}
        view['payload_md5s'] = input_data['unzip']['payload_md5s']
        view['yara_sigs'] = input_data['yara_sigs']['matches'].keys()
        view.update(input_data['meta'])

        # Okay this view is going to also give the meta data about the payloads
        view['payload_meta'] = [self.workbench.work_request('meta', md5) for md5 in input_data['unzip']['payload_md5s']]
        return view