text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.camunda.bpm.engine.test.api.mgmt;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.exception.NotFoundException;
import org.camunda.bpm.engine.exception.NullValueException;
import org.camunda.bpm.engine.history.HistoricIncident;
import org.camunda.bpm.engine.impl.ProcessEngineImpl;
import org.camunda.bpm.engine.impl.cmd.AcquireJobsCmd;
import org.camunda.bpm.engine.impl.interceptor.Command;
import org.camunda.bpm.engine.impl.interceptor.CommandContext;
import org.camunda.bpm.engine.impl.interceptor.CommandExecutor;
import org.camunda.bpm.engine.impl.jobexecutor.JobExecutor;
import org.camunda.bpm.engine.impl.persistence.entity.HistoricIncidentEntity;
import org.camunda.bpm.engine.impl.persistence.entity.HistoricIncidentManager;
import org.camunda.bpm.engine.impl.persistence.entity.JobEntity;
import org.camunda.bpm.engine.impl.persistence.entity.JobManager;
import org.camunda.bpm.engine.impl.persistence.entity.MessageEntity;
import org.camunda.bpm.engine.impl.test.PluggableProcessEngineTestCase;
import org.camunda.bpm.engine.impl.util.ClockUtil;
import org.camunda.bpm.engine.management.JobDefinition;
import org.camunda.bpm.engine.management.TableMetaData;
import org.camunda.bpm.engine.management.TablePage;
import org.camunda.bpm.engine.runtime.Incident;
import org.camunda.bpm.engine.runtime.Job;
import org.camunda.bpm.engine.runtime.JobQuery;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.task.Task;
import org.camunda.bpm.engine.test.Deployment;
import org.junit.Assert;

/**
 * @author Frederik Heremans
 * @author Falko Menge
 * @author Saeid Mizaei
 * @author Joram Barrez
 */
public class ManagementServiceTest extends PluggableProcessEngineTestCase {

  public void testGetMetaDataForUnexistingTable() {
    TableMetaData metaData = managementService.getTableMetaData("unexistingtable");
    assertNull(metaData);
  }

  public void testGetMetaDataNullTableName() {
    try {
      managementService.getTableMetaData(null);
      fail("ProcessEngineException expected");
    } catch (ProcessEngineException re) {
      assertTextPresent("tableName is null", re.getMessage());
    }
  }

  public void testExecuteJobNullJobId() {
    try {
      managementService.executeJob(null);
      fail("ProcessEngineException expected");
    } catch (ProcessEngineException re) {
      assertTextPresent("jobId is null", re.getMessage());
    }
  }

  public void testExecuteJobUnexistingJob() {
    try {
      managementService.executeJob("unexistingjob");
      fail("ProcessEngineException expected");
    } catch (ProcessEngineException ae) {
      assertTextPresent("No job found with id", ae.getMessage());
    }
  }

  @Deployment
  public void testGetJobExceptionStacktrace() {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("exceptionInJobExecution");

    // The execution is waiting in the first usertask. This contains a boundry
    // timer event which we will execute manual for testing purposes.
    Job timerJob = managementService.createJobQuery()
      .processInstanceId(processInstance.getId())
      .singleResult();

    assertNotNull("No job found for process instance", timerJob);

    try {
      managementService.executeJob(timerJob.getId());
      fail("RuntimeException from within the script task expected");
    } catch(RuntimeException re) {
      assertTextPresent("This is an exception thrown from scriptTask", re.getMessage());
    }

    // Fetch the task to see that the exception that occurred is persisted
    timerJob = managementService.createJobQuery()
    .processInstanceId(processInstance.getId())
    .singleResult();

    Assert.assertNotNull(timerJob);
    Assert.assertNotNull(timerJob.getExceptionMessage());
    assertTextPresent("This is an exception thrown from scriptTask", timerJob.getExceptionMessage());

    // Get the full stacktrace using the managementService
    String exceptionStack = managementService.getJobExceptionStacktrace(timerJob.getId());
    Assert.assertNotNull(exceptionStack);
    assertTextPresent("This is an exception thrown from scriptTask", exceptionStack);
  }

  public void testgetJobExceptionStacktraceUnexistingJobId() {
    try {
      managementService.getJobExceptionStacktrace("unexistingjob");
      fail("ProcessEngineException expected");
    } catch (ProcessEngineException re) {
      assertTextPresent("No job found with id unexistingjob", re.getMessage());
    }
  }

  public void testgetJobExceptionStacktraceNullJobId() {
    try {
      managementService.getJobExceptionStacktrace(null);
      fail("ProcessEngineException expected");
    } catch (ProcessEngineException re) {
      assertTextPresent("jobId is null", re.getMessage());
    }
  }

  @Deployment(resources = {"org/camunda/bpm/engine/test/api/mgmt/ManagementServiceTest.testGetJobExceptionStacktrace.bpmn20.xml"})
  public void testSetJobRetries() {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("exceptionInJobExecution");

    // The execution is waiting in the first usertask. This contains a boundary
    // timer event.
    Job timerJob = managementService.createJobQuery()
      .processInstanceId(processInstance.getId())
      .singleResult();

    assertNotNull("No job found for process instance", timerJob);
    assertEquals(JobEntity.DEFAULT_RETRIES, timerJob.getRetries());

    managementService.setJobRetries(timerJob.getId(), 5);

    timerJob = managementService.createJobQuery()
      .processInstanceId(processInstance.getId())
      .singleResult();
    assertEquals(5, timerJob.getRetries());
  }

  @Deployment(resources = {"org/camunda/bpm/engine/test/api/mgmt/ManagementServiceTest.testGetJobExceptionStacktrace.bpmn20.xml"})
  public void testSetJobRetriesNullCreatesIncident() {

    // initially there is no incident
    assertEquals(0, runtimeService.createIncidentQuery().count());

    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("exceptionInJobExecution");

    // The execution is waiting in the first usertask. This contains a boundary
    // timer event.
    Job timerJob = managementService.createJobQuery()
      .processInstanceId(processInstance.getId())
      .singleResult();

    assertNotNull("No job found for process instance", timerJob);
    assertEquals(JobEntity.DEFAULT_RETRIES, timerJob.getRetries());

    managementService.setJobRetries(timerJob.getId(), 0);

    timerJob = managementService.createJobQuery()
      .processInstanceId(processInstance.getId())
      .singleResult();
    assertEquals(0, timerJob.getRetries());

    assertEquals(1, runtimeService.createIncidentQuery().count());

  }

  public void testSetJobRetriesUnexistingJobId() {
    try {
      managementService.setJobRetries("unexistingjob", 5);
      fail("ProcessEngineException expected");
    } catch (ProcessEngineException re) {
      assertTextPresent("No job found with id 'unexistingjob'.", re.getMessage());
    }
  }

  public void testSetJobRetriesEmptyJobId() {
    try {
      managementService.setJobRetries("", 5);
      fail("ProcessEngineException expected");
    } catch (ProcessEngineException re) {
      assertTextPresent("Either job definition id or job id has to be provided as parameter.", re.getMessage());
    }
  }

  public void testSetJobRetriesJobIdNull() {
    try {
      managementService.setJobRetries(null, 5);
      fail("ProcessEngineException expected");
    } catch (ProcessEngineException re) {
      assertTextPresent("Either job definition id or job id has to be provided as parameter.", re.getMessage());
    }
  }

  public void testSetJobRetriesNegativeNumberOfRetries() {
    try {
      managementService.setJobRetries("unexistingjob", -1);
      fail("ProcessEngineException expected");
    } catch (ProcessEngineException re) {
      assertTextPresent("The number of job retries must be a non-negative Integer, but '-1' has been provided.", re.getMessage());
    }
  }

  @Deployment(resources = {"org/camunda/bpm/engine/test/api/mgmt/ManagementServiceTest.testGetJobExceptionStacktrace.bpmn20.xml"})
  public void testSetJobRetriesByJobDefinitionId() {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("exceptionInJobExecution");
    executeAvailableJobs();

    JobQuery query = managementService.createJobQuery()
        .processInstanceId(processInstance.getId());

    JobDefinition jobDefinition = managementService
        .createJobDefinitionQuery()
        .singleResult();

    Job timerJob = query.singleResult();

    assertNotNull("No job found for process instance", timerJob);
    assertEquals(0, timerJob.getRetries());

    managementService.setJobRetriesByJobDefinitionId(jobDefinition.getId(), 5);

    timerJob = query.singleResult();
    assertEquals(5, timerJob.getRetries());
  }

  public void testSetJobRetriesByJobDefinitionIdEmptyJobDefinitionId() {
    try {
      managementService.setJobRetriesByJobDefinitionId("", 5);
      fail("ProcessEngineException expected");
    } catch (ProcessEngineException re) {
      assertTextPresent("Either job definition id or job id has to be provided as parameter.", re.getMessage());
    }
  }

  public void testSetJobRetriesByJobDefinitionIdNull() {
    try {
      managementService.setJobRetriesByJobDefinitionId(null, 5);
      fail("ProcessEngineException expected");
    } catch (ProcessEngineException re) {
      assertTextPresent("Either job definition id or job id has to be provided as parameter.", re.getMessage());
    }
  }

  public void testSetJobRetriesByJobDefinitionIdNegativeNumberOfRetries() {
    try {
      managementService.setJobRetries("unexistingjob", -1);
      fail("ProcessEngineException expected");
    } catch (ProcessEngineException re) {
      assertTextPresent("The number of job retries must be a non-negative Integer, but '-1' has been provided.", re.getMessage());
    }
  }

  public void testSetJobRetriesUnlocksInconsistentJob() {
    // case 1
    // given an inconsistent job that is never again picked up by a job executor
    createJob(0, "owner", ClockUtil.getCurrentTime());

    // when the job retries are reset
    JobEntity job = (JobEntity) managementService.createJobQuery().singleResult();
    managementService.setJobRetries(job.getId(), 3);

    // then the job can be picked up again
    job = (JobEntity) managementService.createJobQuery().singleResult();
    assertNotNull(job);
    assertNull(job.getLockOwner());
    assertNull(job.getLockExpirationTime());
    assertEquals(3, job.getRetries());

    deleteJobAndIncidents(job);

    // case 2
    // given an inconsistent job that is never again picked up by a job executor
    createJob(2, "owner", null);

    // when the job retries are reset
    job = (JobEntity) managementService.createJobQuery().singleResult();
    managementService.setJobRetries(job.getId(), 3);

    // then the job can be picked up again
    job = (JobEntity) managementService.createJobQuery().singleResult();
    assertNotNull(job);
    assertNull(job.getLockOwner());
    assertNull(job.getLockExpirationTime());
    assertEquals(3, job.getRetries());

    deleteJobAndIncidents(job);

    // case 3
    // given a consistent job
    createJob(2, "owner", ClockUtil.getCurrentTime());

    // when the job retries are reset
    job = (JobEntity) managementService.createJobQuery().singleResult();
    managementService.setJobRetries(job.getId(), 3);

    // then the lock owner and expiration should not change
    job = (JobEntity) managementService.createJobQuery().singleResult();
    assertNotNull(job);
    assertNotNull(job.getLockOwner());
    assertNotNull(job.getLockExpirationTime());
    assertEquals(3, job.getRetries());

    deleteJobAndIncidents(job);
  }

  protected void createJob(final int retries, final String owner, final Date lockExpirationTime) {
    CommandExecutor commandExecutor = processEngineConfiguration.getCommandExecutorTxRequired();
    commandExecutor.execute(new Command<Void>() {
      public Void execute(CommandContext commandContext) {
        JobManager jobManager = commandContext.getJobManager();
        MessageEntity job = new MessageEntity();
        job.setJobHandlerType("any");
        job.setLockOwner(owner);
        job.setLockExpirationTime(lockExpirationTime);
        job.setRetries(retries);

        jobManager.send(job);
        return null;
      }
    });
  }

  @Deployment(resources = {"org/camunda/bpm/engine/test/api/mgmt/ManagementServiceTest.testGetJobExceptionStacktrace.bpmn20.xml"})
  public void testSetJobRetriesByDefinitionUnlocksInconsistentJobs() {
    // given a job definition
    final JobDefinition jobDefinition = managementService.createJobDefinitionQuery().singleResult();

    // and an inconsistent job that is never again picked up by a job executor
    CommandExecutor commandExecutor = processEngineConfiguration.getCommandExecutorTxRequired();
    commandExecutor.execute(new Command<Void>() {
      public Void execute(CommandContext commandContext) {
        JobManager jobManager = commandContext.getJobManager();
        MessageEntity job = new MessageEntity();
        job.setJobDefinitionId(jobDefinition.getId());
        job.setJobHandlerType("any");
        job.setLockOwner("owner");
        job.setLockExpirationTime(ClockUtil.getCurrentTime());
        job.setRetries(0);

        jobManager.send(job);
        return null;
      }
    });

    // when the job retries are reset
    managementService.setJobRetriesByJobDefinitionId(jobDefinition.getId(), 3);

    // then the job can be picked up again
    JobEntity job = (JobEntity) managementService.createJobQuery().singleResult();
    assertNotNull(job);
    assertNull(job.getLockOwner());
    assertNull(job.getLockExpirationTime());
    assertEquals(3, job.getRetries());

    deleteJobAndIncidents(job);
  }

  protected void deleteJobAndIncidents(final Job job) {
    final List<HistoricIncident> incidents =
        historyService.createHistoricIncidentQuery()
        .incidentType(Incident.FAILED_JOB_HANDLER_TYPE).list();

    CommandExecutor commandExecutor = processEngineConfiguration.getCommandExecutorTxRequired();
    commandExecutor.execute(new Command<Void>() {
      public Void execute(CommandContext commandContext) {
        ((JobEntity) job).delete();

        HistoricIncidentManager historicIncidentManager = commandContext.getHistoricIncidentManager();
        for (HistoricIncident incident : incidents) {
          HistoricIncidentEntity incidentEntity = (HistoricIncidentEntity) incident;
          historicIncidentManager.delete(incidentEntity);
        }

        commandContext.getHistoricJobLogManager().deleteHistoricJobLogByJobId(job.getId());
        return null;
      }
    });
  }

  public void testDeleteJobNullJobId() {
    try {
      managementService.deleteJob(null);
      fail("ProcessEngineException expected");
    } catch (ProcessEngineException re) {
      assertTextPresent("jobId is null", re.getMessage());
    }
  }

  public void testDeleteJobUnexistingJob() {
    try {
      managementService.deleteJob("unexistingjob");
      fail("ProcessEngineException expected");
    } catch (ProcessEngineException ae) {
      assertTextPresent("No job found with id", ae.getMessage());
    }
  }

  @Deployment(resources = { "org/camunda/bpm/engine/test/api/mgmt/timerOnTask.bpmn20.xml" })
  public void testDeleteJobDeletion() {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("timerOnTask");
    Job timerJob = managementService.createJobQuery().processInstanceId(processInstance.getId()).singleResult();

    assertNotNull("Task timer should be there", timerJob);
    managementService.deleteJob(timerJob.getId());

    timerJob = managementService.createJobQuery().processInstanceId(processInstance.getId()).singleResult();
    assertNull("There should be no job now. It was deleted", timerJob);
  }

  @Deployment(resources = { "org/camunda/bpm/engine/test/api/mgmt/timerOnTask.bpmn20.xml" })
  public void testDeleteJobThatWasAlreadyAcquired() {
    ClockUtil.setCurrentTime(new Date());

    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("timerOnTask");
    Job timerJob = managementService.createJobQuery().processInstanceId(processInstance.getId()).singleResult();

    // We need to move time at least one hour to make the timer executable
    ClockUtil.setCurrentTime(new Date(ClockUtil.getCurrentTime().getTime() + 7200000L));

    // Acquire job by running the acquire command manually
    ProcessEngineImpl processEngineImpl = (ProcessEngineImpl) processEngine;
    JobExecutor jobExecutor = processEngineImpl.getProcessEngineConfiguration().getJobExecutor();
    AcquireJobsCmd acquireJobsCmd = new AcquireJobsCmd(jobExecutor);
    CommandExecutor commandExecutor = processEngineImpl.getProcessEngineConfiguration().getCommandExecutorTxRequired();
    commandExecutor.execute(acquireJobsCmd);

    // Try to delete the job. This should fail.
    try {
      managementService.deleteJob(timerJob.getId());
      fail();
    } catch (ProcessEngineException e) {
      // Exception is expected
    }

    // Clean up
    managementService.executeJob(timerJob.getId());
  }

  @Deployment(resources = {"org/camunda/bpm/engine/test/api/mgmt/ManagementServiceTest.testGetJobExceptionStacktrace.bpmn20.xml"})
  public void testSetJobDuedate() {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("exceptionInJobExecution");

    // The execution is waiting in the first usertask. This contains a boundary
    // timer event.
    Job timerJob = managementService.createJobQuery()
      .processInstanceId(processInstance.getId())
      .singleResult();

    assertNotNull("No job found for process instance", timerJob);
    assertNotNull(timerJob.getDuedate());

    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());
    cal.add(Calendar.DATE, 3); // add 3 days on the actual date
    managementService.setJobDuedate(timerJob.getId(), cal.getTime());

    Job newTimerJob = managementService.createJobQuery()
      .processInstanceId(processInstance.getId())
      .singleResult();

    // normalize date for mysql dropping fractional seconds in time values
    int SECOND = 1000;
    assertEquals((cal.getTime().getTime() / SECOND) * SECOND,
                 (newTimerJob.getDuedate().getTime() / SECOND) * SECOND);
  }

  @Deployment(resources = {"org/camunda/bpm/engine/test/api/mgmt/ManagementServiceTest.testGetJobExceptionStacktrace.bpmn20.xml"})
  public void testSetJobDuedateDateNull() {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("exceptionInJobExecution");

    // The execution is waiting in the first usertask. This contains a boundary
    // timer event.
    Job timerJob = managementService.createJobQuery()
      .processInstanceId(processInstance.getId())
      .singleResult();

    assertNotNull("No job found for process instance", timerJob);
    assertNotNull(timerJob.getDuedate());

    managementService.setJobDuedate(timerJob.getId(), null);

    timerJob = managementService.createJobQuery()
      .processInstanceId(processInstance.getId())
      .singleResult();

    assertNull(timerJob.getDuedate());
  }

  public void testSetJobDuedateJobIdNull() {
    try {
      managementService.setJobDuedate(null, new Date());
      fail("ProcessEngineException expected");
    } catch (ProcessEngineException re) {
      assertTextPresent("The job id is mandatory, but 'null' has been provided.", re.getMessage());
    }
  }

  public void testSetJobDuedateEmptyJobId() {
    try {
      managementService.setJobDuedate("", new Date());
      fail("ProcessEngineException expected");
    } catch (ProcessEngineException re) {
      assertTextPresent("The job id is mandatory, but '' has been provided.", re.getMessage());
    }
  }

  public void testSetJobDuedateUnexistingJobId() {
    try {
      managementService.setJobDuedate("unexistingjob", new Date());
      fail("ProcessEngineException expected");
    } catch (ProcessEngineException re) {
      assertTextPresent("No job found with id 'unexistingjob'.", re.getMessage());
    }
  }

  public void testGetProperties() {
    Map<String, String> properties = managementService.getProperties();
    assertNotNull(properties);
    assertFalse(properties.isEmpty());
  }

  public void  testSetProperty() {
    final String name = "testProp";
    final String value = "testValue";
    managementService.setProperty(name, value);

    Map<String, String> properties = managementService.getProperties();
    assertTrue(properties.containsKey(name));
    String storedValue = properties.get(name);
    assertEquals(value, storedValue);

    managementService.deleteProperty(name);
  }

  public void  testDeleteProperty() {
    final String name = "testProp";
    final String value = "testValue";
    managementService.setProperty(name, value);

    Map<String, String> properties = managementService.getProperties();
    assertTrue(properties.containsKey(name));
    String storedValue = properties.get(name);
    assertEquals(value, storedValue);

    managementService.deleteProperty(name);
    properties = managementService.getProperties();
    assertFalse(properties.containsKey(name));

  }

  public void  testDeleteNonexistingProperty() {

    managementService.deleteProperty("non existing");

  }

  public void testGetHistoryLevel() {
    int historyLevel = managementService.getHistoryLevel();
    assertEquals(processEngineConfiguration.getHistoryLevel().getId(), historyLevel);
  }

  @Deployment(resources = "org/camunda/bpm/engine/test/api/mgmt/asyncTaskProcess.bpmn20.xml")
  public void testSetJobPriority() {
    // given
    runtimeService
      .createProcessInstanceByKey("asyncTaskProcess")
      .startBeforeActivity("task")
      .execute();

    Job job = managementService.createJobQuery().singleResult();

    // when
    managementService.setJobPriority(job.getId(), 42);

    // then
    job = managementService.createJobQuery().singleResult();

    assertEquals(42, job.getPriority());
  }

  public void testSetJobPriorityForNonExistingJob() {
    try {
      managementService.setJobPriority("nonExistingJob", 42);
      fail("should not succeed");
    } catch (NotFoundException e) {
      assertTextPresentIgnoreCase("No job found with id 'nonExistingJob'", e.getMessage());
    }
  }

  public void testSetJobPriorityForNullJob() {
    try {
      managementService.setJobPriority(null, 42);
      fail("should not succeed");
    } catch (NullValueException e) {
      assertTextPresentIgnoreCase("Job id must not be null", e.getMessage());
    }
  }

  @Deployment(resources = "org/camunda/bpm/engine/test/api/mgmt/asyncTaskProcess.bpmn20.xml")
  public void testSetJobPriorityToExtremeValues() {
    runtimeService
      .createProcessInstanceByKey("asyncTaskProcess")
      .startBeforeActivity("task")
      .execute();

    Job job = managementService.createJobQuery().singleResult();

    // it is possible to set the max integer value
    managementService.setJobPriority(job.getId(), Long.MAX_VALUE);
    job = managementService.createJobQuery().singleResult();
    assertEquals(Long.MAX_VALUE, job.getPriority());

    // it is possible to set the min integer value
    managementService.setJobPriority(job.getId(), Long.MIN_VALUE + 1); // +1 for informix
    job = managementService.createJobQuery().singleResult();
    assertEquals(Long.MIN_VALUE + 1, job.getPriority());
  }

  public void testTableCount() {
    Map<String, Long> tableCount = managementService.getTableCount();

    String tablePrefix = processEngineConfiguration.getDatabaseTablePrefix();
    assertEquals(new Long(5), tableCount.get(tablePrefix+"ACT_GE_PROPERTY"));
    assertEquals(new Long(0), tableCount.get(tablePrefix+"ACT_GE_BYTEARRAY"));
    assertEquals(new Long(0), tableCount.get(tablePrefix+"ACT_RE_DEPLOYMENT"));
    assertEquals(new Long(0), tableCount.get(tablePrefix+"ACT_RU_EXECUTION"));
    assertEquals(new Long(0), tableCount.get(tablePrefix+"ACT_ID_GROUP"));
    assertEquals(new Long(0), tableCount.get(tablePrefix+"ACT_ID_MEMBERSHIP"));
    assertEquals(new Long(0), tableCount.get(tablePrefix+"ACT_ID_USER"));
    assertEquals(new Long(0), tableCount.get(tablePrefix+"ACT_RE_PROCDEF"));
    assertEquals(new Long(0), tableCount.get(tablePrefix+"ACT_RU_TASK"));
    assertEquals(new Long(0), tableCount.get(tablePrefix+"ACT_RU_IDENTITYLINK"));
  }

  public void testGetTableMetaData() {

    String tablePrefix = processEngineConfiguration.getDatabaseTablePrefix();

    TableMetaData tableMetaData = managementService.getTableMetaData(tablePrefix+"ACT_RU_TASK");
    assertEquals(tableMetaData.getColumnNames().size(), tableMetaData.getColumnTypes().size());
    assertEquals(20, tableMetaData.getColumnNames().size());

    int assigneeIndex = tableMetaData.getColumnNames().indexOf("ASSIGNEE_");
    int createTimeIndex = tableMetaData.getColumnNames().indexOf("CREATE_TIME_");

    assertTrue(assigneeIndex >= 0);
    assertTrue(createTimeIndex >= 0);

    assertOneOf(new String [] {"VARCHAR", "NVARCHAR2", "nvarchar", "NVARCHAR"}, tableMetaData.getColumnTypes().get(assigneeIndex));
    assertOneOf(new String [] {"TIMESTAMP", "TIMESTAMP(6)", "datetime", "DATETIME", "DATETIME2"}, tableMetaData.getColumnTypes().get(createTimeIndex));
  }

  private void assertOneOf(String[] possibleValues, String currentValue) {
    for(String value : possibleValues) {
      if(currentValue.equals(value)) {
        return;
      }
    }
    fail("Value '" + currentValue + "' should be one of: " + Arrays.deepToString(possibleValues));
  }

  public void testGetTablePage() {
    String tablePrefix = processEngineConfiguration.getDatabaseTablePrefix();
    List<String> taskIds = generateDummyTasks(20);

    TablePage tablePage = managementService.createTablePageQuery()
      .tableName(tablePrefix+"ACT_RU_TASK")
      .listPage(0, 5);

    assertEquals(0, tablePage.getFirstResult());
    assertEquals(5, tablePage.getSize());
    assertEquals(5, tablePage.getRows().size());
    assertEquals(20, tablePage.getTotal());

    tablePage = managementService.createTablePageQuery()
      .tableName(tablePrefix+"ACT_RU_TASK")
      .listPage(14, 10);

    assertEquals(14, tablePage.getFirstResult());
    assertEquals(6, tablePage.getSize());
    assertEquals(6, tablePage.getRows().size());
    assertEquals(20, tablePage.getTotal());

    taskService.deleteTasks(taskIds, true);
  }

  public void testGetSortedTablePage() {
    String tablePrefix = processEngineConfiguration.getDatabaseTablePrefix();
    List<String> taskIds = generateDummyTasks(15);

    // With an ascending sort
    TablePage tablePage = managementService.createTablePageQuery()
      .tableName(tablePrefix+"ACT_RU_TASK")
      .orderAsc("NAME_")
      .listPage(1, 7);
    String[] expectedTaskNames = new String[] {"B", "C", "D", "E", "F", "G", "H"};
    verifyTaskNames(expectedTaskNames, tablePage.getRows());

    // With a descending sort
    tablePage = managementService.createTablePageQuery()
      .tableName(tablePrefix+"ACT_RU_TASK")
      .orderDesc("NAME_")
      .listPage(6, 8);
    expectedTaskNames = new String[] {"I", "H", "G", "F", "E", "D", "C", "B"} ;
    verifyTaskNames(expectedTaskNames, tablePage.getRows());

    taskService.deleteTasks(taskIds, true);
  }

  private void verifyTaskNames(String[] expectedTaskNames, List<Map<String, Object>> rowData) {
    assertEquals(expectedTaskNames.length, rowData.size());
    String columnKey = "NAME_";

    // mybatis will return the correct case for postgres table columns from version 3.0.6 on
    if (processEngineConfiguration.getDatabaseType().equals("postgres")) {
      columnKey = "name_";
    }

    for (int i=0; i < expectedTaskNames.length; i++) {
      assertEquals(expectedTaskNames[i], rowData.get(i).get(columnKey));
    }
  }

  private List<String> generateDummyTasks(int nrOfTasks) {
    ArrayList<String> taskIds = new ArrayList<String>();
    for (int i = 0; i < nrOfTasks; i++) {
      Task task = taskService.newTask();
      task.setName(((char)('A' + i)) + "");
      taskService.saveTask(task);
      taskIds.add(task.getId());
    }
    return taskIds;
  }

}


text:
import React from 'react';
import { cleanup, fireEvent, render, findAllByTestId, waitForElement } from '@testing-library/react';
import Actions from '../../src/back-office/components/Actions';

describe('Click some actions', () => {
  // automatically unmount and cleanup DOM after the test is finished.
  afterEach(cleanup);

  it('calls you back', async () => {
    const callback = jest.fn();

    const { container } = render(
      <Actions onAction={callback}/>
    );

    const data = await waitForElement(() => findAllByTestId(container, 'actions'));

    (await data).forEach(e =>  fireEvent.click(e));
    const calls = callback.mock.calls;

    expect(calls.length).toEqual(3);
    expect(calls[0][0]).toEqual('info');
    expect(calls[1][0]).toEqual('edit');
    expect(calls[2][0]).toEqual('delete');
  });
});

redpajama_set_name: RedPajamaGithub


text:
from __future__ import absolute_import, unicode_literals

import logging
import string

logger = logging.getLogger(__name__)

try:
    import dbus
except ImportError:
    dbus = None

_AVAHI_IF_UNSPEC = -1
_AVAHI_PROTO_UNSPEC = -1
_AVAHI_PUBLISHFLAGS_NONE = 0

def _is_loopback_address(host):
    return (
        host.startswith('127.') or
        host.startswith('::ffff:127.') or
        host == '::1')

def _convert_text_list_to_dbus_format(text_list):
    array = dbus.Array(signature='ay')
    for text in text_list:
        array.append([dbus.Byte(ord(c)) for c in text])
    return array

class Zeroconf(object):

    """Publish a network service with Zeroconf.

    Currently, this only works on Linux using Avahi via D-Bus.

    :param str name: human readable name of the service, e.g. 'MPD on neptune'
    :param str stype: service type, e.g. '_mpd._tcp'
    :param int port: TCP port of the service, e.g. 6600
    :param str domain: local network domain name, defaults to ''
    :param str host: interface to advertise the service on, defaults to ''
    :param text: extra information depending on ``stype``, defaults to empty
        list
    :type text: list of str
    """

    def __init__(self, name, stype, port, domain='', host='', text=None):
        self.stype = stype
        self.port = port
        self.domain = domain
        self.host = host
        self.text = text or []

        self.bus = None
        self.server = None
        self.group = None
        try:
            self.bus = dbus.SystemBus()
            self.server = dbus.Interface(
                self.bus.get_object('org.freedesktop.Avahi', '/'),
                'org.freedesktop.Avahi.Server')
        except dbus.exceptions.DBusException as e:
            logger.debug('%s: Server failed: %s', self, e)

        self.display_hostname = '%s' % self.server.GetHostName()
        self.name = string.Template(name).safe_substitute(
            hostname=self.display_hostname, port=port)

    def __str__(self):
        return 'Zeroconf service "%s" (%s at [%s]:%d)' % (
            self.name, self.stype, self.host, self.port)

    def publish(self):
        """Publish the service.

        Call when your service starts.
        """

        if _is_loopback_address(self.host):
            logger.debug(
                '%s: Publish on loopback interface is not supported.', self)
            return False

        if not dbus:
            logger.debug('%s: dbus not installed; publish failed.', self)
            return False

        if not self.bus:
            logger.debug('%s: Bus not available; publish failed.', self)
            return False

        if not self.server:
            logger.debug('%s: Server not available; publish failed.', self)
            return False

        try:
            if not self.bus.name_has_owner('org.freedesktop.Avahi'):
                logger.debug(
                    '%s: Avahi service not running; publish failed.', self)
                return False

            self.group = dbus.Interface(
                self.bus.get_object(
                    'org.freedesktop.Avahi', self.server.EntryGroupNew()),
                'org.freedesktop.Avahi.EntryGroup')

            self.group.AddService(
                _AVAHI_IF_UNSPEC, _AVAHI_PROTO_UNSPEC,
                dbus.UInt32(_AVAHI_PUBLISHFLAGS_NONE),
                self.name, self.stype,
                self.domain, self.host, dbus.UInt16(self.port),
                _convert_text_list_to_dbus_format(self.text))

            self.group.Commit()
            logger.debug('%s: Published', self)
            return True
        except dbus.exceptions.DBusException as e:
            logger.debug('%s: Publish failed: %s', self, e)
            return False

    def unpublish(self):
        """Unpublish the service.

        Call when your service shuts down.
        """

        if self.group:
            try:
                self.group.Reset()
                logger.debug('%s: Unpublished', self)
            except dbus.exceptions.DBusException as e:
                logger.debug('%s: Unpublish failed: %s', self, e)
            finally:
                self.group = None


text:
layout: project
title:  " SEO & SEM"
date:   2015-05-02 00:00:00
developer: Marcelo
categories:
- projetos
tags:
- performance
- front-end
img: seo01.jpg
thumb: project_seo.jpg
carousel:
- seo01.jpg
- seo02.jpg
client: Corp.
website: http://www.org
priority: 0.6
description: If you're not already aware, on average search engine users overwhelmingly click on the organic results (free results) on Google and Bing, before they click on a sponsor paid ad listing, by a margin of 94 percent to 6 percent.
---
####SEO & SEM
If you're not already aware, on average search engine users overwhelmingly click on the organic results (free results) on Google and Bing, before they click on a sponsor paid ad listing, by a margin of 94 percent to 6 percent.

During the last 15 years we have worked with hundreds of Brazilian and international companies in the area of web site promotion and search engine optimisation (SEO) from our base in São Paulo. We guarantee that our web promotion services will deliver more enquires and customers to your site. Most consumers find web sites by typing a keyword phrase into one of the major search engines. If your site is correctly optimised for the appropriate keywords it will appear near the top of the search results. The higher your site's ranking, the more visitors it should receive. Better still, because these visitors chose your keywords themselves, you know they are ideal prospects for your business.

To rank different web sites, each search engine uses a different algorithm, looking at different components of your web site including document title, meta tags, keywords in the URL, keywords in the text, headings in the text, number of pages, and external links into the site. Many web design and media agency companies will use software that promotes your web site, this is NOT always beneficial and can negatively affect your rankings. We always manually optimise your site for relevant phrases and then submit your site to the top search engines and directories.

####Web Promotion and SEO Quality Guarantee

As a certified web promotion company, we have made customer satisfaction a fundamental priority. Since Search Engine Optimisation is a rapidly evolving, technically complex and often misunderstood field we have taken the initiative of developing the Search Engine Optimisation Quality Guarantee. We explicitly guarantee the following standards of practice on all search engine optimisation projects that we undertake.

We optimise web sites for relevant keywords only. We do not use 'cloaking techniques' that show search engines and web users different content.

We monitor the effectiveness of our optimisation services and provide all clients with a follow up report detailing their site's rankings with the major search engines.

Our primary focus is to improve the search experience for web users by helping search engines find relevant results. Search engines change the algorithms they use to rank web sites frequently and it is not possible to accurately predict future rankings and traffic.

However, we use techniques that we know work on standard sites and anticipate a significant increase in qualified site traffic.

We are not just a search engine registration service. We offer a pin-point target marketing programme that:

Works with you to identify your most relevant keyword phrases.Manually optimises your web site's key documents using our proven techniques.Offers ongoing web promotion strategies.Guarantees your web rankings will improve.Guarantees your web site's traffic will increase.
Search engine optimisation is a crucial part of the marketing mix but many websites are not designed to be search engine friendly and are often missing key components that are important for gaining good rankings.

####E-commerce SEO

As a total solutions business our aim is to help our customers generate more leads, revenue and profitability from their online ecommerce website.

Using our established and tried services and strategies, these can include:
- SEO = Search Engine Optimization
- PPC = Pay Per Click Management
- Social Media Consulting and Marketing
- ECO = Ecommerce Conversion Optimization
- Ecommerce Website Design

Our SEO campaigns include:
- Keyword Research and Analytical Review
- SEO Analysis and DSO Recommendations
- Site Content Optimization
- Natural Link Building
- Analytics and Reporting


text:
1. [Installation](installation.md)
1. [Configuration](configuration.md)
1. [Troubleshooting](troubleshooting.md)

## What is the link for login end user?

There are two ways to trigger user authentication.
- When an end user requests a resource who is behind a firewall, he will be automatically redirected to the
OP's login page.
- Accessing the route configured for `login_check`.

## How to display a logout link?

The name of the logout route is `_oic_rp_logout`. You can use it in your Twig template like below:

```twig
<a href="{{ path('_oic_rp_logout') }}">Logout</a>
```

If you have specified a logout endpoint, the logout mechanism will proceed of the logout the user on the endpoint.

## Not yet implemented

### TODO
 - Add re-authentication mechanise

### Client Prepares Authentication Request

http://openid.net/specs/openid-connect-basic-1_0.html#AuthenticationRequest

This options parameter need to be implemented
 - claims_locales
 - id_token_hint
 - login_hint
 - acr_values

### ID Token Validation

http://openid.net/specs/openid-connect-basic-1_0.html#IDTokenValidation

The point 7 is not implemented.
> If the acr Claim was requested, the Client SHOULD check that the asserted Claim
> Value is appropriate. The meaning and processing of acr Claim Values is out of
> scope for this document.


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <corners android:radius="4dp" />
    <solid android:color="@color/black" />
    <stroke
        android:width="1px"
        android:color="@color/black"/>

</shape>


text:
import * as apid from '../../../api';
import RecordedTag from '../../db/entities/RecordedTag';

export default interface IRecordedTagDB {
    restore(items: RecordedTag[]): Promise<void>;
    insertOnce(tag: RecordedTag): Promise<apid.RecordedTagId>;
    updateOnce(tagId: apid.RecordedTagId, name: string, color: string): Promise<void>;
    setRelation(tagId: apid.RecordedTagId, recordedId: apid.RecordedId): Promise<void>;
    deleteRelation(tagId: apid.RecordedTagId, recordedId: apid.RecordedId): Promise<void>;
    deleteAllRelation(recordedId: apid.RecordedId): Promise<void>;
    deleteOnce(tagId: apid.RecordedTagId): Promise<void>;
    findId(tagId: apid.RecordedTagId): Promise<RecordedTag | null>;
    findAll(option: apid.GetRecordedTagOption): Promise<[RecordedTag[], number]>;
}


text: export { default } from 'shared/components/cluster-welcome/component';


text:
package com.google.cloud.pubsub.client.demos.appengine.servlet;

import com.google.api.services.pubsub.Pubsub;
import com.google.api.services.pubsub.model.PublishRequest;
import com.google.api.services.pubsub.model.PubsubMessage;
import com.google.cloud.pubsub.client.demos.appengine.util.PubsubUtils;
import com.google.common.collect.ImmutableList;

import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Publishes messages to the application topic.
 */
public class SendMessageServlet extends HttpServlet {

    @Override
    public final void doPost(final HttpServletRequest req,
                             final HttpServletResponse resp)
            throws IOException {
        Pubsub client = PubsubUtils.getClient();
        String message = req.getParameter("message");
        if (!"".equals(message)) {
            String fullTopicName = String.format("projects/%s/topics/%s",
                    PubsubUtils.getProjectId(),
                    PubsubUtils.getAppTopicName());
            PubsubMessage pubsubMessage = new PubsubMessage();
            pubsubMessage.encodeData(message.getBytes("UTF-8"));
            PublishRequest publishRequest = new PublishRequest();
            publishRequest.setMessages(ImmutableList.of(pubsubMessage));

            client.projects().topics()
                    .publish(fullTopicName, publishRequest)
                    .execute();
        }
        resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
        resp.getWriter().close();
    }
}


text:
#include "lb_web_media_player_delegate.h"

#include "third_party/WebKit/Source/WebKit/chromium/public/WebMediaPlayer.h"

#include "lb_graphics.h"
#include "lb_web_view_host.h"

namespace {

MessageLoop* GetWebKitMessageLoop() {
  DCHECK(LBWebViewHost::Get());
  return LBWebViewHost::Get()->webkit_message_loop();
}

}  // namespace

namespace webkit_media {

LBWebMediaPlayerDelegate* LBWebMediaPlayerDelegate::instance_ = NULL;

LBWebMediaPlayerDelegate::LBWebMediaPlayerDelegate() {
}

// static
LBWebMediaPlayerDelegate* LBWebMediaPlayerDelegate::Instance() {
  return instance_;
}

// static
base::WeakPtr<LBWebMediaPlayerDelegate>
     LBWebMediaPlayerDelegate::WeakInstance() {
  return instance_->AsWeakPtr();
}

// static
void LBWebMediaPlayerDelegate::Initialize() {
  instance_ = new LBWebMediaPlayerDelegate();
}

// static
void LBWebMediaPlayerDelegate::Terminate() {
  delete instance_;
  instance_ = NULL;
}

void LBWebMediaPlayerDelegate::DidPlay(WebKit::WebMediaPlayer* player) {
  DCHECK_EQ(MessageLoop::current(), GetWebKitMessageLoop());

  // add or update player map with this instance of the player
  player_map_[player] = true;
  SetDimmingState();
}

void LBWebMediaPlayerDelegate::DidPause(WebKit::WebMediaPlayer* player) {
  DCHECK_EQ(MessageLoop::current(), GetWebKitMessageLoop());

  player_map_[player] = false;
  SetDimmingState();
}

void LBWebMediaPlayerDelegate::PlayerGone(WebKit::WebMediaPlayer* player) {
  DCHECK_EQ(MessageLoop::current(), GetWebKitMessageLoop());

  // look for our player in the player map
  PlayerMap::iterator it = player_map_.find(player);
  if (it != player_map_.end()) {
    player_map_.erase(it);
  }
  SetDimmingState();
}

void LBWebMediaPlayerDelegate::PauseActivePlayers() {
  DCHECK_EQ(MessageLoop::current(), GetWebKitMessageLoop());

  // pause all currently playing players in the map
  for (PlayerMap::iterator it = player_map_.begin();
       it != player_map_.end(); ++it) {
    if (it->second) {
      it->first->pause();
      force_paused_list_.push_back(it->first);
    }
  }
}

void LBWebMediaPlayerDelegate::ResumeActivePlayers() {
  DCHECK_EQ(MessageLoop::current(), GetWebKitMessageLoop());

  // resume all force-paused players in the list
  for (PlayerList::iterator it = force_paused_list_.begin();
      it != force_paused_list_.end(); ++it) {
    // make sure object still exists in our map
    PlayerMap::iterator m_it = player_map_.find(*it);
    if (m_it != player_map_.end()) {
      (*it)->play();
    }
  }
  force_paused_list_.clear();
}

LBWebMediaPlayerDelegate::~LBWebMediaPlayerDelegate() {
}

void LBWebMediaPlayerDelegate::SetDimmingState() {
  int num_paused = 0;
  for (PlayerMap::iterator it = player_map_.begin();
       it != player_map_.end(); ++it) {
    if (it->second == false) {
      ++num_paused;
    }
  }

  // If there are no players, or if all players are paused,
  // enable screen-dimming.
  if (num_paused == player_map_.size()) {
    LBGraphics::GetPtr()->EnableDimming();
  } else {
    LBGraphics::GetPtr()->DisableDimming();
  }
}

}  // namespace webkit_media


text:
the vlla resides on 2E, East Campus, MIT. vlla represents a rethinking of the traditional LED paradigm, and uses traditional, GMO free, farm-to-table LED rendering techniques. the vlla is (probably) not sentient. beast is not a hivemind.

## See it in action!
![He-Man](https://thumbs.gfycat.com/CalmLinedDesertpupfish-size_restricted.gif)
![Nyan cat](https://thumbs.gfycat.com/FatScrawnyEland-size_restricted.gif)
![Conway's game of life](https://thumbs.gfycat.com/BlandIllustriousAlaskajingle-size_restricted.gif)
## Launching
### Server
```sh
cd server
npm run start
```

### Client
```sh
cd client
npm run start -- visualizations/[YOUR VISUALIZATION]
```

## Structure
### /client
The local client starts up a node server that sends frames to the server. Ideally, you'll want to keep this local client running when no remote clients are connected to the vlla. You're expected to write your visualizations in `/client/visualizations`. Since this renders to node-canvas, any valid HTML5 Canvas commands will work.

#### Example
```javascript
var vlla = require('../libvlla.js');

// request a canvas and context to render to.
// vlla will ensure the canvas has the correct dimensions
var canvas = vlla.requestCanvas();
var context = vlla.requestContext();

// clear the background
context.fillStyle = 'rgb(0, 0, 0)';
context.fillRect(0, 0, vlla.width, vlla.height);

// write 'hello' to canvas
context.fillStyle = 'rgb(255, 255, 0)';
context.font = '20px Impact';
context.fillText("hello", 0, 29);

// actually send the frame to the vlla
vlla.render();
```

### /server
WebSocket server that accepts connections on **port 8080**. To send a frame, send a ``vlla`` request with the data as a binary array with 60 x 32 x 3 bytes, in R G B R G B format (each color channel is one byte). The server splits and forwards the data to the Teensys through serial.

### /VideoDisplay_8bit
Teensy driver. Accepts 1 byte per LED (960 bytes total, 60 wide by 16 px high), sent in reading order (left-to-right, then top-to-bottom). Each byte should be in the 256 color format: RRRGGGBB. Before sending the data, you must send 0xFF (255). This helps the Teensy know when a frame starts. **Make sure that in your color data, you aren't sending 0xFF (255).**


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace serializer {
    public static class clsSerializer {
        public static string SerializeToString<T>(this T baseType) {
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            serializer.Serialize(stream, baseType);
            stream.Position = 0;
            System.IO.StreamReader strReader = new System.IO.StreamReader(stream);

            return strReader.ReadToEnd();
        }

        public static T DeserializeFromString<T>(string data) {
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
            T theclass;

            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            System.IO.StreamWriter strWriter = new System.IO.StreamWriter(stream);
            strWriter.Write(data);
            strWriter.Flush();
            stream.Position = 0;

            theclass = (T)serializer.Deserialize(stream);

            return theclass;

        }
    }
}


text:
import subprocess
import os
import time
import hashlib
import inspect
import collections
import functools
import util.exceptions
import util.hacks
import util.func
import json

_attr = '_cached_value'

def _disk_cache_path(fn):
    try:
        file_name = util.hacks.get_caller(3)['filename'].strip()
    except IndexError:
        file_name = util.hacks.get_caller(2)['filename'].strip()
    with open(file_name, 'rb') as f:
        sha = hashlib.sha1(f.read()).hexdigest()[:20]
    name = '.'.join(file_name.split('.py')[0].split('/')[-2:])
    return f'/tmp/cache.{name}.{fn.__name__}.{sha}'

@util.func.optionally_parameterized_decorator
def disk(invalidate_on_source_hash=True, max_age_seconds=0):
    def decorator(fn):
        path = _disk_cache_path(fn)
        if not invalidate_on_source_hash:
            path = '.'.join(path.split('.')[:-1])
        @functools.wraps(fn)
        def cached_fn(*a, **kw):
            assert not a or not inspect.ismethod(getattr(a[0], getattr(fn, '__name__', ''), None)), 'cached.disk does not work with methods'
            try:
                with open(path) as f:
                    data = json.load(f)
                    assert not max_age_seconds or time.time() - data['time'] < max_age_seconds
                    return data['value']
            except:
                with open(path, 'w') as f:
                    val = fn(*a, **kw)
                    json.dump({'value': val, 'time': time.time()}, f)
                return val
        cached_fn.clear_cache = lambda: subprocess.check_call(['rm', '-f', path])
        return cached_fn
    return decorator

@util.func.optionally_parameterized_decorator
def disk_memoize(invalidate_on_source_hash=True, max_age_seconds=0):
    def decorator(fn):
        path = _disk_cache_path(fn)
        if not invalidate_on_source_hash:
            path = '.'.join(path.split('.')[:-1])
        @functools.wraps(fn)
        def cached_fn(*a, **kw):
            assert not a or not inspect.ismethod(getattr(a[0], getattr(fn, '__name__', ''), None)), 'cached.disk does not work with methods'
            key = a, kw.items()
            key = ';'.join(map(str, (list(a) + sorted(kw.items(), key=lambda x: x[0]))))
            hash = hashlib.sha1(key.encode('utf-8')).hexdigest()
            _path = '%s_%s' % (path, hash)
            try:
                with open(_path) as f:
                    data = json.load(f)
                    assert not max_age_seconds or time.time() - data['time'] < max_age_seconds
                    return data['value']
            except:
                with open(_path, 'w') as f:
                    val = fn(*a, **kw)
                    json.dump({'value': val, 'time': time.time()}, f)
                return val
        cached_fn.clear_cache = lambda: subprocess.check_call('rm -rf %s*' % path, shell=True)
        return cached_fn
    return decorator

def is_cached(fn):
    return hasattr(fn, _attr)

def func(fn):
    @functools.wraps(fn)
    def cached_fn(*a, **kw):
        assert not a or not inspect.ismethod(getattr(a[0], getattr(fn, '__name__', ''), None)), 'cached.func does not work with methods'
        if not hasattr(cached_fn, _attr):
            cached_fn.clear_cache = lambda: hasattr(cached_fn, _attr) and delattr(cached_fn, _attr)
            setattr(cached_fn, _attr, fn(*a, **kw))
        return getattr(cached_fn, _attr)
    cached_fn.clear_cache = lambda: None
    return cached_fn

@util.func.optionally_parameterized_decorator
def memoize(max_keys=10000):
    def decorator(fn):
        @functools.wraps(fn)
        def decorated(*a, **kw):
            cache = getattr(decorated, _attr)
            key = a, kw.items()
            key = tuple(a), frozenset(kw.items())
            if key not in cache:
                result = fn(*a, **kw)
                cache[key] = result
            else:
                result = cache[key]
            while len(cache) > max_keys: # trim lru to max_keys
                cache.popitem(last=False)
            return result
        setattr(decorated, _attr, collections.OrderedDict())
        return decorated
    return decorator


text:
<!doctype html>

<meta charset="utf-8">
<title>About – My Secondary Vocational English</title>
<meta name="description" content="Task based learning website">

<meta property="og:locale" content="en_US">
<meta property="og:type" content="article">
<meta property="og:title" content="About">
<meta property="og:description" content="Task based learning website">
<meta property="og:url" content="/about/index.html">
<meta property="og:site_name" content="My Secondary Vocational English">

<link rel="canonical" href="/about/">
<link href="/feed.xml" type="application/atom+xml" rel="alternate" title="My Secondary Vocational English Feed">

<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="stylesheet" href="/assets/css/main.css">

<link href="//fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic" rel="stylesheet" type="text/css">

<meta http-equiv="cleartype" content="on">

<link rel="shortcut icon" href="/favicon.ico">

<link rel="shortcut icon" href="/favicon.png">

<link rel="apple-touch-icon-precomposed" href="/images/apple-touch-icon-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="72x72" href="/images/apple-touch-icon-72x72-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="114x114" href="/images/apple-touch-icon-114x114-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="144x144" href="/images/apple-touch-icon-144x144-precomposed.png">

	<button class="dl-trigger">Open Menu</button>

Home

			About

R. Groenbroek and F. Uijtendaal

Is a hedgehog still a hedgehog if it jumps?

Learn More

					 Email

			Grammar

Explanational videos

Individual exercises

			Project opdracht taal

Introduction

Assignment

Step one

Step two

Step three

Conclusion

			Leisure & Hospitality

Project

Introduction

Task

Weekly assignments

Week one

Week two

Week three

Week four

Week five

Week six

Reflection

Report

Teacher page

			Administrative assistant

Project

Introduction

Task

Weekly assignments

Week one

Week two

Week three

Week four

Week five

Reflection

Report

Teacher page

			iMinor Frank

Introduction

Competentie 1

Competentie 2

Competentie 3

Competentie 4

Competentie 5

Competentie 6

Competentie 7

			iMinor Rick

Introduction

Competentie 1

Competentie 2

Competentie 3

Competentie 4

Competentie 5

Competentie 6

Competentie 7

Useful links

Enquête/survey

About

          Reading time ~3 minutes

About task-based language teaching:

Task-Based Language teaching,

Over the course of years Task-Based Language teaching has become more and more interesting. Teachers all over the world have grasped this new idea and developed it in their own way. But what is Task-based teaching? Williams and Burden (1997:168), tell us: "A task is any activity that learners engage in to a process of learning a language." Basically, task-based teaching is an approach which offers students opportunities to actively engage in communication in order to achieve a goal or complete a task. TBL seeks to develop students' interlanguage through providing a task and then using language to solve it. Our tasks, projects and webquests provide an enviroment to do just that. Helping students to achieve a goal, complete a task, to learn something which they can use in their lives.
- F. Uijtendaal & R. Groenbroek

About us:

This site was created by Rick Groenbroek and Frank Uijtendaal. Both studying at the NHL Hogeschool in Leeuwarden, the Netherlands. As teachers to be we have always been figuring out what the best way, for us, is to teach English to Dutch students. There are many ways to teach, standing in front of the classroom, or perhaps making the students work on their own. A new and popular way is Project/Task Based Learning. That's what this website is about.

        Updated on <time datetime="2015-09-16">September 16, 2015</time>
        R. Groenbroek and F. Uijtendaal

 Like

 Tweet

 +1

    © 2014 - 2016 MSVE.nl.

    Please enable JavaScript to view the comments powered by Disqus.
    comments powered by Disqus


text:
using Collection_Hierarchy.Interfaces;

namespace Collection_Hierarchy
{
    public class AddRemoveCollection<T> : Collection<T>, IAddRemoveCollection<T>
    {
        public int Add(T element)
        {
            this.List.Insert(0, element);
            return 0;
        }

        public T Remove()
        {
            T temp = this.List[this.List.Count - 1];
            this.List.RemoveAt(this.List.Count - 1);
            return temp;
        }
    }
}


text:
package com.nutricampus.app.fragments;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.nutricampus.app.R;
import com.nutricampus.app.activities.ListaDadosComplActivity;
import com.nutricampus.app.database.RepositorioDadosComplAnimal;
import com.nutricampus.app.database.RepositorioGrupo;
import com.nutricampus.app.database.SharedPreferencesManager;
import com.nutricampus.app.entities.Animal;
import com.nutricampus.app.entities.DadosComplAnimal;
import com.nutricampus.app.entities.Grupo;
import com.nutricampus.app.utils.Conversor;
import com.nutricampus.app.utils.ValidaFormulario;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Created by Felipe on 19/07/2017.
 * For project NutriCampus.
 * Contact: <felipeguimaraes540@gmail.com>
 */

/*
Explicação para a supressão de warnings:
 - "squid:MaximumInheritanceDepth" = herança extendida em muitos niveis (mais que 5), permitido aqui já
 que refere-se a herança das classes das activities Android
 - "squid:S1172" = erro do sonarqube para os parametros "view" não utilizados
*/
@java.lang.SuppressWarnings({"squid:S1172", "squid:MaximumInheritanceDepth"})
public class DadosComplementaresFragment extends Fragment
        implements View.OnClickListener, DatePickerDialog.OnDateSetListener {

    public static final String EXTRA_ANIMAL = "animal";

    private TextView txtGrupo;
    private EditText inputData;
    private EditText inputPeso;
    private EditText inputCaminhadaVertical;
    private EditText inputCaminhadaHorizontal;
    private RadioGroup radioGroup;
    private EditText inputSemanaLact;

    private Calendar data;
    private Animal animal;
    private DadosComplAnimal dadosComplAnimal;
    private String grupoSelecionado = "";

    private RepositorioGrupo repositorioGrupo;

    public static DadosComplementaresFragment newInstance(Animal animal) {
        Bundle args = new Bundle();
        args.putSerializable(EXTRA_ANIMAL, animal);
        DadosComplementaresFragment fragment = new DadosComplementaresFragment();
        fragment.setArguments(args);
        return fragment;

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        animal = (Animal) getArguments().getSerializable(EXTRA_ANIMAL);
        repositorioGrupo = new RepositorioGrupo(getActivity());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View layout = inflater.inflate(R.layout.fragment_dados_complementares, container, false);

        inputData = (EditText) layout.findViewById(R.id.input_identificador);

        inputData.setVisibility(View.GONE);

        inputData = (EditText) layout.findViewById(R.id.input_data_complementar);
        inputPeso = (EditText) layout.findViewById(R.id.input_peso_vivo);
        inputCaminhadaVertical = (EditText) layout.findViewById(R.id.input_caminhada_vertical);
        inputCaminhadaHorizontal = (EditText) layout.findViewById(R.id.input_caminhada_horizontal);
        inputSemanaLact = (EditText) layout.findViewById(R.id.input_semana_lactacao);
        radioGroup = (RadioGroup) layout.findViewById(R.id.rgEec);

        Button btnSalvar = (Button) layout.findViewById(R.id.btn_salvar);
        Button btnHistRegistros = (Button) layout.findViewById(R.id.btn_hist_registros);

        txtGrupo = (TextView) layout.findViewById(R.id.txtGrupos);

        txtGrupo.setOnClickListener(this);
        btnSalvar.setOnClickListener(this);
        inputData.setOnClickListener(this);
        inicializaCampoData();

        if (animal != null) {
            RepositorioDadosComplAnimal repositorioDadosComplAnimal = new RepositorioDadosComplAnimal(getActivity());
            this.dadosComplAnimal = repositorioDadosComplAnimal.buscarDadosComplAnimal(animal.getId());

            if (dadosComplAnimal != null) {
                inputPeso.setText(String.valueOf(dadosComplAnimal.getPesoVivo()));
                inputData.setText(Conversor.dataFormatada(dadosComplAnimal.getData()));
                inputCaminhadaHorizontal.setText(String.valueOf(dadosComplAnimal.getCaminadaHorizontal()));
                inputCaminhadaVertical.setText(String.valueOf(dadosComplAnimal.getCaminhadaVertical()));
                inputSemanaLact.setText(String.valueOf(dadosComplAnimal.getSemanaLactacao()));

                Log.e("FGP", " <> " + dadosComplAnimal.getIdGrupo());

                txtGrupo.setText("Grupo selecionado: " + repositorioGrupo.buscarGrupo(
                        dadosComplAnimal.getIdGrupo()).getIdentificador());

                if (dadosComplAnimal.getEec() == 0)
                    ((RadioButton) radioGroup.getChildAt(dadosComplAnimal.getEec())).setChecked(true);
                else
                    ((RadioButton) radioGroup.getChildAt(dadosComplAnimal.getEec() - 1)).setChecked(true);
                btnSalvar.setText(getString(R.string.atualizar));
                btnHistRegistros.setVisibility(View.VISIBLE);
                btnHistRegistros.setOnClickListener(this);
            }
        }

        return layout;
    }

    private void inicializaCampoData() {
        Calendar calendario = Calendar.getInstance();
        // O valor do mês pelo Calendar varia entre 0 e 11, por isso soma +1
        if (inputData.getText().toString().equals("")) {
            data = Calendar.getInstance();
            data.set(calendario.get(Calendar.YEAR), calendario.get(Calendar.MONTH), calendario.get(Calendar.DATE));

            inputData.setText(Conversor.dataFormatada(data));
        } else {
            this.data.setTime(Conversor.stringToDate(inputData.getText().toString()));
        }
    }

    public void showDatePickerDialog(View v) {
        Calendar cDefault = Calendar.getInstance();

        DatePickerDialog datePickerDialog = new DatePickerDialog(
                getActivity(),
                this,
                cDefault.get(Calendar.YEAR),
                cDefault.get(Calendar.MONTH),
                cDefault.get(Calendar.DAY_OF_MONTH));

        Calendar cMax = Calendar.getInstance();
        cMax.set(cMax.get(Calendar.YEAR), cMax.get(Calendar.MONTH), cMax.get(Calendar.DATE));
        datePickerDialog.getDatePicker().setMaxDate(cMax.getTime().getTime());

        datePickerDialog.show();
    }

    @Override
    public void onDateSet(DatePicker datePicker, int ano, int mes, int dia) {
        data.set(ano, mes, dia);

        inputData.setText(Conversor.dataFormatada(data));
        inputData.setError(null);
    }

    public interface SalvarDadosAnimal {
        void salvar(DadosComplAnimal dadosComplAnimal, String grupoSelecionado);
    }

    @Override
    public void onClick(View v) {

        if (v.getId() == R.id.txtGrupos) {
            escolherGrupo();
            return;
        }
        else if (v.getId() == R.id.input_data_complementar) {
            showDatePickerDialog(v);
            return;
        }
        else if (v.getId() == R.id.btn_hist_registros) {
            Intent it = new Intent(getActivity(), ListaDadosComplActivity.class);
            it.putExtra(DadosAnimalFragment.EXTRA_ANIMAL, animal);
            startActivity(it);
            return;
        }

        if (!validaDados()) {
            Toast.makeText(getActivity(), R.string.msg_erro_cadastro_geral, Toast.LENGTH_LONG).show();
            return;
        }

        float caminhadaHorizontal = inputCaminhadaHorizontal.getText().toString().equals("") ? 0.0f : Float.parseFloat(inputCaminhadaHorizontal.getText().toString());
        float caminhadaVertical = inputCaminhadaVertical.getText().toString().equals("") ? 0.0f : Float.parseFloat(inputCaminhadaVertical.getText().toString());

        //Atribuir o valor de EEC
        int idRadioButton = radioGroup.getCheckedRadioButtonId();
        RadioButton rb = (RadioButton) radioGroup.findViewById(idRadioButton);

        int eec;
        if (rb == null)
            eec = 0;
        else
            eec = Integer.parseInt(String.valueOf(rb.getText()));

        if (dadosComplAnimal == null) {
            dadosComplAnimal = new DadosComplAnimal(
                    data,
                    Float.parseFloat(inputPeso.getText().toString()),
                    eec,
                    caminhadaHorizontal,
                    caminhadaVertical,
                    Integer.parseInt(inputSemanaLact.getText().toString())
            );
        } else {
            dadosComplAnimal.setData(data);
            dadosComplAnimal.setPesoVivo(Float.parseFloat(inputPeso.getText().toString()));
            dadosComplAnimal.setEec(eec);
            dadosComplAnimal.setCaminadaHorizontal(caminhadaHorizontal);
            dadosComplAnimal.setCaminhadaVertical(caminhadaVertical);
            dadosComplAnimal.setSemanaLactacao(Integer.parseInt(inputSemanaLact.getText().toString()));
            dadosComplAnimal.setIdGrupo(repositorioGrupo.buscarGrupo(grupoSelecionado).getId());
        }

        Activity activity = getActivity();
        if (activity instanceof SalvarDadosAnimal) {
            SalvarDadosAnimal listener = (SalvarDadosAnimal) activity;
            listener.salvar(dadosComplAnimal, grupoSelecionado);
        }

    }

    private boolean validaDados() {
        boolean valido = true;

        List<TextView> camposTexto = new ArrayList<>();
        camposTexto.add(inputData);
        camposTexto.add(inputPeso);
        camposTexto.add(inputSemanaLact);
        camposTexto.add(inputCaminhadaVertical);
        camposTexto.add(inputCaminhadaHorizontal);

        for (TextView view : camposTexto)
            view.setError(null);

        List<TextView> camposVazios = ValidaFormulario.camposTextosVazios(camposTexto);

        if (!camposVazios.isEmpty()) {
            for (TextView view : camposVazios)
                view.setError(getString(R.string.msg_erro_campo));

            valido = false;
        }

        return valido;
    }

    public void escolherGrupo() {

        ArrayList<Grupo> listGrupos= new ArrayList<>();
        listGrupos.clear();

        //Adicionar grupos vindos do repositorio
        int idUsuario = Integer.parseInt(new SharedPreferencesManager(getActivity()).getIdUsuario());
        if (repositorioGrupo.buscarPorUsuario(idUsuario).isEmpty()) {
            repositorioGrupo.inserirGrupo(new Grupo("Pastando", "", idUsuario));
            repositorioGrupo.inserirGrupo(new Grupo("Lactação", "", idUsuario));
            repositorioGrupo.inserirGrupo(new Grupo("Cio", "", idUsuario));
            repositorioGrupo.inserirGrupo(new Grupo("Gestante", "", idUsuario));
        }
        listGrupos.addAll((ArrayList)repositorioGrupo.buscarPorUsuario(idUsuario));

        final String[] grupos = new String[listGrupos.size()];

        for(int i = 0; i < grupos.length; i++) {
            grupos[i] = listGrupos.get(i).getIdentificador();
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("Selecione um grupo");

        int grupoChecked;
        if(animal == null)
            grupoChecked = -1;
        else {
            grupoChecked = dadosComplAnimal.getIdGrupo();
        }

        builder.setSingleChoiceItems(grupos, grupoChecked - 1, new DialogInterface
                .OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                Toast.makeText(getActivity(),
                        grupos[item], Toast.LENGTH_SHORT).show();

                grupoSelecionado = grupos[item];
            }
        });

        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                txtGrupo.setText("Grupo selecionado: " + grupoSelecionado);
                dialog.dismiss();
            }
        });

        AlertDialog alert = builder.create();
        alert.show();
    }

}


text:
class Article < ::ActiveRecord::Base
  rewarding
end


text:
package me.scarlet.undertailor.engine;

/**
 * Skeleton implementation for something that can be
 * processed in every frame.
 */
public interface Processable {

    /**
     * Processes this {@link Processable} object for the
     * current frame.
     *
     * @return generic return value
     */
    public boolean process();
}


text:
require "google/cloud/dlp/v2"

##
# Example demonstrating basic usage of
# Google::Cloud::Dlp::V2::DlpService::Client#get_stored_info_type
#
def get_stored_info_type
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::Dlp::V2::DlpService::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::Dlp::V2::GetStoredInfoTypeRequest.new

  # Call the get_stored_info_type method.
  result = client.get_stored_info_type request

  # The returned object is of type Google::Cloud::Dlp::V2::StoredInfoType.
  p result
end
# [END dlp_v2_generated_DlpService_GetStoredInfoType_sync]


text:
from tkinter import Label
from . import utilities as utils
from .base import Widget

class Picture(Widget):

    def __init__(
        self,
        master,
        image=None,
        grid=None,
        align=None,
        visible=True,
        enabled=None,
        width=None,
        height=None):

        """
        Creates a Picture

        :param Container master:
            The Container (App, Box, etc) the Picture will belong to.

        :param string image:
            A string containing the image to display, defaults to `None`.

        :param List grid:
            Grid co-ordinates for the widget, required if the master layout
            is 'grid', defaults to `None`.

        :param string align:
            How to align the widget within the grid, defaults to None.

        :param bool visible:
            If the widget should be visible, defaults to `True`.

        :param bool enabled:
            If the widget should be enabled, defaults to `None`. If `None`
            the value is inherited from the master.

        :param int width:
            The starting width of the widget. Defaults to `None` and will auto
            size.

        :param int height:
            The starting height of the widget. Defaults to `None` and will auto
            size.
        """

        self._image_source = image
        self._image = None
        self._image_player = None

        # Instantiate label object which will contain image
        tk = Label(master.tk)

        super().__init__(master, tk, grid, align, visible, enabled, width, height)

        # create the image
        self._load_image()

    def _load_image(self):
        if self._height == "fill" or self._width == "fill":
            utils.raise_error("{}\nCannot use 'fill' for width and height.".format(self.description))

        if self._image_source is not None:

            # stop any animation which might still be playing
            if self._image_player:
                self._image_player.stop()

            # load the image and set its properties
            self._image = utils.GUIZeroImage(self._image_source, self._width, self._height)

            self._width = self._image.width
            self._height = self._image.height

            # if its an animation, start it up
            if self._image.animation:
                self._image_player = utils.AnimationPlayer(self, self._image, self._update_tk_image)
            else:
                self._update_tk_image(self._image.tk_image)

            self.tk.config(width=self._width)
            self.tk.config(height=self._height)

    def _update_tk_image(self, tk_image):
        self.tk.config(image=tk_image)

    # PROPERTIES
    # ----------------------------------
    # Get the filename of the image
    @property
    def value(self):
        """
        Gets or sets the file path, tkinter.PhotoImage or PIL.Image you wish to display
        """
        if self._image:
            return self._image.image_source
        else:
            return None

    # Set the image to a given file
    @value.setter
    def value(self, image_source):
        self._image_source = image_source
        self._load_image()

    @property
    def image(self):
        """
        Gets or sets the file path, tkinter.PhotoImage or PIL.Image you wish to display
        """
        return self.value

    # Set the image to a given file
    @image.setter
    def image(self, image_source):
        self.value = image_source

    def resize(self, width, height):
        self._width = width
        self._height = height
        self._load_image()


text:
.class public Lgov/nist/javax/sip/header/ContentEncoding;
.super Lgov/nist/javax/sip/header/SIPHeader;
.source "ContentEncoding.java"

# interfaces
.implements Ljavax/sip/header/ContentEncodingHeader;

# static fields
.field private static final serialVersionUID:J = 0x1c3b09a8a2de85c9L

# instance fields
.field protected contentEncoding:Ljava/lang/String;

# direct methods
.method public constructor <init>()V
    .locals 1

    .prologue
    .line 97
    const-string v0, "Content-Encoding"

    invoke-direct {p0, v0}, Lgov/nist/javax/sip/header/SIPHeader;-><init>(Ljava/lang/String;)V

    .line 98
    return-void
.end method

.method public constructor <init>(Ljava/lang/String;)V
    .locals 1
    .param p1, "enc"    # Ljava/lang/String;

    .prologue
    .line 105
    const-string v0, "Content-Encoding"

    invoke-direct {p0, v0}, Lgov/nist/javax/sip/header/SIPHeader;-><init>(Ljava/lang/String;)V

    .line 106
    iput-object p1, p0, Lgov/nist/javax/sip/header/ContentEncoding;->contentEncoding:Ljava/lang/String;

    .line 107
    return-void
.end method

# virtual methods
.method public encodeBody()Ljava/lang/String;
    .locals 1

    .prologue
    .line 114
    iget-object v0, p0, Lgov/nist/javax/sip/header/ContentEncoding;->contentEncoding:Ljava/lang/String;

    return-object v0
.end method

.method public getEncoding()Ljava/lang/String;
    .locals 1

    .prologue
    .line 122
    iget-object v0, p0, Lgov/nist/javax/sip/header/ContentEncoding;->contentEncoding:Ljava/lang/String;

    return-object v0
.end method

.method public setEncoding(Ljava/lang/String;)V
    .locals 2
    .param p1, "encoding"    # Ljava/lang/String;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/text/ParseException;
        }
    .end annotation

    .prologue
    .line 130
    if-nez p1, :cond_0

    .line 131
    new-instance v0, Ljava/lang/NullPointerException;

    const-string v1, "JAIN-SIP Exception,  encoding is null"

    invoke-direct {v0, v1}, Ljava/lang/NullPointerException;-><init>(Ljava/lang/String;)V

    throw v0

    .line 133
    :cond_0
    iput-object p1, p0, Lgov/nist/javax/sip/header/ContentEncoding;->contentEncoding:Ljava/lang/String;

    .line 134
    return-void
.end method


text:
package com.intellij.remoteServer.runtime;

import com.intellij.util.messages.Topic;
import javax.annotation.Nonnull;

import java.util.EventListener;

/**
 * @author nik
 */
public interface ServerConnectionListener extends EventListener {
  Topic<ServerConnectionListener> TOPIC = Topic.create("server connections", ServerConnectionListener.class);

  void onConnectionCreated(@Nonnull ServerConnection<?> connection);

  void onConnectionStatusChanged(@Nonnull ServerConnection<?> connection);

  void onDeploymentsChanged(@Nonnull ServerConnection<?> connection);
}


text:
package cluedo.control;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;

import cluedo.model.Card;
import cluedo.model.CharRadioBtn;
import cluedo.model.CluedoGame;
import cluedo.model.RoomRadioBtn;
import cluedo.model.WeapRadioBtn;

/**
 * This class creates a custom JDialog which gets
 * 	the player's accusation.
 *
 * @author Patrick and Maria
 *
 */
@SuppressWarnings("serial")
public class Accusation extends JDialog implements ActionListener {

	// reference to main frame
	protected CluedoFrame frame;
	// a field for the selected crime evidence
	public String suspect;
	public String weapon;
	public String room;
	// an arrays of buttons
	private CharRadioBtn[] characterBtns;
	private WeapRadioBtn[] weaponBtns;
	private RoomRadioBtn[] roomBtns;

	private List<Card> result = new ArrayList<Card>();

	public Accusation(CluedoFrame parent) {
		super(parent, "Accusation", true);
        frame = parent;
		initGUI();

		// make the dialog blocking (always on top)
		this.setModalityType(ModalityType.APPLICATION_MODAL);
		// set window title
        this.setTitle("Enter Accusation");
		// set close operation
        this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        // ensures the frame is the minimum size it needs to be
        // in order display the components within it
		this.pack();
        // ensures the minimum size is enforced.
		this.setMinimumSize(this.getSize());
		// set display position
        this.setLocationRelativeTo(getParent());
        // handles the user closing the window dialog
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent evt){
                confirmExit();
            }
        });
	}

	/**
	 * Displays the dialog and returns the result
	 * @return number of players
	 */
	public List<Card> showDialog(){
		this.setVisible(true);
		return result;
	}

	/**
	 * Initilizes the player setup dialog GUI
	 */
	private void initGUI() {
		// adds elements
		createHeader();
		createPlayerGUI();
		createFooter();
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// if selected a suspect
		if(e.getSource() instanceof CharRadioBtn){
			suspect = e.getActionCommand();
		}
		// select a weapon
		else if(e.getSource() instanceof WeapRadioBtn){
			weapon = e.getActionCommand();
		}
		// select a room
		else if(e.getSource() instanceof RoomRadioBtn){
			room = e.getActionCommand();
		}

		// get player's accusation
		if(e.getSource() instanceof JButton){
			// check all elements selected
			if(suspect == null||suspect.length()==0){
				JOptionPane.showMessageDialog(this, "Select a suspect.",
		                "Alert", JOptionPane.ERROR_MESSAGE);

			} else if(weapon == null||weapon.length()==0){
				JOptionPane.showMessageDialog(this, "Select a weapon.",
		                "Alert", JOptionPane.ERROR_MESSAGE);

			} else if(room == null||room.length()==0){
				JOptionPane.showMessageDialog(this, "Select a room.",
		                "Alert", JOptionPane.ERROR_MESSAGE);

			} else if (suspect!=null && weapon!=null && room!=null) {
				List<Card> allCards = new ArrayList<Card>();
				allCards.addAll(Arrays.asList(CluedoGame.Character.values()));
				allCards.addAll(Arrays.asList(CluedoGame.Weapon.values()));
				allCards.addAll(Arrays.asList(CluedoGame.Room.values()));
				for(Card c: allCards){
					if(suspect.equalsIgnoreCase(c.toString())){ result.add(c); }
					if(weapon.equalsIgnoreCase(c.toString())){ result.add(c); }
					if(room.equalsIgnoreCase(c.toString())){ result.add(c); }
				}
				dispose();
			}
		}
	}

	/**
	 * This method create the header for this dialog UI
	 */
	private void createHeader() {
		// Creating a header panel
		JPanel header = new JPanel();
		// Setting header layout and border
		header.setLayout(new BoxLayout(header, BoxLayout.PAGE_AXIS));
		header.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));

		// Creating player and info message labels
		// using html tags to underline text
		JLabel playerMsg = new JLabel("" + frame.player.getCharacter().toString() +
				": " + frame.player.getName() + "");
		JLabel infoMsg = new JLabel("Make Your Accusation.");

		// Setting labels font, border, and alignments
		playerMsg.setFont(new Font("Serif", Font.BOLD, 22));
		playerMsg.setBorder(new EmptyBorder(5,20,5,5));
		infoMsg.setHorizontalAlignment(SwingConstants.CENTER);
		infoMsg.setFont(new Font("Serif", Font.CENTER_BASELINE, 18));
		infoMsg.setBorder(new EmptyBorder(0,10,0,15));

		// adding labels to header panel
		header.add(playerMsg);
		header.add(infoMsg);
		// display header at the north of window
		add(header, BorderLayout.NORTH);
	}

	/**
	 * This method creates the accusation buttons.
	 */
	private void createPlayerGUI() {

		// Creating the content panel to contain the player setup UI
		JPanel content = new JPanel();
		// setting the content layout and border
		content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS));
		content.setBorder(new EmptyBorder(5,5,5,5));

		// Creating a panel for accusation selection
		JPanel charPnl = createCharacterBtnsPnl();
		JPanel weapPnl = createWeaponBtnsPnl();
		JPanel roomPnl = createRoomBtnsPnl();

		// adding the panels to the content panel
		content.add(charPnl);
		content.add(weapPnl);
		content.add(roomPnl);

		// display the content center window
		add(content, BorderLayout.CENTER);
	}

	/**
	 * This method creates the footer for the player setup gui.
	 * 	The footer contains an ok button which validates the
	 * 	users input.
	 */
	private void createFooter() {
		// Creating a panel for the footer
		JPanel footer = new JPanel();
		// Setting the layout and border of the panel
		footer.setLayout(new BoxLayout(footer, BoxLayout.LINE_AXIS));
		footer.setBorder(new EmptyBorder(5,5,5,5));

		// Creating cancel option
		JButton cancelBtn = new JButton("Cancel");
		cancelBtn.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				confirmExit();
			}
		});

		// Creating an ok button
		JButton OKbtn = new JButton("OK");
		// Adding an action listener to the button
		OKbtn.addActionListener(this);

		// Adding the button to the right side of the panel
		footer.add(Box.createHorizontalGlue());
		footer.add(cancelBtn);
		footer.add(OKbtn);

		// Display the footer south in the window
		add(footer, BorderLayout.SOUTH);
	}

	/**
	 * Displays dialog asking if user wants to exit the game
	 */
	protected void confirmExit() {
		String msg = "Are You Sure You Want to Cancel Your Accusation?" ;
		int result = JOptionPane.showConfirmDialog(this, msg,
		        "Alert", JOptionPane.OK_CANCEL_OPTION);
		if(result==0){
			dispose();
			System.exit(0);
		}
	}

	/*---------------------------------------------------
	 * Buttons for suspect, weapon, crime scene selection
	 --------------------------------------------------*/
	/**
	 * Creates and returns a panel containing the
	 * 	character radio buttons for the user to select.
	 * @return JPanel containing radiobuttons
	 */
	private JPanel createCharacterBtnsPnl() {
		// Creating a panel for character selection
		JPanel charPnl = new JPanel(new GridLayout(0,3));
		// setting the character panel border
		charPnl.setBorder(
		   BorderFactory.createCompoundBorder(
				      BorderFactory.createLineBorder(Color.GRAY, 1),
				      BorderFactory.createEmptyBorder(4, 2, 4, 1)
				   )
				);

		// sets a title for this panel
		TitledBorder border = new TitledBorder("Suspects");
	    border.setTitleJustification(TitledBorder.CENTER);
	    border.setTitlePosition(TitledBorder.TOP);
	    charPnl.setBorder(border);

		// Creating a button group for the radio buttons
		ButtonGroup bg = new ButtonGroup();
		// Creating a button for each character in the game
		CharRadioBtn scarlett = new CharRadioBtn("Miss Scarlett");
		CharRadioBtn mustard = new CharRadioBtn("Colonel Mustard");
		CharRadioBtn white = new CharRadioBtn("Mrs White");
		CharRadioBtn green = new CharRadioBtn("The Reverend Green");
		CharRadioBtn peacock = new CharRadioBtn("Mrs Peacock");
		CharRadioBtn plum = new CharRadioBtn("Professor Plum");

		// Adding action commands to the buttons
		scarlett.setActionCommand("MISS SCARLETT");
		mustard.setActionCommand("COLONEL MUSTARD");
		white.setActionCommand("MRS WHITE");
		green.setActionCommand("THE REVEREND GREEN");
		peacock.setActionCommand("MRS PEACOCK");
		plum.setActionCommand("PROFESSOR PLUM");

		// Adding Action listeners
		scarlett.addActionListener(this);
		mustard.addActionListener(this);
		white.addActionListener(this);
		green.addActionListener(this);
		peacock.addActionListener(this);
		plum.addActionListener(this);

		// adding the character radio buttons the the button group
		bg.add(scarlett);
		bg.add(mustard);
		bg.add(white);
		bg.add(green);
		bg.add(peacock);
		bg.add(plum);

		// adding all the buttons to an array
		characterBtns = new CharRadioBtn[6];
		characterBtns[0] = scarlett;
		characterBtns[1] = mustard;
		characterBtns[2] = white;
		characterBtns[3] = green;
		characterBtns[4] = peacock;
		characterBtns[5] = plum;

		// adding each button to the character panel
		charPnl.add(scarlett);
		charPnl.add(mustard);
		charPnl.add(white);
		charPnl.add(green);
		charPnl.add(peacock);
		charPnl.add(plum);

		// return the panel
		return charPnl;
	}

	private JPanel createWeaponBtnsPnl() {
		// Creating a panel for weapon selection
		JPanel weapPnl = new JPanel(new GridLayout(0,3));
		// setting the weapon panel border
		weapPnl.setBorder(
		   BorderFactory.createCompoundBorder(
				      BorderFactory.createLineBorder(Color.GRAY, 1),
				      BorderFactory.createEmptyBorder(4, 2, 4, 1)
				   )
				);

		// sets a title for this panel
		TitledBorder border = new TitledBorder("Weapons");
	    border.setTitleJustification(TitledBorder.CENTER);
	    border.setTitlePosition(TitledBorder.TOP);
	    weapPnl.setBorder(border);

		// Creating a button group for the radio buttons
		ButtonGroup bg = new ButtonGroup();
		// Creating a button for each weapon in the game
		WeapRadioBtn candlestick = new WeapRadioBtn("Candlestick");
		WeapRadioBtn knife = new WeapRadioBtn("Knife");
		WeapRadioBtn pipe = new WeapRadioBtn("Lead Pipe");
		WeapRadioBtn revolver = new WeapRadioBtn("Revolver");
		WeapRadioBtn rope = new WeapRadioBtn("Rope");
		WeapRadioBtn wrench = new WeapRadioBtn("Wrench");

		// Adding action commands to the buttons
		candlestick.setActionCommand("CANDLESTICK");
		knife.setActionCommand("KNIFE");
		pipe.setActionCommand("LEAD PIPE");
		revolver.setActionCommand("REVOLER");
		rope.setActionCommand("ROPE");
		wrench.setActionCommand("WRENCH");

		// Adding Action listeners
		candlestick.addActionListener(this);
		knife.addActionListener(this);
		pipe.addActionListener(this);
		revolver.addActionListener(this);
		rope.addActionListener(this);
		wrench.addActionListener(this);

		// adding the weapon radio buttons the the button group
		bg.add(candlestick);
		bg.add(knife);
		bg.add(pipe);
		bg.add(revolver);
		bg.add(rope);
		bg.add(wrench);

		// adding all the buttons to an array
		weaponBtns = new WeapRadioBtn[6];
		weaponBtns[0] = candlestick;
		weaponBtns[1] = knife;
		weaponBtns[2] = pipe;
		weaponBtns[3] = revolver;
		weaponBtns[4] = rope;
		weaponBtns[5] = wrench;

		// adding each button to the weapon panel
		weapPnl.add(candlestick);
		weapPnl.add(knife);
		weapPnl.add(pipe);
		weapPnl.add(revolver);
		weapPnl.add(rope);
		weapPnl.add(wrench);

		// return the panel
		return weapPnl;
	}

	/**
	 * Creates and returns a panel containing the
	 * 	room radio buttons for the user to select.
	 * @return JPanel containing radiobuttons
	 */
	private JPanel createRoomBtnsPnl() {
		// Creating a panel for room selection
		JPanel roomPnl = new JPanel(new GridLayout(0,3));
		// setting the room panel border
		roomPnl.setBorder(
		   BorderFactory.createCompoundBorder(
				      BorderFactory.createLineBorder(Color.GRAY, 1),
				      BorderFactory.createEmptyBorder(4, 2, 4, 1)
				   )
				);

		// sets a title for this panel
		TitledBorder border = new TitledBorder("Rooms");
	    border.setTitleJustification(TitledBorder.CENTER);
	    border.setTitlePosition(TitledBorder.TOP);
	    roomPnl.setBorder(border);

		// Creating a button group for the radio buttons
		ButtonGroup bg = new ButtonGroup();
		// Creating a button for each room in the game
		RoomRadioBtn kitchen = new RoomRadioBtn("Kitchen");
		RoomRadioBtn ballroom = new RoomRadioBtn("Ball Room");
		RoomRadioBtn conservatory = new RoomRadioBtn("Conservatory");
		RoomRadioBtn billiardRoom = new RoomRadioBtn("Billiard Room");
		RoomRadioBtn library = new RoomRadioBtn("Library");
		RoomRadioBtn study = new RoomRadioBtn("Study");
		RoomRadioBtn hall = new RoomRadioBtn("Hall");
		RoomRadioBtn lounge = new RoomRadioBtn("Lounge");
		RoomRadioBtn diningRoom = new RoomRadioBtn("Dining Room");

		// Adding action commands to the buttons
		kitchen.setActionCommand("KITCHEN");
		ballroom.setActionCommand("BALL ROOM");
		conservatory.setActionCommand("CONSERVATORY");
		billiardRoom.setActionCommand("BILLIARD ROOM");
		library.setActionCommand("LIBRARY");
		study.setActionCommand("STUDY");
		hall.setActionCommand("HALL");
		lounge.setActionCommand("LOUNGE");
		diningRoom.setActionCommand("DINING ROOM");

		// Adding Action listeners
		kitchen.addActionListener(this);
		ballroom.addActionListener(this);
		conservatory.addActionListener(this);
		billiardRoom.addActionListener(this);
		library.addActionListener(this);
		study.addActionListener(this);
		hall.addActionListener(this);
		lounge.addActionListener(this);
		diningRoom.addActionListener(this);

		// adding the room radio buttons the the button group
		bg.add(kitchen);
		bg.add(ballroom);
		bg.add(conservatory);
		bg.add(billiardRoom);
		bg.add(library);
		bg.add(study);
		bg.add(hall);
		bg.add(lounge);
		bg.add(diningRoom);

		// adding all the buttons to an array
		roomBtns = new RoomRadioBtn[9];
		roomBtns[0] = kitchen;
		roomBtns[1] = ballroom;
		roomBtns[2] = conservatory;
		roomBtns[3] = billiardRoom;
		roomBtns[4] = library;
		roomBtns[5] = study;
		roomBtns[6] = hall;
		roomBtns[7] = lounge;
		roomBtns[8] = diningRoom;

		// adding each button to the room panel
		roomPnl.add(kitchen);
		roomPnl.add(ballroom);
		roomPnl.add(conservatory);
		roomPnl.add(billiardRoom);
		roomPnl.add(library);
		roomPnl.add(study);
		roomPnl.add(hall);
		roomPnl.add(lounge);
		roomPnl.add(diningRoom);

		// return the panel
		return roomPnl;
	}
}


text:
using TracingGraphics.Utilities;

namespace TracingGraphics.Materials
{
    public abstract class Material
    {
        public abstract RGBColor PathShade(ref ShadeRec shade);
        public abstract RGBColor AreaLightShade(ref ShadeRec shade);
        public abstract RGBColor Shade(ref ShadeRec shade);
    }
}


text:
/******************************************************************************
 *
 * Module Name: nsdump - table dumping routines for debug
 *
 *****************************************************************************/

/*
 * Copyright (C) 2000 - 2013, Intel Corp.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions, and the following disclaimer,
 *    without modification.
 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
 *    substantially similar to the "NO WARRANTY" disclaimer below
 *    ("Disclaimer") and any redistribution must be conditioned upon
 *    including a substantially similar Disclaimer requirement for further
 *    binary redistribution.
 * 3. Neither the names of the above-listed copyright holders nor the names
 *    of any contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * Alternatively, this software may be distributed under the terms of the
 * GNU General Public License ("GPL") version 2 as published by the Free
 * Software Foundation.
 *
 * NO WARRANTY
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES.
 */

#include <acpi/acpi.h>

/* TBD: This entire module is apparently obsolete and should be removed */

#define _COMPONENT          ACPI_NAMESPACE
ACPI_MODULE_NAME("nsdumpdv")
#ifdef ACPI_OBSOLETE_FUNCTIONS
#if defined(ACPI_DEBUG_OUTPUT) || defined(ACPI_DEBUGGER)
#include "acnamesp.h"
/*******************************************************************************
 *
 * FUNCTION:    acpi_ns_dump_one_device
 *
 * PARAMETERS:  handle              - Node to be dumped
 *              level               - Nesting level of the handle
 *              context             - Passed into walk_namespace
 *              return_value        - Not used
 *
 * RETURN:      Status
 *
 * DESCRIPTION: Dump a single Node that represents a device
 *              This procedure is a user_function called by acpi_ns_walk_namespace.
 *
 ******************************************************************************/
static acpi_status
acpi_ns_dump_one_device(acpi_handle obj_handle,
			u32 level, void *context, void **return_value)
{
	struct acpi_device_info *info;
	acpi_status status;
	u32 i;

	ACPI_FUNCTION_NAME(ns_dump_one_device);

	status =
	    acpi_ns_dump_one_object(obj_handle, level, context, return_value);

	status = acpi_get_object_info(obj_handle, &info);
	if (ACPI_SUCCESS(status)) {
		for (i = 0; i < level; i++) {
			ACPI_DEBUG_PRINT_RAW((ACPI_DB_TABLES, " "));
		}

		ACPI_DEBUG_PRINT_RAW((ACPI_DB_TABLES,
				      "    HID: %s, ADR: %8.8X%8.8X, Status: %X\n",
				      info->hardware_id.string,
				      ACPI_FORMAT_UINT64(info->address),
				      info->current_status));
		ACPI_FREE(info);
	}

	return (status);
}

/*******************************************************************************
 *
 * FUNCTION:    acpi_ns_dump_root_devices
 *
 * PARAMETERS:  None
 *
 * RETURN:      None
 *
 * DESCRIPTION: Dump all objects of type "device"
 *
 ******************************************************************************/

void acpi_ns_dump_root_devices(void)
{
	acpi_handle sys_bus_handle;
	acpi_status status;

	ACPI_FUNCTION_NAME(ns_dump_root_devices);

	/* Only dump the table if tracing is enabled */

	if (!(ACPI_LV_TABLES & acpi_dbg_level)) {
		return;
	}

	status = acpi_get_handle(NULL, METHOD_NAME__SB_, &sys_bus_handle);
	if (ACPI_FAILURE(status)) {
		return;
	}

	ACPI_DEBUG_PRINT((ACPI_DB_TABLES,
			  "Display of all devices in the namespace:\n"));

	status = acpi_ns_walk_namespace(ACPI_TYPE_DEVICE, sys_bus_handle,
					ACPI_UINT32_MAX, ACPI_NS_WALK_NO_UNLOCK,
					acpi_ns_dump_one_device, NULL, NULL,
					NULL);
}

#endif
#endif


text:
from littlepython.parser import Parser
from littlepython.tokenizer import Tokenizer
from tests import v

def test_var():
    ast = v("a")
    parser = Parser(Tokenizer("a"))
    assert parser.statement() == ast


text:
package asyncprovider.client;

public class AsyncClient {

    public static void main (String[] args) {
		Hello_Service service = new Hello_Service();
		Hello proxy = service.getHelloAsyncPort();

		test(proxy, "sync", "source");
		test(proxy, "sync", "bean");
		test(proxy, "async", "source");
		test(proxy, "async", "bean");

    }

	private static void test(Hello proxy, String arg, String extra) {
    	Hello_Type req = new Hello_Type();
    	req.setArgument(arg);
    	req.setExtra(extra);
		System.out.println("Invoking Web Service with = "+arg+","+extra);
    	HelloResponse response = proxy.hello(req, req);
		System.out.println("arg="+response.getArgument()+
			" extra="+response.getExtra());
	}
}