task basic queries
549948
@Override
    public TaskInstance findTaskByWorkItemId(Long workItemId) {
        if( config.isRest() ) {
            Map<String, Object> valuesMap = new HashMap<String, Object>();
            valuesMap.put(WORK_ITEM_ID, workItemId);

            return makeHttpGetRequestAndCreateCustomResponse(
                    build(loadBalancer.getUrl(), QUERY_URI + "/" + TASK_BY_WORK_ITEM_ID_GET_URI, valuesMap), TaskInstance.class);


        } else {
            CommandScript script = new CommandScript( Collections.singletonList( (KieServerCommand) new DescriptorCommand( "QueryService", "getTaskByWorkItemId", new Object[]{workItemId}) ) );
            ServiceResponse<TaskInstance> response = (ServiceResponse<TaskInstance>) executeJmsCommand( script, DescriptorCommand.class.getName(), "BPM" ).getResponses().get(0);

            throwExceptionOnFailure(response);
            if (shouldReturnWithNullResponse(response)) {
                return null;
            }
            return response.getResult();
        }
    }
654052
def find_all_by_parameters(self, task_name, session=None, **task_params):
        
        with self._session(session) as session:
            query = session.query(TaskRecord).join(TaskEvent).filter(TaskRecord.name == task_name)
            for (k, v) in six.iteritems(task_params):
                alias = sqlalchemy.orm.aliased(TaskParameter)
                query = query.join(alias).filter(alias.name == k, alias.value == v)

            tasks = query.order_by(TaskEvent.ts)
            for task in tasks:
                # Sanity check
                assert all(k in task.parameters and v == str(task.parameters[k].value) for (k, v) in six.iteritems(task_params))

                yield task
803869
def get_tasks(self, status=None, offset=None, limit=None):
        
        params = {'project': self.id, 'offset': offset, 'limit': limit}
        if status:
            params['status'] = status
        return self._api.tasks.query(api=self._api, **params)
165484
def get_task_db(self, fs_id):
        '''
        '''
        sql = 'SELECT * FROM tasks WHERE fsid=?'
        req = self.cursor.execute(sql, [fs_id, ])
        if req:
            return req.fetchone()
        else:
            None
662622
def query(sql, &blk)
      layer = SimplerTiles::Query.new(sql, &blk)
      add_query layer
    end
1019490
def list_tasks(collector):
    """"""
    print("Usage: dashmat <task>")
    print("")
    print("Available tasks to choose from are:")
    print("-----------------------------------")
    print("")
    keygetter = lambda item: item[1].label
    tasks = sorted(available_actions.items(), key=keygetter)
    sorted_tasks = sorted(list(tasks), key=lambda item: len(item[0]))
    max_length = max(len(name) for name, _ in sorted_tasks)
    for key, task in sorted_tasks:
        desc = dedent(task.__doc__ or "").strip().split('\n')[0]
        print("\t{0}{1} :-: {2}".format(" " * (max_length-len(key)), key, desc))
    print("")
1181616
def get_tasks():
    """"""
    from paver.tasks import environment
    for tsk in environment.get_tasks():
        print(tsk.shortname)
1307130
def get_task(client, task_id):
    '''  '''
    endpoint = '/'.join([client.api.Endpoints.TASKS, str(task_id)])
    response = client.authenticated_request(endpoint)
    return response.json()
301313
private void executeWork() {
        StatusTrail st = null;        
        if ((st = newWorkQueue.removeFirst()) != null) {
            log.info("New task {}", st);
            DataSource ds = db().getDataSource(st.getDataSourceId());//TODO: Cache the DataSource table.
            String frozenSql = materializeTemplate(ds.getTemplateSql(), st.getNominalTime(), st.getNominalTime(), st.getNominalTime() + JobFreq.valueOf(ds.getFrequency()).inMillis());
            log.info("Sql is {}", frozenSql);
            Either<String, Either<Joiner4All, Mapper4All>> result = druidDriver.query(frozenSql, null, null, false, "sql", true);
            if (result.isLeft()) {
                String taskId = result.left().get();// Because we forced async mode we will get back taskId.
                log.info("Submitted task {} to overlord ", taskId);
                st.setTaskId(taskId);
                st.setStatus(JobStatus.in_progress);
                db().updateStatusTrail(st);
                // Quite possible st may exist in Q- when an item is removed and executed
                // during which time if work generator generates the same st and 
                // updates Q because it still found the ST as not_done.
                if (newWorkQueue.contains(st)) {
                    newWorkQueue.remove(st);
                    log.warn("newWorkQueue had one more entry for st {} which was just set to in_progress", st);
                }                
            } else {// Something wrong. Insert always returns left.
                log.error("Got weird result (expected to run insert) {}", result.right().get());
            }
        }
    }
1016832
function(cb, thisArg) {
      if (cb instanceof Task)
        this.subTasks_.push(cb);
      else
        this.subTasks_.push(new Task(cb, thisArg));
      return this.subTasks_[this.subTasks_.length - 1];
    }
1163185
private void readWBS(ChildTaskContainer parent, Integer id)
   {
      Integer currentID = id;
      Table table = getTable("WBSTAB");

      while (currentID.intValue() != 0)
      {
         MapRow row = table.find(currentID);
         Integer taskID = row.getInteger("TASK_ID");
         Task task = readTask(parent, taskID);
         Integer childID = row.getInteger("CHILD_ID");
         if (childID.intValue() != 0)
         {
            readWBS(task, childID);
         }
         currentID = row.getInteger("NEXT_ID");
      }
   }
949041
private void processTasks() throws SQLException
   {
      List<Row> bars = getRows("select * from bar where projid=?", m_projectID);
      List<Row> expandedTasks = getRows("select * from expanded_task where projid=?", m_projectID);
      List<Row> tasks = getRows("select * from task where projid=?", m_projectID);
      List<Row> milestones = getRows("select * from milestone where projid=?", m_projectID);
      m_reader.processTasks(bars, expandedTasks, tasks, milestones);
   }
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)
553581
def query(transport, query):
    """"""
    with CommandLineClient(transport) as client:
        echo_event(client.query(query))
492760
function Task(task) {
  _.extend(this, task);
  if (task != undefined) this.createId();

  // Short id
  this.__defineGetter__('id', function () {
    return this.__uuid__.substr(0, 8).toString();
  });

  // Keyword
  this.__defineGetter__('keyword', function () {
    return this.labels[0].replace('#', '').toUpperCase();
  });

  // Stemmed
  this.__defineGetter__('stemmed', function () {
    return (this.title+' '+this.body).toLowerCase()
      .split(' ').map(stem).join(' ');
  });

  // All
  this.__defineGetter__('all', function () {
    return '*';
  });
}
180962
def get_batch_children(self):
        
        if not self.batch:
            raise SbgError("This task is not a batch task.")
        return self.query(parent=self.id, api=self._api)
939514
function filterTasks (type, tasks, alltasks) {
    var contains = function (task) {
        return _.includes(tasks, task.name);
    };

    if (type === 'include') {
        return _.filter(alltasks, contains);
    } else if (type === 'exclude') {
        return _.reject(alltasks, contains);
    }
    return alltasks;
}