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.flowable.engine.test.bpmn.subprocess;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.assertj.core.api.Assertions.tuple;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.flowable.common.engine.impl.history.HistoryLevel;
import org.flowable.common.engine.impl.util.CollectionUtil;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.impl.test.HistoryTestHelper;
import org.flowable.engine.impl.test.PluggableFlowableTestCase;
import org.flowable.engine.runtime.ActivityInstance;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.engine.test.Deployment;
import org.flowable.job.api.Job;
import org.flowable.task.api.Task;
import org.flowable.task.api.TaskQuery;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.junit.jupiter.api.Test;

/**
 * @author Joram Barrez
 * @author Tijs Rademakers
 */
public class SubProcessTest extends PluggableFlowableTestCase {

    @Test
    @Deployment
    public void testSimpleSubProcess() {

        // After staring the process, the task in the subprocess should be active
        ProcessInstance pi = runtimeService.startProcessInstanceByKey("simpleSubProcess");
        org.flowable.task.api.Task subProcessTask = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
        assertThat(subProcessTask.getName()).isEqualTo("Task in subprocess");

        assertThat(runtimeService.createActivityInstanceQuery().list())
            .extracting(ActivityInstance::getActivityType, ActivityInstance::getActivityId)
            .containsExactlyInAnyOrder(
                tuple("startEvent", "theStart"),
                tuple("sequenceFlow", "flow1"),
                tuple("subProcess", "subProcess"),
                tuple("startEvent", "subProcessStart"),
                tuple("sequenceFlow", "flow2"),
                tuple("userTask", "subProcessTask")
            );

        // After completing the task in the subprocess,
        // the subprocess scope is destroyed and the complete process ends
        taskService.complete(subProcessTask.getId());
        assertThat(runtimeService.createProcessInstanceQuery().processInstanceId(pi.getId()).singleResult()).isNull();
    }

    /**
     * Same test case as before, but now with all automatic steps
     */
    @Test
    @Deployment
    public void testSimpleAutomaticSubProcess() {
        ProcessInstance pi = runtimeService.startProcessInstanceByKey("simpleSubProcessAutomatic");
        assertThat(pi.isEnded()).isTrue();
        assertProcessEnded(pi.getId());
    }

    @Test
    @Deployment
    public void testSimpleSubProcessWithTimer() {

        // We need to make sure the time ends on .000, .003 or .007 due to SQL Server rounding to that
        Date startTime = Date.from(Instant.now().truncatedTo(ChronoUnit.SECONDS).plusMillis(677));

        // After staring the process, the task in the subprocess should be active
        ProcessInstance pi = runtimeService.startProcessInstanceByKey("simpleSubProcess");
        org.flowable.task.api.Task subProcessTask = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
        assertThat(subProcessTask.getName()).isEqualTo("Task in subprocess");

        // Setting the clock forward 2 hours 1 second (timer fires in 2 hours) and fire up the job executor
        processEngineConfiguration.getClock().setCurrentTime(new Date(startTime.getTime() + (2 * 60 * 60 * 1000) + 1000));
        assertThat(managementService.createTimerJobQuery().count()).isEqualTo(1);
        waitForJobExecutorToProcessAllJobs(7000L, 500L);

        // The subprocess should be left, and the escalated task should be active
        org.flowable.task.api.Task escalationTask = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
        assertThat(escalationTask.getName()).isEqualTo("Fix escalated problem");

        // Verify history for task that was killed
        if (HistoryTestHelper.isHistoryLevelAtLeast(HistoryLevel.ACTIVITY, processEngineConfiguration)) {
            HistoricTaskInstance historicTaskInstance = historyService.createHistoricTaskInstanceQuery().taskName("Task in subprocess").singleResult();
            assertThat(historicTaskInstance.getEndTime()).isNotNull();

            HistoricActivityInstance historicActivityInstance = historyService.createHistoricActivityInstanceQuery().activityId("subProcessTask").singleResult();
            assertActivityInstancesAreSame(historicActivityInstance, runtimeService.createActivityInstanceQuery().activityInstanceId(historicActivityInstance.getId()).singleResult());
            assertThat(historicActivityInstance.getEndTime()).isNotNull();
        }
    }

    /**
     * A test case that has a timer attached to the subprocess, where 2 concurrent paths are defined when the timer fires.
     */
    @Deployment
    public void IGNORE_testSimpleSubProcessWithConcurrentTimer() {

        // After staring the process, the task in the subprocess should be active
        ProcessInstance pi = runtimeService.startProcessInstanceByKey("simpleSubProcessWithConcurrentTimer");
        TaskQuery taskQuery = taskService.createTaskQuery().processInstanceId(pi.getId()).orderByTaskName().asc();

        org.flowable.task.api.Task subProcessTask = taskQuery.singleResult();
        assertThat(subProcessTask.getName()).isEqualTo("Task in subprocess");

        // When the timer is fired (after 2 hours), two concurrent paths should be created
        Job job = managementService.createJobQuery().singleResult();
        managementService.executeJob(job.getId());

        List<org.flowable.task.api.Task> tasksAfterTimer = taskQuery.list();
        assertThat(tasksAfterTimer).hasSize(2);
        org.flowable.task.api.Task taskAfterTimer1 = tasksAfterTimer.get(0);
        org.flowable.task.api.Task taskAfterTimer2 = tasksAfterTimer.get(1);
        assertThat(taskAfterTimer1.getName()).isEqualTo("Task after timer 1");
        assertThat(taskAfterTimer2.getName()).isEqualTo("Task after timer 2");

        // Completing the two tasks should end the process instance
        taskService.complete(taskAfterTimer1.getId());
        taskService.complete(taskAfterTimer2.getId());
        assertProcessEnded(pi.getId());
    }

    /**
     * Test case where the simple sub process of previous test cases is nested within another subprocess.
     */
    @Test
    @Deployment
    public void testNestedSimpleSubProcess() {

        // Start and delete a process with a nested subprocess when it is not yet ended
        ProcessInstance pi = runtimeService.startProcessInstanceByKey("nestedSimpleSubProcess", CollectionUtil.singletonMap("someVar", "abc"));
        runtimeService.deleteProcessInstance(pi.getId(), "deleted");

        // After staring the process, the task in the inner subprocess must be active
        pi = runtimeService.startProcessInstanceByKey("nestedSimpleSubProcess");
        org.flowable.task.api.Task subProcessTask = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
        assertThat(subProcessTask.getName()).isEqualTo("Task in subprocess");

        // After completing the task in the subprocess,
        // both subprocesses are destroyed and the task after the subprocess should be active
        taskService.complete(subProcessTask.getId());
        org.flowable.task.api.Task taskAfterSubProcesses = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
        assertThat(taskAfterSubProcesses).isNotNull();
        assertThat(taskAfterSubProcesses.getName()).isEqualTo("Task after subprocesses");
        taskService.complete(taskAfterSubProcesses.getId());

        assertProcessEnded(pi.getId());
    }

    @Test
    @Deployment
    public void testNestedSimpleSubprocessWithTimerOnInnerSubProcess() {
        // We need to make sure the time ends on .000, .003 or .007 due to SQL Server rounding to that
        Date startTime = Date.from(Instant.now().truncatedTo(ChronoUnit.SECONDS).plusMillis(370));

        // After staring the process, the task in the subprocess should be active
        ProcessInstance pi = runtimeService.startProcessInstanceByKey("nestedSubProcessWithTimer");
        org.flowable.task.api.Task subProcessTask = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
        assertThat(subProcessTask.getName()).isEqualTo("Task in subprocess");

        // Setting the clock forward 1 hour 5 second (timer fires in 1 hour) and
        // fire up the job executor
        processEngineConfiguration.getClock().setCurrentTime(new Date(startTime.getTime() + (60 * 60 * 1000) + 5000));
        waitForJobExecutorToProcessAllJobs(7000L, 50L);

        // The inner subprocess should be destroyed, and the escalated task should be active
        org.flowable.task.api.Task escalationTask = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
        assertThat(escalationTask.getName()).isEqualTo("Escalated task");

        // Completing the escalated task, destroys the outer scope and activates
        // the task after the subprocess
        taskService.complete(escalationTask.getId());
        org.flowable.task.api.Task taskAfterSubProcess = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
        assertThat(taskAfterSubProcess.getName()).isEqualTo("Task after subprocesses");
    }

    /**
     * Test case where the simple sub process of previous test cases is nested within two other sub processes
     */
    @Test
    @Deployment
    public void testDoubleNestedSimpleSubProcess() {
        // After staring the process, the task in the inner subprocess must be active
        ProcessInstance pi = runtimeService.startProcessInstanceByKey("nestedSimpleSubProcess");
        org.flowable.task.api.Task subProcessTask = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
        assertThat(subProcessTask.getName()).isEqualTo("Task in subprocess");

        // After completing the task in the subprocess,
        // both subprocesses are destroyed and the task after the subprocess
        // should be active
        taskService.complete(subProcessTask.getId());
        org.flowable.task.api.Task taskAfterSubProcesses = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
        assertThat(taskAfterSubProcesses.getName()).isEqualTo("Task after subprocesses");
    }

    @Test
    @Deployment
    public void testSimpleParallelSubProcess() {

        // After starting the process, the two task in the subprocess should be active
        ProcessInstance pi = runtimeService.startProcessInstanceByKey("simpleParallelSubProcess");
        List<org.flowable.task.api.Task> subProcessTasks = taskService.createTaskQuery().processInstanceId(pi.getId()).orderByTaskName().asc().list();

        // Tasks are ordered by name (see query)
        org.flowable.task.api.Task taskA = subProcessTasks.get(0);
        org.flowable.task.api.Task taskB = subProcessTasks.get(1);
        assertThat(taskA.getName()).isEqualTo("Task A");
        assertThat(taskB.getName()).isEqualTo("Task B");

        // Completing both tasks, should destroy the subprocess and activate the
        // task after the subprocess
        taskService.complete(taskA.getId());
        taskService.complete(taskB.getId());
        org.flowable.task.api.Task taskAfterSubProcess = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
        assertThat(taskAfterSubProcess.getName()).isEqualTo("Task after sub process");
    }

    @Test
    @Deployment
    public void testSimpleParallelSubProcessWithTimer() {

        // After staring the process, the tasks in the subprocess should be active
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("simpleParallelSubProcessWithTimer");
        List<org.flowable.task.api.Task> subProcessTasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).orderByTaskName().asc().list();

        // Tasks are ordered by name (see query)
        org.flowable.task.api.Task taskA = subProcessTasks.get(0);
        org.flowable.task.api.Task taskB = subProcessTasks.get(1);
        assertThat(taskA.getName()).isEqualTo("Task A");
        assertThat(taskB.getName()).isEqualTo("Task B");

        Job job = managementService.createTimerJobQuery().processInstanceId(processInstance.getId()).singleResult();

        managementService.moveTimerToExecutableJob(job.getId());
        managementService.executeJob(job.getId());

        // The inner subprocess should be destroyed, and the task after the timer should be active
        org.flowable.task.api.Task taskAfterTimer = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        assertThat(taskAfterTimer.getName()).isEqualTo("Task after timer");

        // Completing the task after the timer ends the process instance
        taskService.complete(taskAfterTimer.getId());

        assertProcessEnded(processInstance.getId());
    }

    @Test
    @Deployment
    public void testTwoSubProcessInParallel() {
        ProcessInstance pi = runtimeService.startProcessInstanceByKey("twoSubProcessInParallel");
        TaskQuery taskQuery = taskService.createTaskQuery().processInstanceId(pi.getId()).orderByTaskName().asc();
        List<org.flowable.task.api.Task> tasks = taskQuery.list();

        // After process start, both tasks in the subprocesses should be active
        assertThat(tasks.get(0).getName()).isEqualTo("Task in subprocess A");
        assertThat(tasks.get(1).getName()).isEqualTo("Task in subprocess B");

        // Completing both tasks should active the tasks outside the
        // subprocesses
        taskService.complete(tasks.get(0).getId());

        tasks = taskQuery.list();
        assertThat(tasks.get(0).getName()).isEqualTo("Task after subprocess A");
        assertThat(tasks.get(1).getName()).isEqualTo("Task in subprocess B");

        taskService.complete(tasks.get(1).getId());

        tasks = taskQuery.list();

        assertThat(tasks.get(0).getName()).isEqualTo("Task after subprocess A");
        assertThat(tasks.get(1).getName()).isEqualTo("Task after subprocess B");

        // Completing these tasks should end the process
        taskService.complete(tasks.get(0).getId());
        taskService.complete(tasks.get(1).getId());

        assertProcessEnded(pi.getId());
    }

    @Test
    @Deployment
    public void testTwoSubProcessInParallelWithinSubProcess() {
        ProcessInstance pi = runtimeService.startProcessInstanceByKey("twoSubProcessInParallelWithinSubProcess");
        TaskQuery taskQuery = taskService.createTaskQuery().processInstanceId(pi.getId()).orderByTaskName().asc();
        List<org.flowable.task.api.Task> tasks = taskQuery.list();

        // After process start, both tasks in the subprocesses should be active
        org.flowable.task.api.Task taskA = tasks.get(0);
        org.flowable.task.api.Task taskB = tasks.get(1);
        assertThat(taskA.getName()).isEqualTo("Task in subprocess A");
        assertThat(taskB.getName()).isEqualTo("Task in subprocess B");

        // Completing both tasks should active the tasks outside the subprocesses
        taskService.complete(taskA.getId());
        taskService.complete(taskB.getId());

        org.flowable.task.api.Task taskAfterSubProcess = taskQuery.singleResult();
        assertThat(taskAfterSubProcess.getName()).isEqualTo("Task after subprocess");

        // Completing this task should end the process
        taskService.complete(taskAfterSubProcess.getId());
        assertProcessEnded(pi.getId());
    }

    @Test
    @Deployment
    public void testTwoNestedSubProcessesInParallelWithTimer() {

        // Date startTime = new Date();

        ProcessInstance pi = runtimeService.startProcessInstanceByKey("nestedParallelSubProcessesWithTimer");
        TaskQuery taskQuery = taskService.createTaskQuery().processInstanceId(pi.getId()).orderByTaskName().asc();
        List<org.flowable.task.api.Task> tasks = taskQuery.list();

        // After process start, both tasks in the subprocesses should be active
        assertThat(tasks)
                .extracting(Task::getName)
                .containsExactly("Task in subprocess A", "Task in subprocess B");

        // Firing the timer should destroy all three subprocesses and activate the task after the timer
        // processEngineConfiguration.getClock().setCurrentTime(new
        // Date(startTime.getTime() + (2 * 60 * 60 * 1000 ) + 1000));
        // waitForJobExecutorToProcessAllJobs(7000L, 50L);
        Job job = managementService.createTimerJobQuery().singleResult();
        managementService.moveTimerToExecutableJob(job.getId());
        managementService.executeJob(job.getId());

        org.flowable.task.api.Task taskAfterTimer = taskQuery.singleResult();
        assertThat(taskAfterTimer.getName()).isEqualTo("Task after timer");

        // Completing the task should end the process instance
        taskService.complete(taskAfterTimer.getId());
        assertProcessEnded(pi.getId());
    }

    /**
     * @see https://activiti.atlassian.net/browse/ACT-1072
     */
    @Test
    @Deployment
    public void testNestedSimpleSubProcessWithoutEndEvent() {
        testNestedSimpleSubProcess();
    }

    /**
     * @see https://activiti.atlassian.net/browse/ACT-1072
     */
    @Test
    @Deployment
    public void testSimpleSubProcessWithoutEndEvent() {
        ProcessInstance pi = runtimeService.startProcessInstanceByKey("testSimpleSubProcessWithoutEndEvent");
        assertProcessEnded(pi.getId());
    }

    /**
     * @see https://activiti.atlassian.net/browse/ACT-1072
     */
    @Test
    @Deployment
    public void testNestedSubProcessesWithoutEndEvents() {
        ProcessInstance pi = runtimeService.startProcessInstanceByKey("testNestedSubProcessesWithoutEndEvents");
        assertProcessEnded(pi.getId());
    }

    /**
     * @see https://activiti.atlassian.net/browse/ACT-1847
     */
    @Test
    @Deployment
    public void testDataObjectScope() {

        // After staring the process, the task in the subprocess should be
        // active
        ProcessInstance pi = runtimeService.startProcessInstanceByKey("dataObjectScope");

        // get main process task
        org.flowable.task.api.Task currentTask = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();

        assertThat(currentTask.getName()).isEqualTo("Complete Task A");

        // verify main process scoped variables
        Map<String, Object> variables = runtimeService.getVariables(pi.getId());
        assertThat(variables)
                .containsOnly(
                        entry("StringTest123", "Testing123"),
                        entry("NoData123", null)
                );

        // After completing the task in the main process, the subprocess scope
        // initiates
        taskService.complete(currentTask.getId());

        // get subprocess task
        currentTask = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();

        assertThat(currentTask.getName()).isEqualTo("Complete SubTask");

        // verify current scoped variables - includes subprocess variables
        variables = runtimeService.getVariables(currentTask.getExecutionId());
        assertThat(variables)
                .containsOnly(
                        entry("StringTest123", "Testing123"),
                        entry("StringTest456", "Testing456"),
                        entry("NoData123", null)
                );

        // After completing the task in the subprocess, the subprocess scope is destroyed and the main process continues
        taskService.complete(currentTask.getId());

        // verify main process scoped variables
        variables = runtimeService.getVariables(pi.getId());
        assertThat(variables)
                .containsOnly(
                        entry("StringTest123", "Testing123"),
                        entry("NoData123", null)
                );

        currentTask = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
        // Verify there are no local variables assigned to the current task. (subprocess variables are gone).
        variables = runtimeService.getVariablesLocal(currentTask.getExecutionId());
        assertThat(variables).isEmpty();

        // After completing the final task in the main process,
        // the process scope is destroyed and the process ends
        currentTask = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
        assertThat(currentTask.getName()).isEqualTo("Complete Task B");

        taskService.complete(currentTask.getId());
        assertThat(runtimeService.createProcessInstanceQuery().processInstanceId(pi.getId()).singleResult()).isNull();
    }

    @Test
    @Deployment
    public void testAsyncMiSequentialSubProcess() {
        ProcessInstance processInstance = runtimeService.createProcessInstanceBuilder()
                .processDefinitionKey("testAsyncMiSubProcess")
                .variable("myList", Arrays.asList("one", "two", "three"))
                .start();
        assertThat(taskService.createTaskQuery().processInstanceId(processInstance.getId()).count()).isZero();

        Job job = managementService.createJobQuery().processInstanceId(processInstance.getId()).singleResult();
        assertThat(job).isNotNull();
        managementService.executeJob(job.getId());

        assertThat(taskService.createTaskQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(1);
        Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        String variable = (String) runtimeService.getVariable(task.getExecutionId(), "counter");
        assertThat(variable).isEqualTo("one");
        taskService.complete(task.getId());

        Job secondJob = managementService.createJobQuery().processInstanceId(processInstance.getId()).singleResult();
        assertThat(secondJob.getId()).isNotSameAs(job.getId());
        managementService.executeJob(secondJob.getId());

        task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        assertThat((String) runtimeService.getVariable(task.getExecutionId(), "counter")).isEqualTo("two");
        taskService.complete(task.getId());

        Job thirdJob = managementService.createJobQuery().processInstanceId(processInstance.getId()).singleResult();
        assertThat(thirdJob.getId()).isNotSameAs(secondJob.getId());
        managementService.executeJob(thirdJob.getId());

        task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        assertThat((String) runtimeService.getVariable(task.getExecutionId(), "counter")).isEqualTo("three");
        taskService.complete(task.getId());

        assertProcessEnded(processInstance.getId());
    }

    @Test
    @Deployment
    public void testAsyncMiParallelSubProcess() {
        ProcessInstance processInstance = runtimeService.createProcessInstanceBuilder()
                .processDefinitionKey("testAsyncMiSubProcess")
                .variable("myList", Arrays.asList("one", "two", "three"))
                .start();
        assertThat(taskService.createTaskQuery().processInstanceId(processInstance.getId()).count()).isZero();

        List<Job> jobs = managementService.createJobQuery().processInstanceId(processInstance.getId()).list();
        assertThat(jobs).hasSize(3);
        jobs.forEach(job -> managementService.executeJob(job.getId()));

        assertThat(taskService.createTaskQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(3);
        taskService.createTaskQuery().processInstanceId(processInstance.getId()).list().forEach(task -> taskService.complete(task.getId()));

        assertProcessEnded(processInstance.getId());
    }
}


text:
package com.opengamma.financial.fudgemsg;

import static org.testng.AssertJUnit.assertEquals;

import java.util.HashMap;
import java.util.Map;

import org.testng.annotations.Test;

import com.opengamma.core.id.ExternalSchemes;
import com.opengamma.engine.target.Primitive.ExternalIdentifiablePrimitive;
import com.opengamma.financial.analytics.volatility.surface.FuturePriceCurveData;
import com.opengamma.id.UniqueId;
import com.opengamma.util.money.Currency;
import com.opengamma.util.test.TestGroup;

/**
 * Test.
 */
@Test(groups = TestGroup.UNIT)
public class FuturePriceCurveDataFudgeEncodingTest extends FinancialTestBase {

  private static final String DEFINITION_NAME = "DN";
  private static final String SPECIFICATION_NAME = "SN";
  private static final Currency UID = Currency.USD;
  private static final Map<Double, Double> VALUES;
  private static final Double[] X;

  static {
    final int n = 10;
    X = new Double[n];
    VALUES = new HashMap<>();
    for (int i = 0; i < n; i++) {
      X[i] = i * 3.;
      VALUES.put(X[i], Math.random());
    }
  }

  @Test
  public void testCycle() {
    final FuturePriceCurveData<Double> data = new FuturePriceCurveData<>(DEFINITION_NAME, SPECIFICATION_NAME, UID, X, VALUES);
    assertEquals(data, cycleObject(FuturePriceCurveData.class, data));
  }

  @Test
  public void testExternalIdAsTarget() {
//    The following does not work
//    ExternalId extId = ExternalId.of(ExternalSchemes.ACTIVFEED_TICKER, "=SPX.W");
//    UniqueId uniqId = UniqueId.of(extId);
//  ExternalIdentifiablePrimitive primitive = new ExternalIdentifiablePrimitive(uniqId, extId);

    // But this does!
    final UniqueId uniqId = UniqueId.of(ExternalSchemes.ACTIVFEED_TICKER.getName(), "=SPX.W");
    final ExternalIdentifiablePrimitive primitive = new ExternalIdentifiablePrimitive(uniqId, uniqId.toExternalId());

    final FuturePriceCurveData<Double> data = new FuturePriceCurveData<>(DEFINITION_NAME, SPECIFICATION_NAME, primitive, X, VALUES);
    assertEquals(data, cycleObject(FuturePriceCurveData.class, data));
  }
}

redpajama_set_name: RedPajamaGithub


text:
.class final Landroid/app/SystemServiceRegistry$32;
.super Landroid/app/SystemServiceRegistry$CachedServiceFetcher;
.source "SystemServiceRegistry.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/app/SystemServiceRegistry;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = null
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Landroid/app/SystemServiceRegistry$CachedServiceFetcher",
        "<",
        "Landroid/net/wifi/WifiOffloadManager;",
        ">;"
    }
.end annotation

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

    invoke-direct {p0}, Landroid/app/SystemServiceRegistry$CachedServiceFetcher;-><init>()V

    return-void
.end method

# virtual methods
.method public createService(Landroid/app/ContextImpl;)Landroid/net/wifi/WifiOffloadManager;
    .locals 4

    const-string/jumbo v2, "wifioffload"

    invoke-static {v2}, Landroid/os/ServiceManager;->getService(Ljava/lang/String;)Landroid/os/IBinder;

    move-result-object v0

    invoke-static {v0}, Landroid/net/wifi/IWifiOffloadManager$Stub;->asInterface(Landroid/os/IBinder;)Landroid/net/wifi/IWifiOffloadManager;

    move-result-object v1

    const-string/jumbo v2, "SystemServiceRegistry"

    const-string/jumbo v3, "return wifioffload service"

    invoke-static {v2, v3}, Landroid/util/Log;->i(Ljava/lang/String;Ljava/lang/String;)I

    new-instance v2, Landroid/net/wifi/WifiOffloadManager;

    invoke-direct {v2, v1}, Landroid/net/wifi/WifiOffloadManager;-><init>(Landroid/net/wifi/IWifiOffloadManager;)V

    return-object v2
.end method

.method public bridge synthetic createService(Landroid/app/ContextImpl;)Ljava/lang/Object;
    .locals 1
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/ServiceManager$ServiceNotFoundException;
        }
    .end annotation

    invoke-virtual {p0, p1}, Landroid/app/SystemServiceRegistry$32;->createService(Landroid/app/ContextImpl;)Landroid/net/wifi/WifiOffloadManager;

    move-result-object v0

    return-object v0
.end method


text:
package org.robolectric.shadows;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.Shadows;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.RealObject;
import org.robolectric.res.ResourceLoader;
import org.robolectric.fakes.RoboSharedPreferences;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Shadow for {@link android.content.ContextWrapper}.
 */
@Implements(ContextWrapper.class)
public class ShadowContextWrapper extends ShadowContext {
  private final Map<String, RoboSharedPreferences> sharedPreferencesMap = new HashMap<>();
  @RealObject
  private ContextWrapper realContextWrapper;
  private String packageName;

  @Implementation
  public int checkCallingPermission(String permission) {
    return checkPermission(permission, -1, -1);
  }

  @Implementation
  public int checkCallingOrSelfPermission(String permission) {
    return checkPermission(permission, -1, -1);
  }

  @Implementation
  public Context getApplicationContext() {
    Context applicationContext = realContextWrapper.getBaseContext().getApplicationContext();
    return applicationContext == null ? RuntimeEnvironment.application : applicationContext;
  }

  @Implementation
  public ApplicationInfo getApplicationInfo() {
    try {
      final PackageManager packageManager = RuntimeEnvironment.getPackageManager();
      return packageManager != null ? packageManager.getApplicationInfo(getPackageName(), 0) : null;
    } catch (PackageManager.NameNotFoundException e) {
      throw new RuntimeException("Could not find applicationInfo for current package.");
    }
  }

  @Implementation
  public int getUserId() {
    return 0;
  }

  @Override
  public ResourceLoader getResourceLoader() {
    return super.getResourceLoader();
  }

  @Implementation
  @Override
  public String getString(int resId) {
    return super.getString(resId);
  }

  @Implementation
  @Override
  public String getString(int resId, Object... formatArgs) {
    return super.getString(resId, formatArgs);
  }

  @Implementation
  @Override
  public CharSequence getText(int resId) {
    return super.getText(resId);
  }

  @Implementation
  @Override
  public File getExternalCacheDir() {
    return super.getExternalCacheDir();
  }

  @Implementation
  @Override
  public File getExternalFilesDir(String type) {
    return super.getExternalFilesDir(type);
  }

  @Implementation
  public Resources getResources() {
    return getApplicationContext().getResources();
  }

  @Implementation
  public ContentResolver getContentResolver() {
    return getApplicationContext().getContentResolver();
  }

  @Implementation
  public void sendBroadcast(Intent intent) {
    getApplicationContext().sendBroadcast(intent);
  }

  @Implementation
  public void sendBroadcast(Intent intent, String receiverPermission) {
    getApplicationContext().sendBroadcast(intent, receiverPermission);
  }

  @Implementation
  public void sendOrderedBroadcast(Intent intent, String receiverPermission) {
    getApplicationContext().sendOrderedBroadcast(intent, receiverPermission);
  }

  @Implementation
  public void sendOrderedBroadcast(Intent intent, String receiverPermission, BroadcastReceiver resultReceiver,
                                   Handler scheduler, int initialCode, String initialData, Bundle initialExtras) {
    getApplicationContext().sendOrderedBroadcast(intent, receiverPermission, resultReceiver, scheduler, initialCode,
            initialData, initialExtras);
  }

  @Implementation
  public void sendStickyBroadcast(Intent intent) {
    getApplicationContext().sendStickyBroadcast(intent);
  }

  public List<Intent> getBroadcastIntents() {
    return ((ShadowApplication) Shadows.shadowOf(getApplicationContext())).getBroadcastIntents();
  }

  @Implementation
  public int checkPermission(String permission, int pid, int uid) {
    return getShadowApplication().checkPermission(permission, pid, uid);
  }

  @Implementation
  public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
    return ((ShadowApplication) Shadows.shadowOf(getApplicationContext())).registerReceiverWithContext(receiver, filter, null, null, realContextWrapper);
  }

  @Implementation
  public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler) {
    return ((ShadowApplication) Shadows.shadowOf(getApplicationContext())).registerReceiverWithContext(receiver, filter, broadcastPermission, scheduler, realContextWrapper);
  }

  @Implementation
  public void unregisterReceiver(BroadcastReceiver broadcastReceiver) {
    getApplicationContext().unregisterReceiver(broadcastReceiver);
  }

  @Implementation
  public ClassLoader getClassLoader() {
    return getClass().getClassLoader();
  }

  @Implementation
  public String getPackageName() {
    return realContextWrapper == getApplicationContext() ? packageName : getApplicationContext().getPackageName();
  }

  @Implementation
  public PackageManager getPackageManager() {
    return RuntimeEnvironment.getPackageManager();
  }

  @Implementation
  public ComponentName startService(Intent service) {
    return getApplicationContext().startService(service);
  }

  @Implementation
  public boolean stopService(Intent name) {
    return getApplicationContext().stopService(name);
  }

  @Implementation
  public void startActivity(Intent intent) {
    getApplicationContext().startActivity(intent);
  }

  @Implementation
  public void startActivity(Intent intent, Bundle options) {
    getApplicationContext().startActivity(intent, options);
  }

  @Implementation
  public void startActivities(Intent[] intents) {
    for (int i = intents.length - 1; i >= 0; i--) {
      startActivity(intents[i]);
    }
  }

  @Implementation
  public void startActivities(Intent[] intents, Bundle options) {
    for (int i = intents.length - 1; i >= 0; i--) {
      startActivity(intents[i], options);
    }
  }

  @Implementation
  public SharedPreferences getSharedPreferences(String name, int mode) {
    if (!sharedPreferencesMap.containsKey(name)) {
      sharedPreferencesMap.put(name, new RoboSharedPreferences(getShadowApplication().getSharedPreferenceMap(), name, mode));
    }

    return sharedPreferencesMap.get(name);
  }

  @Implementation
  public AssetManager getAssets() {
    return getResources().getAssets();
  }

  /**
   * Non-Android accessor that is used at start-up to set the package name
   *
   * @param packageName the package name
   */
  public void setPackageName(String packageName) {
    this.packageName = packageName;
  }

  /**
   * Non-Android accessor that delegates to the application to consume and return the next {@code Intent} on the
   * started activities stack.
   *
   * @return the next started {@code Intent} for an activity
   */
  public Intent getNextStartedActivity() {
    return getShadowApplication().getNextStartedActivity();
  }

  /**
   * Non-Android accessor that delegates to the application to return (without consuming) the next {@code Intent} on
   * the started activities stack.
   *
   * @return the next started {@code Intent} for an activity
   */
  public Intent peekNextStartedActivity() {
    return getShadowApplication().peekNextStartedActivity();
  }

  /**
   * Non-Android accessor that delegates to the application to consume and return the next {@code Intent} on the
   * started services stack.
   *
   * @return the next started {@code Intent} for a service
   */
  public Intent getNextStartedService() {
    return getShadowApplication().getNextStartedService();
  }

  /**
   * Non-android accessor that delefates to the application to clear the stack of started
   * service intents.
   */
  public void clearStartedServices() {
    getShadowApplication().clearStartedServices();
  }

  /**
   * Return (without consuming) the next {@code Intent} on the started services stack.
   *
   * @return the next started {@code Intent} for a service
   */
  public Intent peekNextStartedService() {
    return getShadowApplication().peekNextStartedService();
  }

  /**
   * Non-Android accessor that delegates to the application to return the next {@code Intent} to stop
   * a service (irrespective of if the service was running)
   *
   * @return {@code Intent} for the next service requested to be stopped
   */
  public Intent getNextStoppedService() {
    return getShadowApplication().getNextStoppedService();
  }

  @Implementation
  public Looper getMainLooper() {
    return getShadowApplication().getMainLooper();
  }

  public ShadowApplication getShadowApplication() {
    return ((ShadowApplication) Shadows.shadowOf(getApplicationContext()));
  }

  @Implementation
  public boolean bindService(Intent intent, final ServiceConnection serviceConnection, int i) {
    return getShadowApplication().bindService(intent, serviceConnection, i);
  }

  @Implementation
  public void unbindService(final ServiceConnection serviceConnection) {
    getShadowApplication().unbindService(serviceConnection);
  }

  @Implementation
  public boolean isRestricted() {
    return false;
  }

  public void grantPermissions(String... permissionNames) {
    getShadowApplication().grantPermissions(permissionNames);
  }

  public void denyPermissions(String... permissionNames) {
    getShadowApplication().denyPermissions(permissionNames);
  }
}


text:
#import "SNBCreateBugViewController.h"
#import "SNBBugCreateModel.h"
#import "SNBAnnotateViewController.h"
#import "SNBScreenShotCollectionCell.h"

#import "SNBBugCreateCellDelegate.h"
#import "SNBBugCreateModelCell.h"
#import "SNBBugCreateSummaryCell.h"

@interface SNBCreateBugViewController () <SNBBugCreateCellDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) IBOutlet UITableView *tableView;
@property (nonatomic, copy) SNBCreateBugViewControllerDismissBlock dismissBlock;
@property (nonatomic, strong) id<SNBBugCreateModel>model;
@property (nonatomic, strong) IBOutlet UITextField *summary;
@property (nonatomic, assign) BOOL didShowBouncerLogin;

@end

@implementation SNBCreateBugViewController

- (instancetype)initWithModel:(id<SNBBugCreateModel>)model dismissBlock:(SNBCreateBugViewControllerDismissBlock)dismissBlock
{
    self = [super init];
    if(self) {
        self.model = model;
        self.dismissBlock = dismissBlock;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self setupView];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [self.model reloadData];
    [self.tableView reloadData];
}

- (void)setupView
{
    self.title = @"New Bug";
    self.view.backgroundColor = [UIColor whiteColor];
    self.view.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;

    UIBarButtonItem *createButton = [[UIBarButtonItem alloc] initWithTitle:@"Send" style:UIBarButtonItemStylePlain target:self action:@selector(createButtonPressed)];
    createButton.accessibilityLabel = @"Create";
    self.navigationItem.rightBarButtonItem = createButton;

    UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStylePlain target:self action:@selector(cancelButtonPressed)];
    cancelButton.accessibilityLabel = @"Cancel";
    self.navigationItem.leftBarButtonItem = cancelButton;

    NSSet *cellTypes = [self.model cellTypes];
    for(Class<SNBBugCreateModelCell>cellType in cellTypes) {
        [self.tableView registerNib:[UINib nibWithNibName:[cellType identifier] bundle:nil] forCellReuseIdentifier:[cellType identifier]];
    }
}

- (void)createButtonPressed
{
    if(![self.model isValidFeedback]) {
        [self showErrorWithTitle:nil message:[self.model invalidFeedbackMessage]];
    } else {
        __weak SNBCreateBugViewController *weakSelf = self;
        [self.model saveWithPresentingViewController:self completionBlock:^(id<SNBBugCreateModel>modeCreator) {
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                [weakSelf dismissViewControllerAnimated:YES completion:NULL];
                if(weakSelf.dismissBlock) {
                    weakSelf.dismissBlock(weakSelf);
                }
            }];
        }];
    }
}

- (void)showErrorWithTitle:(NSString *)title message:(NSString *)message
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                    message:message
                                                   delegate:nil
                                          cancelButtonTitle:nil
                                          otherButtonTitles: NSLocalizedString(@"Ok", nil), nil];
    [alert show];
}

- (void)cancelButtonPressed
{
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        [self dismissViewControllerAnimated:YES completion:NULL];
        if(self.dismissBlock) {
            self.dismissBlock(self);
        }
    }];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [self.model numberOfSections];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.model numberOfRowsInSection:section];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    id<SNBBugCreateModelCell> modelCell = [self.model cellModelForRowAtIndexPath:indexPath];

    UITableViewCell <SNBBugCreateCell> *cell = [tableView dequeueReusableCellWithIdentifier:[[modelCell class] identifier]];
    cell.model = modelCell;
    cell.delegate = self;

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self tableView:self.tableView cellForRowAtIndexPath:indexPath];
    return CGRectGetHeight(cell.bounds);
}

#pragma SNBBugCreateCellDelegate

- (void)didSelectScreenShotWithDataItem:(SNBStateDataItem *)item
{
    // only supported on iOS 7+
    if([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        SNBAnnotateViewController *controller = [[SNBAnnotateViewController alloc] initWithDataItem:item];
        controller.modalPresentationStyle = UIModalPresentationFullScreen;

        if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
            [self.navigationController pushViewController:controller animated:YES];
        } else {
            [self presentViewController:controller animated:YES completion:^{

            }];
        }
    }
}

- (void)keyboardWillShow:(NSNotification *)notification
{
    CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    CGFloat keyBoardHeight = 0;

    if (UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation])) {
        keyBoardHeight = keyboardSize.height;
    } else {
        keyBoardHeight = keyboardSize.width;
    }

    CGRect frame = [UIApplication sharedApplication].keyWindow.frame;
    frame.size.height -= keyBoardHeight;

    NSNumber *rate = notification.userInfo[UIKeyboardAnimationDurationUserInfoKey];
    [UIView animateWithDuration:rate.floatValue animations:^{
        self.tableView.frame = frame;
    }];

}

- (void)keyboardWillHide:(NSNotification *)notification
{
    CGRect frame = self.view.bounds;
    self.tableView.frame = frame;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end


text:
import { formattedTime } from '~/pipelines/stores/test_reports/utils';

describe('Test reports utils', () => {
  describe('formattedTime', () => {
    describe('when time is smaller than a second', () => {
      it('should return time in milliseconds fixed to 2 decimals', () => {
        const result = formattedTime(0.4815162342);
        expect(result).toBe('481.52ms');
      });
    });

    describe('when time is equal to a second', () => {
      it('should return time in seconds fixed to 2 decimals', () => {
        const result = formattedTime(1);
        expect(result).toBe('1.00s');
      });
    });

    describe('when time is greater than a second', () => {
      it('should return time in seconds fixed to 2 decimals', () => {
        const result = formattedTime(4.815162342);
        expect(result).toBe('4.82s');
      });
    });
  });
});


text:
package com.amazonaws.services.cloudformation.model.transform;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.cloudformation.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;

/**
 * GetTemplateRequest Marshaller
 */

public class GetTemplateRequestMarshaller implements
        Marshaller<Request<GetTemplateRequest>, GetTemplateRequest> {

    public Request<GetTemplateRequest> marshall(
            GetTemplateRequest getTemplateRequest) {

        if (getTemplateRequest == null) {
            throw new AmazonClientException(
                    "Invalid argument passed to marshall(...)");
        }

        Request<GetTemplateRequest> request = new DefaultRequest<GetTemplateRequest>(
                getTemplateRequest, "AmazonCloudFormation");
        request.addParameter("Action", "GetTemplate");
        request.addParameter("Version", "2010-05-15");
        request.setHttpMethod(HttpMethodName.POST);

        if (getTemplateRequest.getStackName() != null) {
            request.addParameter("StackName",
                    StringUtils.fromString(getTemplateRequest.getStackName()));
        }

        return request;
    }

}


text:
using Template10.Mvvm;
using System.Collections.Generic;
using System;
using System.Linq;
using System.Threading.Tasks;
using Template10.Services.NavigationService;
using Windows.UI.Xaml.Navigation;

namespace DiveInoUWP.ViewModels
{
    public class MainPageViewModel : ViewModelBase
    {
        public MainPageViewModel()
        {
            if (Windows.ApplicationModel.DesignMode.DesignModeEnabled)
            {
                Value = "Designtime value";
            }
        }

        string _Value = "Gas";
        public string Value { get { return _Value; } set { Set(ref _Value, value); } }

        public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary<string, object> suspensionState)
        {
            if (suspensionState.Any())
            {
                Value = suspensionState[nameof(Value)]?.ToString();
            }
            await Task.CompletedTask;
        }

        public override async Task OnNavigatedFromAsync(IDictionary<string, object> suspensionState, bool suspending)
        {
            if (suspending)
            {
                suspensionState[nameof(Value)] = Value;
            }
            await Task.CompletedTask;
        }

        public override async Task OnNavigatingFromAsync(NavigatingEventArgs args)
        {
            args.Cancel = false;
            await Task.CompletedTask;
        }

        public void GotoDetailsPage() =>
            NavigationService.Navigate(typeof(Views.DetailPage), Value);

        public void GotoSettings() =>
            NavigationService.Navigate(typeof(Views.SettingsPage), 0);

        public void GotoPrivacy() =>
            NavigationService.Navigate(typeof(Views.SettingsPage), 1);

        public void GotoAbout() =>
            NavigationService.Navigate(typeof(Views.SettingsPage), 2);

    }
}


text:
var ffi = require('node-ffi'),
    platform = require('./platform');

var raw = module.exports = new ffi.Library(platform.PCAP_LIBRARY, {
	"pcap_close": ['void', ['pointer']],
	"pcap_open_live": ['pointer', ['string', 'int', 'int', 'int', 'pointer']],
	"pcap_open_dead": ['pointer', ['int', 'int']],
	"pcap_open_offline": ['pointer', ['string', 'pointer']]
});

raw.createErrbuf = function() {
	return new ffi.Pointer(256);
}


text:
use crate::asm::label_parsers::label_ref;
use crate::asm::register_parsers::register;
use crate::asm::Token;

use nom::digit;
use nom::types::CompleteStr;

named!(pub operand<CompleteStr, Token>,
    alt!(
        real_operand |
        integer_operand |
        label_ref |
        register |
        string
    )
);

named!(integer_operand<CompleteStr, Token>,
    ws!(
        do_parse!(
            tag!("#") >>
            sign: opt!(tag!("-")) >>
            integer: digit >>
            (
                {
                    let mut tmp = String::from("");
                    if sign.is_some() {
                        tmp.push_str("-");
                    }
                    tmp.push_str(&integer.to_string());
                    Token::Integer{value: tmp.parse::<i32>().unwrap()}
                }
            )
        )
    )
);

named!(real_operand<CompleteStr, Token>,
    ws!(
        do_parse!(
            tag!("#") >>
            sign: opt!(tag!("-")) >>
            left: digit >>
            tag!(".") >>
            right: digit >>
            (
                {
                    let mut tmp = String::from("");
                    if sign.is_some() {
                        tmp.push_str("-");
                    }
                    tmp.push_str(&left.to_string());
                    tmp.push_str(".");
                    tmp.push_str(&right.to_string());
                    Token::Real{value: tmp.parse::<f64>().unwrap()}
                }
            )
        )
    )
);

named!(string<CompleteStr, Token>,
    do_parse!(
        tag!("'") >>
        content: take_until!("'") >>
        tag!("'") >>
        (
            Token::DoString{ value: content.to_string() }
        )
    )
);

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_integer() {
        let result = integer_operand(CompleteStr("#42"));
        assert!(result.is_ok());

        let (rest, value) = result.unwrap();
        assert_eq!(rest, CompleteStr(""));
        assert_eq!(value, Token::Integer { value: 42 });

        let result = integer_operand(CompleteStr("42"));
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_real() {
        let result = real_operand(CompleteStr("#4.2"));
        assert!(result.is_ok());

        let (rest, value) = result.unwrap();
        assert_eq!(rest, CompleteStr(""));
        assert_eq!(value, Token::Real { value: 4.2 });

        let result = real_operand(CompleteStr("4.2"));
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_operand() {
        let result = operand(CompleteStr("#3.145"));
        assert!(result.is_ok());

        let (rest, value) = result.unwrap();
        assert_eq!(rest, CompleteStr(""));
        assert_eq!(value, Token::Real { value: 3.145 });

        let result = operand(CompleteStr("#4"));
        assert!(result.is_ok());

        let (rest, value) = result.unwrap();
        assert_eq!(rest, CompleteStr(""));
        assert_eq!(value, Token::Integer { value: 4 });
    }

    #[test]
    fn test_parse_label() {
        let result = operand(CompleteStr("@test"));
        assert!(result.is_ok());

        let (rest, value) = result.unwrap();
        assert_eq!(rest, CompleteStr(""));
        assert_eq!(
            value,
            Token::LabelRef {
                name: "test".to_string()
            }
        );

        let result = operand(CompleteStr("test"));
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_string() {
        let result = string(CompleteStr("'hello do'"));
        assert!(result.is_ok());

        let (rest, value) = result.unwrap();
        assert_eq!(rest, CompleteStr(""));
        assert_eq!(
            value,
            Token::DoString {
                value: "hello do".to_string()
            }
        );

        let result = string(CompleteStr("'invalid"));
        assert!(result.is_err());
    }
}


text:
"""Dynamic loss scaler for AMP."""
import logging

from .. import autograd as ag
from .. import ndarray
from ..util import is_np_array

class LossScaler(object):
    """Dynamic loss scaler for AMP.

    Properties
    ----------
    loss_scale : float
        The current loss scale
    """
    def __init__(self):
        self._loss_scale = 2.**16
        self._next_loss_scale = self._loss_scale
        self._max_loss_scale = 2.**24
        self._scale_seq_len = 2000
        self._unskipped = 0

    @property
    def loss_scale(self):
        return self._loss_scale

    def has_overflow(self, params):
        """Check gradients for overflow."""
        if is_np_array():
            all_finite_f = ndarray.numpy._internal.multi_all_finite
            ones_f = ndarray.numpy.ones
        else:
            all_finite_f = ndarray.multi_all_finite
            ones_f = ndarray.ones
        with ag.pause():
            chunk_size = 200
            valid_params = [p._grad[0] for p in params if p._grad is not None]
            gpu_output = ones_f((1,), ctx=valid_params[0].context)
            nb_params = len(valid_params)
            for idx in range(0, nb_params, chunk_size):
                all_finite_f(*valid_params[idx:idx+chunk_size],
                             num_arrays=len(valid_params[idx:idx+chunk_size]),
                             init_output=False, out=gpu_output)
        has_overflow = not bool(gpu_output.asnumpy())
        self._loss_scale = self._next_loss_scale
        if has_overflow:
            self._next_loss_scale = self._loss_scale / 2.
            self._unskipped = 0
            logging.info("AMP: decreasing loss scale to %f", self._next_loss_scale)
        else:
            self._unskipped += 1
        if self._unskipped == self._scale_seq_len:
            self._unskipped = 0
            self._next_loss_scale = min(self._max_loss_scale, self._loss_scale * 2.)
            logging.info("AMP: increasing loss scale to %f", self._next_loss_scale)
        return has_overflow


text:
docid: sample-code
title: Sample code
layout: docs
permalink: /docs/sample-code.html
---

*Note: the samples are licensed for non-commercial or evaluation purposes only, not the MIT license used for Fresco itself.*

Fresco's GitHub repository contains several samples to demonstrate how to use Fresco in your apps.

The samples are available in source form only. Follow the [build instructions](building-from-source.html) to set up your dev environment to build and run them.

### The Showcase app

The [Showcase App](https://github.com/facebook/fresco/blob/master/samples/showcase) demonstrates various features and allows to customize parameters to show their effect.
It includes samples for Drawee and for the image pipeline. Furthermore, it showcases how to use both built-in and custom image formats.

### The zoomable library

The [zoomable library](https://github.com/facebook/fresco/blob/master/samples/zoomable) features a `ZoomableDraweeView` class that supports gestures such as pinch-to-zoom and panning of a Drawee image.

### The comparison app

The comparison app lets the user do a proper, apples-to-apples comparison of Fresco with [Picasso](http://square.github.io/picasso), [Universal Image Loader](https://github.com/nostra13/Android-Universal-Image-Loader), [Volley](https://developer.android.com/training/volley/index.html)'s image loader, and [Glide](https://github.com/bumptech/glide).

Fresco allows you to also compare its performance with OkHttp as its network layer. You can also see the performance of Drawee running over Volley instead of Fresco's image pipeline.

The app offers you a choice of images from your local camera or from the Internet. The network images come from [Imgur](http://imgur.com).

You can build, install, and run a controlled test of any combination of loaders using the [run_comparison.py](https://github.com/facebook/fresco/blob/master/run_comparison.py) script. The following command will run them all on a connected ARM v7 device:

```./run_comparison.py -c armeabi-v7a```

### The round app

The round app shows the same image scaled in several different ways, with and without a circle applied.


text:
import Vue from 'vue'
import {
  Pagination,
  Dialog,
  Autocomplete,
  Dropdown,
  DropdownMenu,
  DropdownItem,
  Menu,
  Submenu,
  MenuItem,
  MenuItemGroup,
  Input,
  InputNumber,
  Radio,
  RadioGroup,
  RadioButton,
  Checkbox,
  CheckboxGroup,
  Switch,
  Select,
  Option,
  OptionGroup,
  Button,
  ButtonGroup,
  Table,
  TableColumn,
  DatePicker,
  TimeSelect,
  TimePicker,
  Popover,
  Tooltip,
  Breadcrumb,
  BreadcrumbItem,
  Form,
  FormItem,
  Tabs,
  TabPane,
  Tag,
  Tree,
  Alert,
  Slider,
  Icon,
  Row,
  Col,
  Upload,
  Progress,
  Spinner,
  Badge,
  Card,
  Rate,
  Steps,
  Step,
  Carousel,
  Scrollbar,
  CarouselItem,
  Collapse,
  CollapseItem,
  Cascader,
  ColorPicker,
  Loading,
  MessageBox,
  Message,
  Notification
} from 'element-ui'

Vue.use(Pagination)
Vue.use(Dialog)
Vue.use(Autocomplete)
Vue.use(Dropdown)
Vue.use(DropdownMenu)
Vue.use(DropdownItem)
Vue.use(Menu)
Vue.use(Submenu)
Vue.use(MenuItem)
Vue.use(MenuItemGroup)
Vue.use(Input)
Vue.use(InputNumber)
Vue.use(Radio)
Vue.use(RadioGroup)
Vue.use(RadioButton)
Vue.use(Checkbox)
Vue.use(CheckboxGroup)
Vue.use(Switch)
Vue.use(Select)
Vue.use(Option)
Vue.use(OptionGroup)
Vue.use(Button)
Vue.use(ButtonGroup)
Vue.use(Table)
Vue.use(TableColumn)
Vue.use(DatePicker)
Vue.use(TimeSelect)
Vue.use(TimePicker)
Vue.use(Popover)
Vue.use(Tooltip)
Vue.use(Breadcrumb)
Vue.use(BreadcrumbItem)
Vue.use(Form)
Vue.use(FormItem)
Vue.use(Tabs)
Vue.use(TabPane)
Vue.use(Tag)
Vue.use(Tree)
Vue.use(Alert)
Vue.use(Slider)
Vue.use(Icon)
Vue.use(Row)
Vue.use(Col)
Vue.use(Upload)
Vue.use(Progress)
Vue.use(Spinner)
Vue.use(Badge)
Vue.use(Card)
Vue.use(Rate)
Vue.use(Steps)
Vue.use(Step)
Vue.use(Carousel)
Vue.use(Scrollbar)
Vue.use(CarouselItem)
Vue.use(Collapse)
Vue.use(CollapseItem)
Vue.use(Cascader)
Vue.use(ColorPicker)

Vue.use(Loading.directive)

Vue.prototype.$loading = Loading.service
Vue.prototype.$msgbox = MessageBox
Vue.prototype.$alert = MessageBox.alert
Vue.prototype.$confirm = MessageBox.confirm
Vue.prototype.$prompt = MessageBox.prompt
Vue.prototype.$notify = Notification
Vue.prototype.$message = Message