Run the WMI query and return the data.
969531
def WmiQueryFromClient(args):
  """"""
  query = args.query
  base_object = args.base_object or r"winmgmts:\root\cimv2"

  if not query.upper().startswith("SELECT "):
    raise RuntimeError("Only SELECT WMI queries allowed.")

  for response_dict in RunWMIQuery(query, baseobj=base_object):
    yield response_dict
716551
def _get_data(self, read_size):
        """"""
        if NIX:
            return super(Mouse, self)._get_data(read_size)
        return self._pipe.recv_bytes()
870682
def query(self, query, *parameters, **kwargs):
        """"""
        cursor = self._cursor()
        try:
            self._execute(cursor, query, parameters or None, kwargs)
            if cursor.description:
                column_names = [column.name for column in cursor.description]
                res = [Row(zip(column_names, row)) for row in cursor.fetchall()]
                cursor.close()
                return res
        except:
            cursor.close()
            raise
1065576
def do_query(self, args):
        

        if not self.current:
            print('There are no resources in use. Use the command "open".')
            return

        try:
            print('Response: {}'.format(self.current.query(args)))
        except Exception as e:
            print(e)
981050
def run(self):
        """"""
        query = self.query

        # count before filtering
        self.cardinality = query.add_columns(self.columns[0].sqla_expr).count()

        self._set_column_filter_expressions()
        self._set_global_filter_expression()
        self._set_sort_expressions()
        self._set_yadcf_data(query)

        # apply filters
        query = query.filter(
            *[e for e in self.filter_expressions if e is not None])

        self.cardinality_filtered = query.add_columns(
            self.columns[0].sqla_expr).count()

        # apply sorts
        query = query.order_by(
            *[e for e in self.sort_expressions if e is not None])

        # add paging options
        length = int(self.params.get('length'))
        if length >= 0:
            query = query.limit(length)
        elif length == -1:
            pass
        else:
            raise (ValueError(
                'Length should be a positive integer or -1 to disable'))
        query = query.offset(int(self.params.get('start')))

        # add columns to query
        query = query.add_columns(*[c.sqla_expr for c in self.columns])

        # fetch the result of the queries
        column_names = [
            col.mData if col.mData else str(i)
            for i, col in enumerate(self.columns)
        ]
        self.results = [{k: v
                         for k, v in zip(column_names, row)}
                        for row in query.all()]
1169698
def getquery(query):
	''
	try:
		conn = connection.cursor()
		conn.execute(query)
		data = conn.fetchall()
		conn.close()
	except: data = list()
	return data
1299374
def query(self,
              startTime=None,
              endTime=None,
              sinceServerStart=False,
              level="WARNING",
              services="*",
              machines="*",
              server="*",
              codes=[],
              processIds=[],
              export=False,
              exportType="CSV", #CSV or TAB
              out_path=None
              ):
        
        allowed_levels = ("SEVERE", "WARNING", "INFO",
                          "FINE", "VERBOSE", "DEBUG")
        qFilter = {
            "services": "*",
            "machines": "*",
            "server" : "*"
        }
        if len(processIds) > 0:
            qFilter['processIds'] = processIds
        if len(codes) > 0:
            qFilter['codes'] = codes
        params = {
            "f" : "json",
            "sinceServerStart" : sinceServerStart,
            "pageSize" : 10000
        }
        if startTime is not None and \
           isinstance(startTime, datetime):
            params['startTime'] = startTime.strftime("%Y-%m-%dT%H:%M:%S")
        if endTime is not None and \
           isinstance(endTime, datetime):
            params['endTime'] = endTime.strftime("%Y-%m-%dT%H:%M:%S")
        if level.upper() in allowed_levels:
            params['level'] = level
        if server != "*":
            qFilter['server'] = server.split(',')
        if services != "*":
            qFilter['services'] = services.split(',')
        if machines != "*":
            qFilter['machines'] = machines.split(",")
        params['filter'] = qFilter
        if export == True and \
           out_path is not None:
            messages = self._post(self._url + "/query", params,
                                     securityHandler=self._securityHandler,
                                     proxy_url=self._proxy_url,
                                     proxy_port=self._proxy_port)

            with open(name=out_path, mode='wb') as f:
                hasKeys = False
                if exportType == "TAB":
                    csvwriter = csv.writer(f, delimiter='\t')
                else:
                    csvwriter = csv.writer(f)
                for message in messages['logMessages']:
                    if hasKeys == False:
                        csvwriter.writerow(message.keys())
                        hasKeys = True
                    csvwriter.writerow(message.values())
                    del message
            del messages
            return out_path
        else:
            return self._post(self._url + "/query", params,
                                 securityHandler=self._securityHandler,
                                 proxy_url=self._proxy_url,
                                 proxy_port=self._proxy_port)
858171
def run_object_query(client, base_object_query, start_record, limit_to,
                     verbose=False):
    """"""
    if verbose:
        print("[start: %d limit: %d]" % (start_record, limit_to))
    start = datetime.datetime.now()
    result = client.execute_object_query(
        object_query=base_object_query,
        start_record=start_record,
        limit_to=limit_to)
    end = datetime.datetime.now()
    if verbose:
        print("[%s - %s]" % (start, end))
    return result
701263
def data_from_query(self, cmd):
        
        res  = None
        ckey = "%s /%s" % (self.command, cmd)

        if not isinstance(self._query_params, dict):
            self._query_params = {}

        if ckey in _NCMD:
            self._cmd = _NCMD[ckey]
        else:
            for key in sorted(_RCMD, key=len, reverse=True):
                if not key.startswith("%s " % self.command):
                    continue

                m = _RCMD[key].name.match(cmd)
                if m:
                    self._cmd = _RCMD[key]
                    self._query_params.update(m.groupdict())
                    break

        try:
            if not self._cmd:
                raise self.req_error(404)

            if not self._cmd.to_log:
                self._to_log = False

            if self._cmd.to_auth:
                self.authenticate(self._cmd.auth_users)

            if self._cmd.static:
                if self._cmd.handler:
                    res = self._cmd.handler(self)

                return self.static_file(cmd, res)

            res = self._cmd.handler(self)

            if not isinstance(res, HttpResponse):
                return self.response_dumps(res)

            return res
        finally:
            self._query_params = {}
572149
def run(self):
        
        with zopen(self.output_file, 'w') as fout:
            return subprocess.Popen(self.nwchem_cmd + [self.input_file],
                                    stdout=fout)
327262
def execute(self):
        """"""

        logging.info('Requesting view metadata for project %s' % self.project_name)
        project_csv_meta = self.rws_connection.send_request(ProjectMetaDataRequest(self.project_name))

        # Process it into a set of tables
        self.db_adapter.processMetaData(project_csv_meta)

        # Get the data for the study
        for dataset_name in self.db_adapter.datasets.keys():
            logging.info('Requesting data from dataset %s' % dataset_name)
            form_name, _type = self.name_type_from_viewname(dataset_name)
            form_data = self.rws_connection.send_request(
                FormDataRequest(self.project_name, self.environment, _type, form_name))

            # Now process the form_data into the db of choice
            logging.info('Populating dataset %s' % dataset_name)
            self.db_adapter.processFormData(form_data, dataset_name)

        logging.info('Process complete')
222401
def query(query):
    '''
    
    '''

    # send the query to the Gaia archive
    with warnings.catch_warnings() :
        warnings.filterwarnings("ignore")

        _gaia_job = astroquery.gaia.Gaia.launch_job(query)

        # return the table of results
        return _gaia_job.get_results()
633116
def execute(self, query):
        
        c = self.conn.cursor()
        result = c.execute(query)
        for i in result:
            yield i
1370624
def run(client, outputs, no_output, success_codes, isolation, command_line):
    """"""
    working_dir = client.repo.working_dir
    mapped_std = _mapped_std_streams(client.candidate_paths)
    factory = CommandLineToolFactory(
        command_line=command_line,
        directory=os.getcwd(),
        working_dir=working_dir,
        successCodes=success_codes,
        **{
            name: os.path.relpath(path, working_dir)
            for name, path in mapped_std.items()
        }
    )

    with client.with_workflow_storage() as wf:
        with factory.watch(
            client, no_output=no_output, outputs=outputs
        ) as tool:
            # Make sure all inputs are pulled from a storage.
            client.pull_paths_from_storage(
                *(
                    path
                    for _, path in tool.iter_input_files(client.workflow_path)
                )
            )

            returncode = call(
                factory.command_line,
                cwd=os.getcwd(),
                **{key: getattr(sys, key)
                   for key in mapped_std.keys()},
            )

            if returncode not in (success_codes or {0}):
                raise errors.InvalidSuccessCode(
                    returncode, success_codes=success_codes
                )

            sys.stdout.flush()
            sys.stderr.flush()

            wf.add_step(run=tool)
829599
def _run_query(self, query):
        
        query_request = self.service.jobs()
        logger.debug('Running query: %s', query)
        start = datetime.now()
        resp = query_request.query(
            projectId=self.project_id, body={'query': query}
        ).execute()
        duration = datetime.now() - start
        logger.debug('Query response (in %s): %s', duration, resp)
        if not resp['jobComplete']:
            logger.error('Error: query reported job not complete!')
        if int(resp['totalRows']) == 0:
            return []
        if int(resp['totalRows']) != len(resp['rows']):
            logger.error('Error: query reported %s total rows, but only '
                         'returned %d', resp['totalRows'], len(resp['rows']))
        data = []
        fields = [f['name'] for f in resp['schema']['fields']]
        for row in resp['rows']:
            d = {}
            for idx, val in enumerate(row['f']):
                d[fields[idx]] = val['v']
            data.append(d)
        return data
1303295
def execute(self, limitRequest=350000, limitResMax=-1):
        """"""
        query = self.getQueries()
        query  = self.__buildLimit(query, limitResMax)
        nbr_results = limitResMax
        if (limitResMax == -1):
            query.setBaseUrl(self.__url+'/count')
            countUrl = query.getUrl()            
            result_count = Util.retrieveJsonResponseFromServer(countUrl)    
            nbr_results=result_count['total']
        else:
            nbr_results = limitResMax
        resultSearch = []
        if nbr_results < limitRequest :            
            query.setBaseUrl(self.__url+'/records')
            url = query.getUrl()
            startVal = query._getParameters()['start']
            while (nbr_results-startVal)>0 :#Do the job per 300 items till nbr_result is reached                
                resultTemp = Util.retrieveJsonResponseFromServer(url)
                resultSearch.extend(self.__parseResponse(resultTemp))
                parameters = query._getParameters()                
                startVal = parameters['start'] + parameters['limit']
                query = UpdateParameter(query, 'start', startVal) 
                query.setBaseUrl(self.__url+'/records')
		url=query.getUrl()            
        else:
            out_mess="Not allowed\nNbr results (%d) exceeds limit_request param: %d\n" % (nbr_results, limitRequest)
            self.__logger.info(out_mess)        
        return resultSearch
1027177
def run(self):
        """"""
        kwargs = {'query': self.get_data()}
        if self.data_type == "ip":
            kwargs.update({'query_type': 'ip'})
        elif self.data_type == "network":
            kwargs.update({'query_type': 'network'})
        elif self.data_type == 'autonomous-system':
            kwargs.update({'query_type': 'asn'})
        elif self.data_type == 'port':
            kwargs.update({'query_type': 'port'})
        else:
            self.notSupported()
            return False

        if self.service == 'observations':
            response = self.bs.get_observations(**kwargs)
            self.report(response)
        elif self.service == 'enrichment':
            response = self.bs.enrich(**kwargs)
            self.report(response)
        else:
            self.report({'error': 'Invalid service defined.'})