text:
import os
import shutil
import paddle
import unittest
import paddle.fluid as fluid
from mobilenet import MobileNet
from paddle.fluid.contrib.slim.core import Compressor
from paddle.fluid.contrib.slim.graph import GraphWrapper

class TestReader(unittest.TestCase):
    """
    Test API of quantization strategy.
    """

    def set_train_reader(self, image, label, place):
        train_reader = paddle.batch(
            paddle.dataset.mnist.train(), batch_size=128)
        return train_reader

    def set_val_reader(self, image, label, place):
        val_reader = paddle.batch(paddle.dataset.mnist.test(), batch_size=128)
        return val_reader

    def set_feed_list(self, image, label):
        return [('img', image.name), ('label', label.name)]

    def quan(self, config_file):
        if os.path.exists('./checkpoints_quan'):
            shutil.rmtree('./checkpoints_quan')

        if not fluid.core.is_compiled_with_cuda():
            return
        class_dim = 10
        image_shape = [1, 28, 28]

        train_program = fluid.Program()
        startup_program = fluid.Program()
        val_program = fluid.Program()

        with fluid.program_guard(train_program, startup_program):
            with fluid.unique_name.guard():
                image = fluid.layers.data(
                    name='image', shape=image_shape, dtype='float32')
                image.stop_gradient = False
                label = fluid.layers.data(
                    name='label', shape=[1], dtype='int64')
                out = MobileNet(name='quan').net(input=image,
                                                 class_dim=class_dim)
                print("out: {}".format(out.name))
                acc_top1 = fluid.layers.accuracy(input=out, label=label, k=1)
                acc_top5 = fluid.layers.accuracy(input=out, label=label, k=5)
                cost = fluid.layers.cross_entropy(input=out, label=label)
                avg_cost = fluid.layers.mean(x=cost)
        optimizer = fluid.optimizer.Momentum(
            momentum=0.9,
            learning_rate=0.01,
            regularization=fluid.regularizer.L2Decay(4e-5))

        val_program = train_program.clone(for_test=False)

        place = fluid.CUDAPlace(0)
        exe = fluid.Executor(place)
        exe.run(startup_program)

        val_reader = self.set_val_reader(image, label, place)

        val_feed_list = self.set_feed_list(image, label)
        val_fetch_list = [('acc_top1', acc_top1.name), ('acc_top5',
                                                        acc_top5.name)]

        train_reader = self.set_train_reader(image, label, place)
        train_feed_list = self.set_feed_list(image, label)
        train_fetch_list = [('loss', avg_cost.name)]

        com_pass = Compressor(
            place,
            fluid.global_scope(),
            train_program,
            train_reader=train_reader,
            train_feed_list=train_feed_list,
            train_fetch_list=train_fetch_list,
            eval_program=val_program,
            eval_reader=val_reader,
            eval_feed_list=val_feed_list,
            eval_fetch_list=val_fetch_list,
            train_optimizer=optimizer)
        com_pass.config(config_file)
        eval_graph = com_pass.run()

class TestReader1(TestReader):
    def set_train_reader(self, image, label, place):
        loader = fluid.io.DataLoader.from_generator(
            feed_list=[image, label], capacity=16, iterable=True)
        loader.set_sample_generator(
            paddle.dataset.mnist.train(), batch_size=128, places=place)
        return loader

    def set_val_reader(self, image, label, place):
        loader = fluid.io.DataLoader.from_generator(
            feed_list=[image, label], capacity=16, iterable=True)
        loader.set_sample_generator(
            paddle.dataset.mnist.test(), batch_size=128, places=place)
        return loader

    def test_compression(self):
        self.quan("./quantization/compress_1.yaml")

if __name__ == '__main__':
    unittest.main()


text:
DROP TABLE IF EXISTS public."HET_TIME_RECORD_HIST";

CREATE TABLE public."HET_TIME_RECORD_HIST"
(
    "TIME_RECORD_HIST_ID" integer NOT NULL DEFAULT nextval('"HET_TIME_RECORD_HIST_ID_seq"'::regclass),
	"TIME_RECORD_ID" integer NOT NULL,
	"EFFECTIVE_DATE" timestamp without time zone NOT NULL,
    "END_DATE" timestamp without time zone,
    "ENTERED_DATE" timestamp without time zone,
    "HOURS" real,
    "RENTAL_AGREEMENT_RATE_ID" integer,
    "WORKED_DATE" timestamp without time zone NOT NULL,
    "TIME_PERIOD" character varying(20) COLLATE pg_catalog."default",
    "DB_CREATE_TIMESTAMP" timestamp without time zone NOT NULL DEFAULT '0001-01-01 00:00:00'::timestamp without time zone,
    "APP_CREATE_USER_DIRECTORY" character varying(50) COLLATE pg_catalog."default",
    "DB_LAST_UPDATE_TIMESTAMP" timestamp without time zone NOT NULL DEFAULT '0001-01-01 00:00:00'::timestamp without time zone,
    "APP_LAST_UPDATE_USER_DIRECTORY" character varying(50) COLLATE pg_catalog."default",
    "RENTAL_AGREEMENT_ID" integer,
    "CONCURRENCY_CONTROL_NUMBER" integer NOT NULL DEFAULT 1,
	"APP_CREATE_TIMESTAMP" timestamp without time zone NOT NULL DEFAULT '0001-01-01 00:00:00'::timestamp without time zone,
    "APP_CREATE_USER_GUID" character varying(255) COLLATE pg_catalog."default",
    "APP_CREATE_USERID" character varying(255) COLLATE pg_catalog."default",
    "APP_LAST_UPDATE_TIMESTAMP" timestamp without time zone NOT NULL DEFAULT '0001-01-01 00:00:00'::timestamp without time zone,
    "APP_LAST_UPDATE_USER_GUID" character varying(255) COLLATE pg_catalog."default",
    "APP_LAST_UPDATE_USERID" character varying(255) COLLATE pg_catalog."default",
    "DB_CREATE_USER_ID" character varying(63) COLLATE pg_catalog."default",
    "DB_LAST_UPDATE_USER_ID" character varying(63) COLLATE pg_catalog."default",
    CONSTRAINT "HET_TIME_RECORD_HIST_PK" PRIMARY KEY ("TIME_RECORD_HIST_ID")

)
WITH (
    OIDS = FALSE
)
TABLESPACE pg_default;

ALTER TABLE public."HET_TIME_RECORD_HIST"
    OWNER to "user6DA";

redpajama_set_name: RedPajamaGithub


text:
package git4idea.test;

import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vcs.impl.ProjectLevelVcsManagerImpl;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.vcs.log.VcsLogObjectsFactory;
import com.intellij.vcs.log.VcsRef;
import git4idea.GitUtil;
import git4idea.GitVcs;
import git4idea.config.GitVersion;
import git4idea.repo.GitRepository;
import org.jetbrains.annotations.NotNull;
import org.picocontainer.MutablePicoContainer;

import java.io.File;
import java.io.IOException;
import java.util.Set;

import static com.intellij.openapi.vcs.Executor.append;
import static com.intellij.openapi.vcs.Executor.cd;
import static com.intellij.openapi.vcs.Executor.mkdir;
import static com.intellij.openapi.vcs.Executor.touch;
import static git4idea.test.GitExecutor.*;
import static junit.framework.Assert.assertNotNull;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assume.assumeTrue;

public class GitTestUtil {

  public static final String USER_NAME = "John Doe";
  public static final String USER_EMAIL = "John.Doe@example.com";

  /**
   *
Creates file structure for given paths. Path element should be a relative (from project root)
   * path to a file or a directory. All intermediate paths will be created if needed.
   * To create a dir without creating a file pass "dir/" as a parameter.

   *
Usage example:
   * createFileStructure("a.txt", "b.txt", "dir/c.txt", "dir/subdir/d.txt", "anotherdir/");

   *
This will create files a.txt and b.txt in the project dir, create directories dir, dir/subdir and anotherdir,
   * and create file c.txt in dir and d.txt in dir/subdir.

   *
Note: use forward slash to denote directories, even if it is backslash that separates dirs in your system.

   *
All files are populated with "initial content" string.

   */
  public static void createFileStructure(@NotNull VirtualFile rootDir, String... paths) {
    for (String path : paths) {
      cd(rootDir);
      boolean dir = path.endsWith("/");
      if (dir) {
        mkdir(path);
      }
      else {
        touch(path, "initial_content_" + Math.random());
      }
    }
  }

  private static void initRepo(@NotNull String repoRoot, boolean makeInitialCommit) {
    cd(repoRoot);
    git("init");
    setupUsername();
    if (makeInitialCommit) {
      touch("initial.txt");
      git("add initial.txt");
      git("commit -m initial");
    }
  }

  public static void setupUsername() {
    git("config user.name '" + USER_NAME + "'");
    git("config user.email '" + USER_EMAIL + "'");
  }

  /**
   * Creates a Git repository in the given root directory;
   * registers it in the Settings;
   * return the {@link GitRepository} object for this newly created repository.
   */
  @NotNull
  public static GitRepository createRepository(@NotNull Project project, @NotNull String root) {
    return createRepository(project, root, true);
  }

  public static GitRepository createRepository(@NotNull Project project, @NotNull String root, boolean makeInitialCommit) {
    initRepo(root, makeInitialCommit);
    VirtualFile gitDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(root, GitUtil.DOT_GIT));
    assertNotNull(gitDir);
    return registerRepo(project, root);
  }

  @NotNull
  public static GitRepository registerRepo(Project project, String root) {
    ProjectLevelVcsManagerImpl vcsManager = (ProjectLevelVcsManagerImpl)ProjectLevelVcsManager.getInstance(project);
    vcsManager.setDirectoryMapping(root, GitVcs.NAME);
    VirtualFile file = LocalFileSystem.getInstance().findFileByIoFile(new File(root));
    assertFalse(vcsManager.getAllVcsRoots().length == 0);
    GitRepository repository = GitUtil.getRepositoryManager(project).getRepositoryForRoot(file);
    assertNotNull("Couldn't find repository for root " + root, repository);
    return repository;
  }

  public static void assumeSupportedGitVersion(@NotNull GitVcs vcs) {
    GitVersion version = vcs.getVersion();
    assumeTrue("Unsupported Git version: " + version, version.isSupported());
  }

  @SuppressWarnings("unchecked")
  @NotNull
  public static <T> T overrideService(@NotNull Project project, Class<? super T> serviceInterface, Class<T> serviceImplementation) {
    String key = serviceInterface.getName();
    MutablePicoContainer picoContainer = (MutablePicoContainer) project.getPicoContainer();
    picoContainer.unregisterComponent(key);
    picoContainer.registerComponentImplementation(key, serviceImplementation);
    return (T) ServiceManager.getService(project, serviceInterface);
  }

  @SuppressWarnings("unchecked")
  @NotNull
  public static <T> T overrideService(Class<? super T> serviceInterface, Class<T> serviceImplementation) {
    String key = serviceInterface.getName();
    MutablePicoContainer picoContainer = (MutablePicoContainer) ApplicationManager.getApplication().getPicoContainer();
    picoContainer.unregisterComponent(key);
    picoContainer.registerComponentImplementation(key, serviceImplementation);
    return (T) ServiceManager.getService(serviceInterface);
  }

  @NotNull
  public static Set<VcsRef> readAllRefs(@NotNull VirtualFile root, @NotNull VcsLogObjectsFactory objectsFactory) {
    String[] refs = StringUtil.splitByLines(git("log --branches --tags --no-walk --format=%H%d --decorate=full"));
    Set<VcsRef> result = ContainerUtil.newHashSet();
    for (String ref : refs) {
      result.addAll(new RefParser(objectsFactory).parseCommitRefs(ref, root));
    }
    return result;
  }

  @NotNull
  public static String makeCommit(String file) throws IOException {
    append(file, "some content");
    addCommit("some message");
    return last();
  }

  public static void assertNotification(@NotNull NotificationType type,
                                        @NotNull String title,
                                        @NotNull String content,
                                        @NotNull Notification actual) {
    assertEquals("Incorrect type of notification: " + tos(actual), type, actual.getType());
    assertEquals(title, actual.getTitle());
    assertEquals(cleanupForAssertion(content), cleanupForAssertion(actual.getContent()));
  }

  @NotNull
  public static String cleanupForAssertion(@NotNull String content) {
    return content.replace("
", "\n").replace("\n", " ").replaceAll("[ ]{2,}", " ").replaceAll(" href='[^']*'", "").trim();
  }

  @NotNull
  private static String tos(@NotNull Notification notification) {
    return notification.getTitle() + "|" + notification.getContent();
  }
}


text:
from mock import patch
from pytest import raises

from teuthology.config import FakeNamespace
from teuthology.orchestra.cluster import Cluster
from teuthology.orchestra.remote import Remote
from teuthology.task import Task

class TestTask(object):
    def setup(self):
        self.ctx = FakeNamespace()
        self.ctx.config = dict()

    def test_overrides(self):
        self.ctx.config['overrides'] = dict(
            task=dict(
                key_1='overridden',
            ),
        )
        task_config = dict(
            key_1='default',
            key_2='default',
        )
        with Task(self.ctx, task_config) as task:
            assert task.config['key_1'] == 'overridden'
            assert task.config['key_2'] == 'default'

    def test_hosts_no_filter(self):
        self.ctx.cluster = Cluster()
        self.ctx.cluster.add(Remote('remote1'), ['role1'])
        self.ctx.cluster.add(Remote('remote2'), ['role2'])
        task_config = dict()
        with Task(self.ctx, task_config) as task:
            task_hosts = task.cluster.remotes.keys()
            assert len(task_hosts) == 2
            assert sorted(host.name for host in task_hosts) == ['remote1',
                                                                'remote2']

    def test_hosts_no_results(self):
        self.ctx.cluster = Cluster()
        self.ctx.cluster.add(Remote('remote1'), ['role1'])
        task_config = dict(
            hosts=['role2'],
        )
        with raises(RuntimeError):
            with Task(self.ctx, task_config):
                pass

    def test_hosts_one_role(self):
        self.ctx.cluster = Cluster()
        self.ctx.cluster.add(Remote('remote1'), ['role1'])
        self.ctx.cluster.add(Remote('remote2'), ['role2'])
        task_config = dict(
            hosts=['role1'],
        )
        with Task(self.ctx, task_config) as task:
            task_hosts = task.cluster.remotes.keys()
            assert len(task_hosts) == 1
            assert task_hosts[0].name == 'remote1'

    def test_hosts_two_roles(self):
        self.ctx.cluster = Cluster()
        self.ctx.cluster.add(Remote('remote1'), ['role1'])
        self.ctx.cluster.add(Remote('remote2'), ['role2'])
        self.ctx.cluster.add(Remote('remote3'), ['role3'])
        task_config = dict(
            hosts=['role1', 'role3'],
        )
        with Task(self.ctx, task_config) as task:
            task_hosts = task.cluster.remotes.keys()
            assert len(task_hosts) == 2
            hostnames = [host.name for host in task_hosts]
            assert sorted(hostnames) == ['remote1', 'remote3']

    def test_hosts_two_hostnames(self):
        self.ctx.cluster = Cluster()
        self.ctx.cluster.add(Remote('remote1.example.com'), ['role1'])
        self.ctx.cluster.add(Remote('remote2.example.com'), ['role2'])
        self.ctx.cluster.add(Remote('remote3.example.com'), ['role3'])
        task_config = dict(
            hosts=['remote1', 'remote2.example.com'],
        )
        with Task(self.ctx, task_config) as task:
            task_hosts = task.cluster.remotes.keys()
            assert len(task_hosts) == 2
            hostnames = [host.name for host in task_hosts]
            assert sorted(hostnames) == ['remote1.example.com',
                                         'remote2.example.com']

    def test_hosts_one_role_one_hostname(self):
        self.ctx.cluster = Cluster()
        self.ctx.cluster.add(Remote('remote1.example.com'), ['role1'])
        self.ctx.cluster.add(Remote('remote2.example.com'), ['role2'])
        self.ctx.cluster.add(Remote('remote3.example.com'), ['role3'])
        task_config = dict(
            hosts=['role1', 'remote2.example.com'],
        )
        with Task(self.ctx, task_config) as task:
            task_hosts = task.cluster.remotes.keys()
            assert len(task_hosts) == 2
            hostnames = [host.name for host in task_hosts]
            assert sorted(hostnames) == ['remote1.example.com',
                                         'remote2.example.com']

    @patch.object(Task, 'setup')
    def test_setup_called(self, m_setup):
        task_config = dict()
        with Task(self.ctx, task_config):
            m_setup.assert_called_once_with()

    @patch.object(Task, 'begin')
    def test_begin_called(self, m_begin):
        task_config = dict()
        with Task(self.ctx, task_config):
            m_begin.assert_called_once_with()

    @patch.object(Task, 'end')
    def test_end_called(self, m_end):
        task_config = dict()
        with Task(self.ctx, task_config):
            pass
        m_end.assert_called_once_with()

    @patch.object(Task, 'teardown')
    def test_teardown_called(self, m_teardown):
        task_config = dict()
        with Task(self.ctx, task_config):
            pass
        m_teardown.assert_called_once_with()

    def test_skip_teardown(self):
        task_config = dict(
            skip_teardown=True,
        )

        def fake_teardown(self):
            assert False

        with patch.object(Task, 'teardown', fake_teardown):
            with Task(self.ctx, task_config):
                pass


text:
<resources>
    <item name="bgload" type="color">#282B30</item>
    <item name="bgmain" type="color">#F5F5F5</item>
    <item name="bgfiat" type="color">#2AA3A3</item>
    <item name="bgbar" type="color">#000000</item>
    <item name="btc" type="color">#E68A00</item>
    <item name="ln" type="color">#0099FE</item>

    <item name="fabtext" type="color">#FFFFFF</item>
    <item name="fabbgnormal" type="color">#333333</item>
    <item name="fabbgpressed" type="color">#444444</item>
    <item name="fabbgripple" type="color">#66FFFFFF</item>
    <item name="reddish" type="color">#E31300</item>

    <color name="simpletooltip_text">#FFFFFF</color>
    <color name="simpletooltip_background">#FFB20D</color>
    <color name="simpletooltip_arrow">#FFB20D</color>

    <color name="chip_default_text_color">#DE000000</color>
    <color name="chip_default_icon_background_color">#517FA4</color>

    <color name="transparent">#00000000</color>
    <color name="pressed_color">#E7E7E7</color>
    <color name="left_action_icon">#787878</color>
    <color name="clear_btn_color">#787878</color>
    <color name="background">#FFFFFF</color>
    <color name="hint_color">#808080</color>
    <color name="dark_gray">#787878</color>
</resources>


text:
<!DOCTYPE html>

  <title>Sage</title>
<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="dist/css/bootstrap.css">
	<link rel="stylesheet" href="dist/css/custom.css">

<link rel="stylesheet" href="css/custom.css">

Home

2011 Mustang GT Premium.

Upgraded parts.

	Accel Super Coil On Plug Kit - Yellow (11-Early 16 GT, BOSS 302)

	Flowmaster 40 Delta Flow Mufflers.

	Foose Nitrous F201 Wheels.

	Escort Passport 9500ix

		Scroll down for additional information.

      Previous

      Next

jk, ill get to that later


text:
package flow.sample.multikey;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import flow.Direction;
import flow.Flow;
import flow.KeyChanger;
import flow.KeyDispatcher;
import flow.State;
import flow.TraversalCallback;
import java.util.Map;

/**
 * Demonstrates MultiKeys, e.g. screens with dialogs.
 */
public class MultiKeySampleActivity extends AppCompatActivity {
  @Override protected void attachBaseContext(Context baseContext) {
    baseContext = Flow.configure(baseContext, this)
        .dispatcher(KeyDispatcher.configure(this, new Changer()).build())
        .defaultKey(new ScreenOne())
        .install();
    super.attachBaseContext(baseContext);
  }

  @Override public void onBackPressed() {
    if (!getFlow().goBack()) {
      super.onBackPressed();
    }
  }

  private final class Changer implements KeyChanger {
    Dialog visibleDialog;

    @Override public void changeKey(@Nullable State outgoingState, @NonNull State incomingState,
        @NonNull Direction direction, @NonNull Map<Object, Context> incomingContexts,
        @NonNull TraversalCallback callback) {

      final Object mainKey;
      final Object dialogKey;

      final Object showThis = incomingState.getKey();
      if (showThis instanceof DialogScreen) {
        mainKey = ((DialogScreen) showThis).mainContent;
        dialogKey = showThis;
      } else {
        mainKey = showThis;
        dialogKey = null;
      }

      final TextView mainView = new TextView(incomingContexts.get(mainKey));
      if (mainKey instanceof ScreenOne) {
        mainView.setOnClickListener(new View.OnClickListener() {
          @Override public void onClick(View view) {
            getFlow().set(new DialogScreen(mainKey));
          }
        });
      } else {
        mainView.setOnClickListener(new View.OnClickListener() {
          @Override public void onClick(View view) {
            getFlow().set(new ScreenOne());
          }
        });
      }
      mainView.setText(mainKey.toString());

      setContentView(mainView);

      dismissOldDialog();
      if (dialogKey != null) {
        visibleDialog = new AlertDialog.Builder(incomingContexts.get(dialogKey)) //
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
              @Override public void onClick(DialogInterface dialogInterface, int i) {
                getFlow().goBack();
              }
            }) //
            .setOnCancelListener(new DialogInterface.OnCancelListener() {
              @Override public void onCancel(DialogInterface dialogInterface) {
                getFlow().goBack();
              }
            }) //
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
              @Override public void onClick(DialogInterface dialogInterface, int i) {
                getFlow().set(new ScreenTwo());

                // In real life you'd be more likely to do something like this,
                // to prevent the dialog from showing up again when the back
                // button is hit.
                //
                //final History.Builder newHistory = getFlow().getHistory().buildUpon();
                //newHistory.pop(); // drop the dialog
                //newHistory.push(new ScreenTwo());
                //getFlow().setHistory(newHistory.build(), Flow.Direction.FORWARD);
              }
            }) //
            .setTitle(dialogKey.toString()) //
            .show();

        // Prevent logging of android.view.WindowLeaked.
        getApplication().registerActivityLifecycleCallbacks(new ActivityLifecycleCallbackAdapter() {
          @Override public void onActivityDestroyed(Activity activity) {
            getApplication().unregisterActivityLifecycleCallbacks(this);
            dismissOldDialog();
          }
        });
      }

      callback.onTraversalCompleted();
    }

    private void dismissOldDialog() {
      if (visibleDialog != null) {
        visibleDialog.dismiss();
        visibleDialog = null;
      }
    }
  }

  private Flow getFlow() {
    return Flow.get(MultiKeySampleActivity.this);
  }
}


text:
<!doctype html>
<html lang="en">
<head>
<title>End2end Test Runner</title>
<meta charset="utf-8">
<base href="../..">
<script src="app/lib/angular/angular-scenario.js" ng-autotest></script>
<script src="test/e2e/scenarios.js"></script>
</head>
<body>
</body>
</html>


text:
using DataCore.Test.Models;
using System;
using System.Linq;
using NUnit.Framework;

namespace DataCore.Test
{
    [TestFixture]
    public class DatabaseCheckedTest
    {
        [Test, TestCaseSource(typeof(SqlTestDataFactory), nameof(SqlTestDataFactory.TestCases))]
        public void CanCreateAndDropDatabase(TestHelper.DatabaseType dbType, string connectionString)
        {
            using (var db = TestHelper.GetDatabaseFor(dbType, connectionString))
            {
                db.DropDatabaseIfExists("test_db");
                db.CreateDatabaseIfNotExists("test_db");
                db.CreateDatabaseIfNotExists("test_db");
                db.DropDatabaseIfExists("test_db");
            }
        }

        [Test, TestCaseSource(typeof(SqlTestDataFactory), nameof(SqlTestDataFactory.TestCases))]
        public void CanCreateTable(TestHelper.DatabaseType dbType, string connectionString)
        {
            using (var database = TestHelper.GetDatabaseFor(dbType, connectionString))
            {
                database.CreateTableIfNotExists<TestClass>();

                var query = database.From<TestClass>().Where(t => t.Id == 1);

                database.Select(query);
            }
        }

        [Test, TestCaseSource(typeof(SqlTestDataFactory), nameof(SqlTestDataFactory.TestCases))]
        public void CanCreateTables(TestHelper.DatabaseType dbType, string connectionString)
        {
            using (var database = TestHelper.GetDatabaseFor(dbType, connectionString))
            {
                database.CreateTablesIfNotExists(typeof(TestClass), typeof(TestClass2));

                var query = database.From<TestClass>().Where(t => t.Id == 1);
                database.Select(query);

                var query2 = database.From<TestClass2>().Where(t => t.Id == 1);
                database.Select(query2);
            }
        }

        [Test, TestCaseSource(typeof(SqlTestDataFactory), nameof(SqlTestDataFactory.TestCases))]
        public void CanCreateTableWithOverridedName(TestHelper.DatabaseType dbType, string connectionString)
        {
            using (var database = TestHelper.GetDatabaseFor(dbType, connectionString))
            {
                database.CreateTableIfNotExists<TestOverride>();

                var query = database.From<TestOverride>().Where(t => t.Id == 1);

                database.Select(query);
            }
        }

        [Test, TestCaseSource(typeof(SqlTestDataFactory), nameof(SqlTestDataFactory.TestCases))]
        public void CanCreateTableWithoutIgnoredAttributes(TestHelper.DatabaseType dbType, string connectionString)
        {
            using (var database = TestHelper.GetDatabaseFor(dbType, connectionString))
            {
                database.CreateTableIfNotExists<TestIgnore>();

                var query = database.From<TestIgnore>().Where(t => t.Ignored == "exception!");

                Assert.Throws(Is.InstanceOf<Exception>(), () => database.Select(query));
            }
        }

        [Test, TestCaseSource(typeof(SqlTestDataFactory), nameof(SqlTestDataFactory.TestCases))]
        public void CanCreateTableWithIdentity(TestHelper.DatabaseType dbType, string connectionString)
        {
            using (var database = TestHelper.GetDatabaseFor(dbType, connectionString))
            {
                database.CreateTableIfNotExists<TestClass>();

                database.Insert(TestHelper.GetNewTestClass(0));
                database.Insert(TestHelper.GetNewTestClass(0));

                var result = database.SelectById<TestClass>(1, 2);

                Assert.AreEqual(2, result.Count());
            }
        }

        [Test, TestCaseSource(typeof(SqlTestDataFactory), nameof(SqlTestDataFactory.TestCases))]
        public void DoNotErrorOnDoubleCreateTable(TestHelper.DatabaseType dbType, string connectionString)
        {
            using (var database = TestHelper.GetDatabaseFor(dbType, connectionString))
            {
                database.CreateTableIfNotExists<TestClass>();
                database.CreateTableIfNotExists<TestClass>();

                var query = database.From<TestClass>().Where(t => t.Id == 1);

                database.Select(query);
            }
        }

        [Test, TestCaseSource(typeof(SqlTestDataFactory), nameof(SqlTestDataFactory.TestCasesNoSqlite))]
        public void CanCreateTableWithReferences(TestHelper.DatabaseType dbType, string connectionString)
        {
            using (var database = TestHelper.GetDatabaseFor(dbType, connectionString))
            {
                database.CreateTableIfNotExists<TestClassRef1>();
                database.CreateTableIfNotExists<TestClassRef2>(true);

                database.DropForeignKeyIfExists<TestClassRef2>("FK_TestClassRef2");
            }
        }

        [Test, TestCaseSource(typeof(SqlTestDataFactory), nameof(SqlTestDataFactory.TestCases))]
        public void CanCreateTableIndex(TestHelper.DatabaseType dbType, string connectionString)
        {
            using (var database = TestHelper.GetDatabaseFor(dbType, connectionString))
            {
                database.CreateTableIfNotExists<TestClassRef1>();

                database.DropIndexIfExists<TestClassRef1>("IX_TestClassRef1_Id2");
                database.DropIndexIfExists<TestClassRef1>("IX_TestTest");
            }
        }

        [Test, TestCaseSource(typeof(SqlTestDataFactory), nameof(SqlTestDataFactory.TestCases))]
        public void CanDropTable(TestHelper.DatabaseType dbType, string connectionString)
        {
            using (var database = TestHelper.GetDatabaseFor(dbType, connectionString))
            {
                database.CreateTableIfNotExists<TestClass>();

                database.Select(database.From<TestClass>().Where(t => t.Id == 1));

                database.DropTableIfExists<TestClass>();
            }
        }

        [Test, TestCaseSource(typeof(SqlTestDataFactory), nameof(SqlTestDataFactory.TestCases))]
        public void CanDropTables(TestHelper.DatabaseType dbType, string connectionString)
        {
            using (var database = TestHelper.GetDatabaseFor(dbType, connectionString))
            {
                database.CreateTablesIfNotExists(typeof(TestClass), typeof(TestClass2));

                database.Select(database.From<TestClass>().Where(t => t.Id == 1));
                database.Select(database.From<TestClass2>().Where(t => t.Id == 1));

                database.DropTablesIfExists(typeof(TestClass), typeof(TestClass2));
            }
        }

        [Test, TestCaseSource(typeof(SqlTestDataFactory), nameof(SqlTestDataFactory.TestCases))]
        public void CanCreateColumn(TestHelper.DatabaseType dbType, string connectionString)
        {
            using (var database = TestHelper.GetDatabaseFor(dbType, connectionString))
            {
                var translator = database.Translator;

                var tableDefinition = new TableDefinition(typeof(TestClass4));

                var textInt = translator.GetTextFor(tableDefinition.Fields.First(f => f.Name == "Id"));
                var textString = translator.GetTextFor(tableDefinition.Fields.First(f => f.Name == "Name"));

                database.Execute("CREATE TABLE TestClass4 ( Id " + textInt + " not null, FormatNumber " + textInt + " not null, Name " + textString + "(250) not null )");

                database.CreateColumnIfNotExists<TestClass4>(t => t.InsertDate);

                var date = DateTime.Now;

                var query = database.From<TestClass4>().Where(t => t.InsertDate == date);

                database.Select(query);

                database.DropTableIfExists<TestClass4>();
            }
        }

        [Test, TestCaseSource(typeof(SqlTestDataFactory), nameof(SqlTestDataFactory.TestCasesNoSqlite))]
        public void CanDropColumn(TestHelper.DatabaseType dbType, string connectionString)
        {
            using (var database = TestHelper.GetDatabaseFor(dbType, connectionString))
            {
                database.CreateTableIfNotExists<TestClass>();

                database.DropColumnIfExists<TestClass>(t => t.Name);
            }
        }

        [Test, TestCaseSource(typeof(SqlTestDataFactory), nameof(SqlTestDataFactory.TestCases))]
        public void CanCreateIndex(TestHelper.DatabaseType dbType, string connectionString)
        {
            using (var database = TestHelper.GetDatabaseFor(dbType, connectionString))
            {
                database.CreateTableIfNotExists<TestClass>();

                database.CreateIndexIfNotExists<TestClass>(t => new { t.Id, t.Name }, true);
            }
        }

        [Test, TestCaseSource(typeof(SqlTestDataFactory), nameof(SqlTestDataFactory.TestCases))]
        public void CanDropIndex(TestHelper.DatabaseType dbType, string connectionString)
        {
            const string indexName = "IX_TestClass_Id_Name";

            using (var database = TestHelper.GetDatabaseFor(dbType, connectionString))
            {
                database.CreateTableIfNotExists<TestClass>();

                database.CreateIndexIfNotExists<TestClass>(t => new { t.Id, t.Name }, true, indexName);
                database.DropIndexIfExists<TestClass>(indexName);
            }
        }

        [Test, TestCaseSource(typeof(SqlTestDataFactory), nameof(SqlTestDataFactory.TestCases))]
        public void CanCreateForeignKey(TestHelper.DatabaseType dbType, string connectionString)
        {
            using (var database = TestHelper.GetDatabaseFor(dbType, connectionString))
            {
                database.CreateTableIfNotExists<TestClass>();
                database.CreateTableIfNotExists<TestClass2>();

                database.CreateForeignKeyIfNotExists<TestClass, TestClass2>(t => t.TestClass2Id, t => t.Id);
            }
        }

        [Test, TestCaseSource(typeof(SqlTestDataFactory), nameof(SqlTestDataFactory.TestCasesNoSqlite))]
        public void CanDropForeignKey(TestHelper.DatabaseType dbType, string connectionString)
        {
            const string indexName = "FK_TestClass_Id";

            using (var database = TestHelper.GetDatabaseFor(dbType, connectionString))
            {
                database.CreateTableIfNotExists<TestClass>();
                database.CreateTableIfNotExists<TestClass2>();

                database.CreateForeignKeyIfNotExists<TestClass, TestClass2>(t => t.TestClass2Id, t => t.Id, indexName);
                database.DropForeignKeyIfExists<TestClass>(indexName);
            }
        }

        [Test, TestCaseSource(typeof(SqlTestDataFactory), nameof(SqlTestDataFactory.TestCases))]
        public void CanCreateTableNoReference(TestHelper.DatabaseType dbType, string connectionString)
        {
            using (var database = TestHelper.GetDatabaseFor(dbType, connectionString))
            {
                database.CreateTableIfNotExists<TestClassNoReference>();
                database.Insert(new TestClassNoReference { Id = 1 });

                var result = database.SelectById<TestClassNoReference>(1);

                Assert.That(result, Is.Not.Null);
                Assert.That(result.Ref, Is.Null);
            }
        }

        [Test, TestCaseSource(typeof(SqlTestDataFactory), nameof(SqlTestDataFactory.TestCasesNoOracle))]
        public void CanCreateTableOnlyIdentityColumn(TestHelper.DatabaseType dbType, string connectionString)
        {
            using (var database = TestHelper.GetDatabaseFor(dbType, connectionString))
            {
                database.CreateTableIfNotExists<TestClassOnlyIdentity>();

                database.Insert(new TestClassOnlyIdentity());
            }
        }

        [Test, TestCaseSource(typeof(SqlTestDataFactory), nameof(SqlTestDataFactory.TestCases))]
        public void CanCreateTableWithNullProperty(TestHelper.DatabaseType dbType, string connectionString)
        {
            using (var database = TestHelper.GetDatabaseFor(dbType, connectionString))
            {
                database.CreateTableIfNotExists<TestNullableProperty>();

                database.Insert(new TestNullableProperty { Id = 1 });

                var result = database.SelectById<TestNullableProperty>(1);

                Assert.That(result, Is.Not.Null);
                Assert.That(result.Id, Is.EqualTo(1));
                Assert.That(result.IdMaybe, Is.Null);
            }
        }
    }
}


text:
using namespace boost::python;

namespace  {

struct Magick_DrawableAffine_Wrapper: Magick::DrawableAffine
{
    Magick_DrawableAffine_Wrapper(PyObject* py_self_, double p0, double p1, double p2, double p3, double p4, double p5):
        Magick::DrawableAffine(p0, p1, p2, p3, p4, p5), py_self(py_self_) {}

    Magick_DrawableAffine_Wrapper(PyObject* py_self_):
        Magick::DrawableAffine(), py_self(py_self_) {}

    PyObject* py_self;
};

}

void __DrawableAffine()
{
    class_< Magick::DrawableAffine, bases<Magick::DrawableBase>, boost::noncopyable, Magick_DrawableAffine_Wrapper >("DrawableAffine", init<  >())
        .def(init< double, double, double, double, double, double >())
        .def("sx", (void (Magick::DrawableAffine::*)(const double) )&Magick::DrawableAffine::sx)
        .def("sx", (double (Magick::DrawableAffine::*)() const)&Magick::DrawableAffine::sx)
        .def("sy", (void (Magick::DrawableAffine::*)(const double) )&Magick::DrawableAffine::sy)
        .def("sy", (double (Magick::DrawableAffine::*)() const)&Magick::DrawableAffine::sy)
        .def("rx", (void (Magick::DrawableAffine::*)(const double) )&Magick::DrawableAffine::rx)
        .def("rx", (double (Magick::DrawableAffine::*)() const)&Magick::DrawableAffine::rx)
        .def("ry", (void (Magick::DrawableAffine::*)(const double) )&Magick::DrawableAffine::ry)
        .def("ry", (double (Magick::DrawableAffine::*)() const)&Magick::DrawableAffine::ry)
        .def("tx", (void (Magick::DrawableAffine::*)(const double) )&Magick::DrawableAffine::tx)
        .def("tx", (double (Magick::DrawableAffine::*)() const)&Magick::DrawableAffine::tx)
        .def("ty", (void (Magick::DrawableAffine::*)(const double) )&Magick::DrawableAffine::ty)
        .def("ty", (double (Magick::DrawableAffine::*)() const)&Magick::DrawableAffine::ty)
    ;
}


text:
var Task = (function () {
    function Task(id, name, desc, status, fromNpcID, toNpcId) {
        this.id = id;
        this.name = name;
        this.desc = desc;
        this.status = status;
        this.fromNpcId = fromNpcID;
        this.toNpcId = toNpcId;
    }
    var d = __define,c=Task,p=c.prototype;
    p.onAccept = function (task) {
    };
    p.onSubmit = function (task) {
    };
    p.checkStatus = function () {
    };
    return Task;
}());
egret.registerClass(Task,'Task');
var TaskStatus;
(function (TaskStatus) {
    TaskStatus[TaskStatus["UNACCEPTABLE"] = 0] = "UNACCEPTABLE";
    TaskStatus[TaskStatus["ACCEPTABLE"] = 1] = "ACCEPTABLE";
    TaskStatus[TaskStatus["DURING"] = 2] = "DURING";
    TaskStatus[TaskStatus["CAN_SUBMIT"] = 3] = "CAN_SUBMIT";
    TaskStatus[TaskStatus["SUBMITTED"] = 4] = "SUBMITTED";
})(TaskStatus || (TaskStatus = {}));
//# sourceMappingURL=Task.js.map


text:
<?php

declare(strict_types=1);

namespace Broadway\EventSourcing;

use Broadway\Domain\DomainEventStream;

/**
 * Interface implemented by event stream decorators.
 *
 * An event stream decorator can alter the domain event stream before it is
 * written. An example would be adding metadata before writing the events to
 * storage.
 */
interface EventStreamDecorator
{
    /**
     * @param string            $aggregateType
     * @param string            $aggregateIdentifier
     * @param DomainEventStream $eventStream
     *
     * @return DomainEventStream
     */
    public function decorateForWrite(string $aggregateType, string $aggregateIdentifier, DomainEventStream $eventStream): DomainEventStream;
}


text:
namespace ndnboost { namespace mpl {

template<
      typename Tag1
    , typename Tag2

    , NDNBOOST_MPL_AUX_NTTP_DECL(int, tag1_)  = NDNBOOST_MPL_AUX_MSVC_VALUE_WKND(Tag1)::value
    , NDNBOOST_MPL_AUX_NTTP_DECL(int, tag2_)  = NDNBOOST_MPL_AUX_MSVC_VALUE_WKND(Tag2)::value
    >
struct less_equal_impl
    : if_c<
          ( tag1_ > tag2_ )
        , aux::cast2nd_impl< less_equal_impl< Tag1,Tag1 >,Tag1, Tag2 >
        , aux::cast1st_impl< less_equal_impl< Tag2,Tag2 >,Tag1, Tag2 >
        >::type
{
};

/// for Digital Mars C++/compilers with no CTPS/TTP support
template<> struct less_equal_impl< na,na >
{
    template< typename U1, typename U2 > struct apply
    {
        typedef apply type;
        NDNBOOST_STATIC_CONSTANT(int, value  = 0);
    };
};

template<> struct less_equal_impl< na,integral_c_tag >
{
    template< typename U1, typename U2 > struct apply
    {
        typedef apply type;
        NDNBOOST_STATIC_CONSTANT(int, value  = 0);
    };
};

template<> struct less_equal_impl< integral_c_tag,na >
{
    template< typename U1, typename U2 > struct apply
    {
        typedef apply type;
        NDNBOOST_STATIC_CONSTANT(int, value  = 0);
    };
};

template< typename T > struct less_equal_tag
    : tag< T,na >
{
};

template<
      typename NDNBOOST_MPL_AUX_NA_PARAM(N1)
    , typename NDNBOOST_MPL_AUX_NA_PARAM(N2)
    >
struct less_equal
    : aux::msvc_eti_base< typename apply_wrap2<
          less_equal_impl<
              typename less_equal_tag<N1>::type
            , typename less_equal_tag<N2>::type
            >
        , N1
        , N2
        >::type >::type

{
    NDNBOOST_MPL_AUX_LAMBDA_SUPPORT(2, less_equal, (N1, N2))

};

NDNBOOST_MPL_AUX_NA_SPEC2(2, 2, less_equal)

}}

namespace ndnboost { namespace mpl {

template<>
struct less_equal_impl< integral_c_tag,integral_c_tag >
{
    template< typename N1, typename N2 > struct apply

    {
        NDNBOOST_STATIC_CONSTANT(bool, value =
             ( NDNBOOST_MPL_AUX_VALUE_WKND(N1)::value <=
             NDNBOOST_MPL_AUX_VALUE_WKND(N2)::value )
            );
        typedef bool_<value> type;
    };
};

}}


text:
import { HTTP } from 'meteor/http';

var config = require("../config.js");
var collection = require("../../collection/collection.js");
var Info = collection.info;

exports.getinfo = function(code){
    var oauth2_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' + config.appID + '&secret=' + config.appsecret + '&code=' + code + '&grant_type=authorization_code';
    var oauth2_result = HTTP.get(oauth2_url);
    var oauth2_data = JSON.parse(oauth2_result.content);
    var openid = oauth2_data.openid;
    var access_token = oauth2_data.access_token;

    var userinfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid;
    var userinfo_result = HTTP.get(userinfo_url);
    var userinfo_data = JSON.parse(userinfo_result.content);

    if(!Info.findOne({openid : openid}))
      {
        var uid = getinfoJS.num_user();
        var user_info = {};
        user_info.uid = uid;
        user_info.openid = openid;
        user_info.country = userinfo_data.country;
        user_info.province = userinfo_data.province;
        user_info.city = userinfo_data.city;
        user_info.nickname = userinfo_data.nickname;
        user_info.headimgurl = userinfo_data.headimgurl;
        user_info.qr = userqrJS.createqr(uid);
        Info.insert(user_info);
      };

      return 0;
}

exports.getopenid = function(code) {
    var oauth2_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' + config.appID + '&secret=' + config.appsecret + '&code=' + code + '&grant_type=authorization_code';
    var oauth2_result = HTTP.get(oauth2_url);
    var oauth2_data = JSON.parse(oauth2_result.content);
    return oauth2_data.openid;
}

exports.person_info = function(name) {
    return Info.findOne({nickname : name});
}

exports.getname = function(popenid) {
    var selper = Info.findOne({openid : popenid});
    return selper.nickname;
}

exports.num_user = function() {
    return Info.find().count();
}


text:
package com.grumoon.volleydemo.util;

import android.content.Context;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

public class VolleyUtil {

	private volatile static RequestQueue requestQueue;

	/** 返回RequestQueue单例 **/
	public static RequestQueue getQueue(Context context) {
		if (requestQueue == null) {
			synchronized (VolleyUtil.class) {
				if (requestQueue == null) {
					requestQueue = Volley.newRequestQueue(context.getApplicationContext());
				}
			}
		}
		return requestQueue;
	}
}


text:
//
//  ASDisplayNode+Deprecated.h
//  AsyncDisplayKit
//
//  Copyright (c) 2014-present, Facebook, Inc.  All rights reserved.
//  This source code is licensed under the BSD-style license found in the
//  LICENSE file in the root directory of this source tree. An additional grant
//  of patent rights can be found in the PATENTS file in the same directory.
//

#pragma once

#import "ASDisplayNode.h"

@interface ASDisplayNode (Deprecated)

/**
 * @abstract The name of this node, which will be displayed in `description`. The default value is nil.
 *
 * @deprecated Deprecated in version 2.0: Use .debugName instead. This value will display in
 * results of the -asciiArtString method (@see ASLayoutElementAsciiArtProtocol).
 */
@property (nullable, nonatomic, copy) NSString *name ASDISPLAYNODE_DEPRECATED_MSG("Use .debugName instead.");

/**
 * @abstract Provides a default intrinsic content size for calculateSizeThatFits:. This is useful when laying out
 * a node that either has no intrinsic content size or should be laid out at a different size than its intrinsic content
 * size. For example, this property could be set on an ASImageNode to display at a size different from the underlying
 * image size.
 *
 * @return Try to create a CGSize for preferredFrameSize of this node from the width and height property of this node. It will return CGSizeZero if width and height dimensions are not of type ASDimensionUnitPoints.
 *
 * @deprecated Deprecated in version 2.0: Just calls through to set the height and width property of the node. Convert to use sizing properties instead: height, minHeight, maxHeight, width, minWidth, maxWidth.
 */
@property (nonatomic, assign, readwrite) CGSize preferredFrameSize ASDISPLAYNODE_DEPRECATED_MSG("Use .style.preferredSize instead OR set individual values with .style.height and .style.width.");

/**
 * @abstract Asks the node to measure and return the size that best fits its subnodes.
 *
 * @param constrainedSize The maximum size the receiver should fit in.
 *
 * @return A new size that fits the receiver's subviews.
 *
 * @discussion Though this method does not set the bounds of the view, it does have side effects--caching both the
 * constraint and the result.
 *
 * @warning Subclasses must not override this; it calls -measureWithSizeRange: with zero min size.
 * -measureWithSizeRange: caches results from -calculateLayoutThatFits:.  Calling this method may
 * be expensive if result is not cached.
 *
 * @see measureWithSizeRange:
 * @see [ASDisplayNode(Subclassing) calculateLayoutThatFits:]
 *
 * @deprecated Deprecated in version 2.0: Use layoutThatFits: with a constrained size of (CGSizeZero, constrainedSize) and call size on the returned ASLayout
 */
- (CGSize)measure:(CGSize)constrainedSize ASDISPLAYNODE_DEPRECATED_MSG("Use layoutThatFits: with a constrained size of (CGSizeZero, constrainedSize) and call size on the returned ASLayout.");

ASLayoutElementStyleForwardingDeclaration

/**
 * @abstract Called whenever the visiblity of the node changed.
 *
 * @discussion Subclasses may use this to monitor when they become visible.
 *
 * @deprecated @see didEnterVisibleState @see didExitVisibleState
 */
- (void)visibilityDidChange:(BOOL)isVisible ASDISPLAYNODE_REQUIRES_SUPER ASDISPLAYNODE_DEPRECATED_MSG("Use -didEnterVisibleState / -didExitVisibleState instead.");

/**
 * @abstract Called whenever the visiblity of the node changed.
 *
 * @discussion Subclasses may use this to monitor when they become visible.
 *
 * @deprecated @see didEnterVisibleState @see didExitVisibleState
 */
- (void)visibleStateDidChange:(BOOL)isVisible ASDISPLAYNODE_REQUIRES_SUPER ASDISPLAYNODE_DEPRECATED_MSG("Use -didEnterVisibleState / -didExitVisibleState instead.");

/**
 * @abstract Called whenever the the node has entered or exited the display state.
 *
 * @discussion Subclasses may use this to monitor when a node should be rendering its content.
 *
 * @note This method can be called from any thread and should therefore be thread safe.
 *
 * @deprecated @see didEnterDisplayState @see didExitDisplayState
 */
- (void)displayStateDidChange:(BOOL)inDisplayState ASDISPLAYNODE_REQUIRES_SUPER ASDISPLAYNODE_DEPRECATED_MSG("Use -didEnterDisplayState / -didExitDisplayState instead.");

/**
 * @abstract Called whenever the the node has entered or left the load state.
 *
 * @discussion Subclasses may use this to monitor data for a node should be loaded, either from a local or remote source.
 *
 * @note This method can be called from any thread and should therefore be thread safe.
 *
 * @deprecated @see didEnterPreloadState @see didExitPreloadState
 */
- (void)loadStateDidChange:(BOOL)inLoadState ASDISPLAYNODE_REQUIRES_SUPER ASDISPLAYNODE_DEPRECATED_MSG("Use -didEnterPreloadState / -didExitPreloadState instead.");

/**
 * @abstract Cancels all performing layout transitions. Can be called on any thread.
 *
 * @deprecated Deprecated in version 2.0: Use cancelLayoutTransition
 */
- (void)cancelLayoutTransitionsInProgress ASDISPLAYNODE_DEPRECATED_MSG("Use -cancelLayoutTransition instead.");

/**
 * @abstract A boolean that shows whether the node automatically inserts and removes nodes based on the presence or
 * absence of the node and its subnodes is completely determined in its layoutSpecThatFits: method.
 *
 * @discussion If flag is YES the node no longer require addSubnode: or removeFromSupernode method calls. The presence
 * or absence of subnodes is completely determined in its layoutSpecThatFits: method.
 *
 * @deprecated Deprecated in version 2.0: Use automaticallyManagesSubnodes
 */
@property (nonatomic, assign) BOOL usesImplicitHierarchyManagement ASDISPLAYNODE_DEPRECATED_MSG("Set .automaticallyManagesSubnodes instead.");

@end


text:
import { Routes, RouterModule } from '@angular/router';

export const routes: Routes = [
  { path: '', redirectTo: 'auth/signin', pathMatch: 'full' },
  // { path: 'auth', redirectTo: 'auth/signin'},
  { path: 'mahasiswa', redirectTo: 'mahasiswa/dashboard'},
  { path: 'dosen', redirectTo: 'dosen/dashboard'},
  { path: 'admin', redirectTo: 'admin/dashboard'},
  // { path: '**', redirectTo: 'mahasiswa' }
];

export const routing = RouterModule.forRoot(routes, { useHash: true });


text:
<?php

namespace League\Uri\Modifiers;

use League\Uri\Interfaces\Uri;
use League\Uri\Types\ValidatorTrait;
use Psr\Http\Message\UriInterface;

/**
 * Abstract Class for all pipeline
 *
 * @package League.uri
 * @author  Ignace Nyamagana Butera <nyamsprod@gmail.com>
 * @since   4.0.0
 */
abstract class AbstractUriModifier
{
    use ValidatorTrait;

    /**
     * Return a Uri object modified according to the modifier
     *
     * @param Uri|UriInterface $payload
     *
     * @return Uri|UriInterface
     */
    abstract public function __invoke($payload);
}


text:
Param(
  [Parameter(Mandatory=$true)]  [string]$subscriptionId,
  [Parameter(Mandatory=$false)] [string]$region            = "eastasia",
  [Parameter(Mandatory=$false)] [string]$resourceGroupName = "pslibtestosprofile",
  [Parameter(Mandatory=$false)] [string]$keyVaultName      = "pslibtestkeyvault"
)
$PfxCertifcate = ""
$PfxCertifcatePassword = "[PLACEHOLDER]"

Switch-AzureMode AzureResourceManager
Select-AzureSubscription -SubscriptionId $subscriptionId
New-AzureResourceGroup -Name $resourceGroupName -Location $region
$keyVault = New-AzureKeyVault -ResourceGroupName $resourceGroupName -Location $region -VaultName $keyVaultName -EnabledForDeployment

$CertificateJson = @"
{
  "data":     "$PfxCertifcate",
  "dataType": "pfx",
  "password": "$PfxCertifcatePassword"
}
"@

$CertificateBytes = [System.Text.Encoding]::UTF8.GetBytes($CertificateJson)
$JsonEncodedCertificate = [System.Convert]::ToBase64String($CertificateBytes)
$secret = ConvertTo-SecureString -String $JsonEncodedCertificate -AsPlainText -Force
$secretName = "WinRM"
$secret = Set-AzureKeyVaultSecret -VaultName $keyVaultName -Name $secretName -SecretValue $secret

Write-Host "Please Use the values below during recording:"
Write-Host
Write-Host -ForegroundColor Green "KeyVaultId: " $keyVault.ResourceId
Write-Host
Write-Host -ForegroundColor Green "CertificateUrl: " $secret.Id
Write-Host
Write-Host
Write-Host "After recording completes, Please  delete the whole resource group which contains the key vault, using the following command"
Write-Host -ForegroundColor Yellow  "  Remove-AzureResourceGroup -Name $resourceGroupName "


text:
<!doctype html>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<iframe id="i" src="/common/blank.html"></iframe>
<script>
promise_test(async t => {
  await new Promise(resolve => window.onload = resolve);
  i.contentWindow.navigation.oncurrententrychange = t.unreached_func("currententrychange should not fire for cross-document navigations");
  i.contentWindow.navigation.navigate("/common/blank.html?1");
  await new Promise(resolve => i.onload = resolve);
}, "currententrychange does not fire for cross-document navigation.navigate()");
</script>


text:
'use strict';

describe('Admin page header Spec', require('../../../common/tests/specs/header-spec-definition')('Admin'));


text:
package tests

import (
	"testing"
	"time"

	"github.com/networkservicemesh/networkservicemesh/controlplane/api/connection/mechanisms/common"
	"github.com/networkservicemesh/networkservicemesh/controlplane/api/connection/mechanisms/kernel"
	"github.com/networkservicemesh/networkservicemesh/controlplane/api/connection/mechanisms/vxlan"

	. "github.com/onsi/gomega"
	"golang.org/x/net/context"

	"github.com/networkservicemesh/networkservicemesh/controlplane/api/connection"
	"github.com/networkservicemesh/networkservicemesh/controlplane/api/connectioncontext"
	"github.com/networkservicemesh/networkservicemesh/controlplane/api/networkservice"
	"github.com/networkservicemesh/networkservicemesh/controlplane/api/registry"
)

func TestHealLocalForwarder(t *testing.T) {
	g := NewWithT(t)

	storage := NewSharedStorage()
	srv := NewNSMDFullServer(Master, storage)
	srv2 := NewNSMDFullServer(Worker, storage)
	defer srv.Stop()
	defer srv2.Stop()

	srv.TestModel.AddForwarder(context.Background(), testForwarder1)
	srv2.TestModel.AddForwarder(context.Background(), testForwarder2)

	// Register in both
	nseReg := srv2.registerFakeEndpointWithName("golden_network", "test", Worker, "ep1")

	// Add to local endpoints for Server2
	srv2.TestModel.AddEndpoint(context.Background(), nseReg)

	l1 := newTestConnectionModelListener()
	l2 := newTestConnectionModelListener()

	srv.TestModel.AddListener(l1)
	srv2.TestModel.AddListener(l2)

	// Now we could try to connect via Client API
	nsmClient, conn := srv.requestNSMConnection("nsm-1")
	defer conn.Close()

	request := &networkservice.NetworkServiceRequest{
		Connection: &connection.Connection{
			NetworkService: "golden_network",
			Context: &connectioncontext.ConnectionContext{
				IpContext: &connectioncontext.IPContext{
					DstIpRequired: true,
					SrcIpRequired: true,
				},
			},
			Labels: make(map[string]string),
		},
		MechanismPreferences: []*connection.Mechanism{
			{
				Type: kernel.MECHANISM,
				Parameters: map[string]string{
					common.NetNsInodeKey:    "10",
					common.InterfaceNameKey: "icmp-responder1",
				},
			},
		},
	}

	nsmResponse, err := nsmClient.Request(context.Background(), request)
	g.Expect(err).To(BeNil())
	g.Expect(nsmResponse.GetNetworkService()).To(Equal("golden_network"))

	// We need to check for cross connections.
	clientConnection1 := srv.TestModel.GetClientConnection(nsmResponse.GetId())
	g.Expect(clientConnection1.GetID()).To(Equal("1"))
	g.Expect(clientConnection1.Xcon.Destination.Mechanism.GetParameters()[vxlan.SrcIP]).To(Equal("127.0.0.1"))

	clientConnection2 := srv2.TestModel.GetClientConnection(clientConnection1.Xcon.Destination.GetId())
	g.Expect(clientConnection2.GetID()).To(Equal("1"))

	timeout := time.Second * 10

	l1.WaitAdd(1, timeout, t)
	// We need to inform cross connection monitor about this connection, since forwarder is fake one.
	epName := clientConnection1.Endpoint.GetNetworkServiceEndpoint().GetName()
	_, err = srv.nseRegistry.RemoveNSE(context.Background(), &registry.RemoveNSERequest{
		NetworkServiceEndpointName: epName,
	})
	if err != nil {
		t.Fatal("Err must be nil")
	}

	// Simulate forwarder dead
	srv.TestModel.AddForwarder(context.Background(), testForwarder1_1)
	srv.TestModel.DeleteForwarder(context.Background(), testForwarder1.RegisteredName)

	// We need to inform cross connection monitor about this connection, since forwarder is fake one.
	// First update is with down state
	// But we want to wait for Up state
	l1.WaitUpdate(5, timeout, t)
	// We need to inform cross connection monitor about this connection, since forwarder is fake one.

	clientConnection1_1 := srv.TestModel.GetClientConnection(nsmResponse.GetId())
	g.Expect(clientConnection1_1 != nil).To(Equal(true))
	g.Expect(clientConnection1_1.GetID()).To(Equal("1"))
	g.Expect(clientConnection1_1.Xcon.Destination.GetId()).To(Equal("1"))
	g.Expect(clientConnection1_1.Xcon.Destination.GetNetworkServiceEndpointName()).To(Equal(epName))
	g.Expect(clientConnection1_1.Xcon.Destination.GetMechanism().GetParameters()[vxlan.SrcIP]).To(Equal("127.0.0.7"))
}


text:
const eol = require('os').EOL;
import * as chai from 'chai';
import { temporaryDir, shell, pkg, exists, exec, read, shellAsync } from '../helpers';

const expect = chai.expect;
const tmp = temporaryDir();

describe('CLI duplicates support', () => {
    const distFolder = tmp.name + '-duplicates';

    before(done => {
        tmp.create(distFolder);
        let ls = shell('node', [
            './bin/index-cli.js',
            '-p',
            './test/fixtures/todomvc-ng2-duplicates/src/tsconfig.json',
            '-d',
            distFolder
        ]);

        if (ls.stderr.toString() !== '') {
            console.error(`shell error: ${ls.stderr.toString()}`);
            done('error');
        }
        done();
    });
    after(() => tmp.clean(distFolder));

    it('Todo class generated', () => {
        const file = exists(distFolder + '/classes/Todo.html');
        expect(file).to.be.true;
    });

    it('Todo-1 class generated', () => {
        const file = exists(distFolder + '/classes/Todo-1.html');
        expect(file).to.be.true;
    });

    it('Todo-2 class generated', () => {
        const file = exists(distFolder + '/classes/Todo-2.html');
        expect(file).to.be.true;
    });

    it('TimeInterface generated', () => {
        const file = exists(distFolder + '/interfaces/TimeInterface.html');
        expect(file).to.be.true;
    });

    it('TimeInterface-1 generated', () => {
        const file = exists(distFolder + '/interfaces/TimeInterface-1.html');
        expect(file).to.be.true;
    });

    it('EmptyService generated', () => {
        const file = exists(distFolder + '/injectables/EmptyService.html');
        expect(file).to.be.true;
    });

    it('EmptyService-1 generated', () => {
        const file = exists(distFolder + '/injectables/EmptyService-1.html');
        expect(file).to.be.true;
    });

    it('FirstUpperPipe generated', () => {
        const file = exists(distFolder + '/pipes/FirstUpperPipe.html');
        expect(file).to.be.true;
    });

    it('NoopInterceptor generated', () => {
        const file = exists(distFolder + '/interceptors/NoopInterceptor.html');
        expect(file).to.be.true;
    });

    it('NoopInterceptor-1 generated', () => {
        const file = exists(distFolder + '/interceptors/NoopInterceptor-1.html');
        expect(file).to.be.true;
    });

    it('EmptyComponent generated', () => {
        const file = exists(distFolder + '/components/EmptyComponent.html');
        expect(file).to.be.true;
    });

    it('EmptyComponent-1 generated', () => {
        const file = exists(distFolder + '/components/EmptyComponent-1.html');
        expect(file).to.be.true;
    });

    it('DoNothingDirective generated', () => {
        const file = exists(distFolder + '/directives/DoNothingDirective.html');
        expect(file).to.be.true;
    });

    it('DoNothingDirective-1 generated', () => {
        const file = exists(distFolder + '/directives/DoNothingDirective-1.html');
        expect(file).to.be.true;
    });

    it('should support component inside module', () => {
        const file = read(distFolder + '/js/menu-wc.js');
        expect(file).to.contain(
            `<a href="components/ValidationDemo.html" data-type="entity-link" data-context="sub-entity" data-context-id="modules" >ValidationDemo</a>`
        );
    });

    it('should support component inside module with duplicate', () => {
        const file = read(distFolder + '/js/menu-wc.js');
        expect(file).to.contain(
            `<a href="components/FooterComponent.html" data-type="entity-link" data-context="sub-entity" data-context-id="modules" >FooterComponent</a>`
        );
    });

    it('Injectable with multiple decorators should not appear twice', () => {
        let file = exists(distFolder + '/injectables/MyService.html');
        expect(file).to.be.true;
        file = exists(distFolder + '/injectables/MyService-1.html');
        expect(file).to.be.false;
    });
});


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>new (Spec::Mocks::ArgumentExpectation)</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <link rel="stylesheet" href="../../../.././rdoc-style.css" type="text/css" media="screen" />

# File lib/spec/mocks/argument_expectation.rb, line 7
      def initialize(args, &block)
        @args = args
        @constraints_block = block

        if ArgumentConstraints::AnyArgsConstraint === args.first
          @match_any_args = true
        elsif ArgumentConstraints::NoArgsConstraint === args.first
          @constraints = []
        else
          @constraints = args.collect {|arg| constraint_for(arg)}
        end
      end


text:
require "gumbo/logger"
require "gumbo/asset_builder"
require "gumbo/asset_file"
require "gumbo/asset_package"
require "gumbo/package_file"
require "gumbo/java_script_file"
require "gumbo/style_sheet_file"
require "gumbo/compile_to_java_script_file"
require "gumbo/coffee_script_file"
require "gumbo/eco_file"
require "gumbo/template_file"
require "gumbo/liquid_file"
require "gumbo/cli"


text:
namespace device {

typedef HRESULT (WINAPI *NuiGetSensorCountFunc) (int *pCount);
typedef HRESULT (WINAPI *NuiCreateSensorByIndexFunc) (int index, INuiSensor **ppNuiSensor);
typedef HRESULT (WINAPI *NuiImageGetColorPixelCoordinatesFromDepthPixelFunc) (
						NUI_IMAGE_RESOLUTION eColorResolution,
						CONST NUI_IMAGE_VIEW_AREA *pcViewArea,
						LONG   lDepthX, LONG   lDepthY, USHORT usDepthValue,
						LONG *plColorX, LONG *plColorY);

struct KinectFuncs
{
	NuiGetSensorCountFunc								NuiGetSensorCount;
	NuiCreateSensorByIndexFunc							NuiCreateSensorByIndex;
	NuiImageGetColorPixelCoordinatesFromDepthPixelFunc	NuiImageGetColorPixelCoordinatesFromDepthPixel;
};

KinectFuncs *kinect_load_library();
void kinect_free_library();

} // namespace device

#endif


text:
namespace boost {

namespace unit_test {

// ************************************************************************** //
// **************                progress_monitor              ************** //
// ************************************************************************** //

class BOOST_TEST_DECL progress_monitor_t : public test_observer, public singleton<progress_monitor_t> {
public:
    // test observer interface
    void    test_start( counter_t test_cases_amount );
    void    test_finish() {}
    void    test_aborted();

    void    test_unit_start( test_unit const& ) {}
    void    test_unit_finish( test_unit const&, unsigned long );
    void    test_unit_skipped( test_unit const& );
    void    test_unit_aborted( test_unit const& ) {}

    void    assertion_result( bool ) {}
    void    exception_caught( execution_exception const& ) {}

    // configuration
    void    set_stream( std::ostream& );

private:
    BOOST_TEST_SINGLETON_CONS( progress_monitor_t );
}; // progress_monitor_t

BOOST_TEST_SINGLETON_INST( progress_monitor )

} // namespace unit_test

} // namespace boost

//____________________________________________________________________________//

#include <boost/test/detail/enable_warnings.hpp>

// ***************************************************************************
//  Revision History :
//
//  $Log: progress_monitor.hpp,v $
//  Revision 1.4  2006/02/22 16:22:37  rogeeff
//  eliminate warning
//
//  Revision 1.3  2005/12/14 05:11:07  rogeeff
//  dll support introduced
//
//  Revision 1.2  2005/06/24 04:09:34  rogeeff
//  added missing iosfwd
//
//  Revision 1.1  2005/02/20 08:27:06  rogeeff
//  This a major update for Boost.Test framework. See release docs for complete list of fixes/updates
//
// ***************************************************************************

#endif // BOOST_TEST_PROGRESS_MONITOR_HPP_020105GER


text:
from __future__ import absolute_import

import six
from oslo_config import cfg
from bson.objectid import ObjectId

from st2common import log as logging
from st2common.util import date as date_utils
from st2common.util import reference
import st2common.util.action_db as action_utils
from st2common.constants import action as action_constants
from st2common.persistence.execution import ActionExecution
from st2common.persistence.runner import RunnerType
from st2common.persistence.rule import Rule
from st2common.persistence.trigger import TriggerType, Trigger, TriggerInstance
from st2common.models.api.action import RunnerTypeAPI, ActionAPI, LiveActionAPI
from st2common.models.api.rule import RuleAPI
from st2common.models.api.trigger import TriggerTypeAPI, TriggerAPI, TriggerInstanceAPI
from st2common.models.db.execution import ActionExecutionDB
from st2common.runners import utils as runners_utils
from st2common.metrics.base import Timer
from st2common.services import coordination
from six.moves import range

__all__ = [
    "create_execution_object",
    "update_execution",
    "abandon_execution_if_incomplete",
    "is_execution_canceled",
    "AscendingSortedDescendantView",
    "DFSDescendantView",
    "get_descendants",
]

LOG = logging.getLogger(__name__)

# Attributes which are stored in the "liveaction" dictionary when composing LiveActionDB object
# into a ActionExecution compatible dictionary.
# Those attributes are LiveAction specific and are therefore stored in a "liveaction" key
LIVEACTION_ATTRIBUTES = [
    "id",
    "callback",
    "action",
    "action_is_workflow",
    "runner_info",
    "parameters",
    "notify",
]

def _decompose_liveaction(liveaction_db):
    """
    Splits the liveaction into an ActionExecution compatible dict.
    """
    decomposed = {"liveaction": {}}
    liveaction_api = vars(LiveActionAPI.from_model(liveaction_db))
    for k in liveaction_api.keys():
        if k in LIVEACTION_ATTRIBUTES:
            decomposed["liveaction"][k] = liveaction_api[k]
        else:
            decomposed[k] = getattr(liveaction_db, k)
    return decomposed

def _create_execution_log_entry(status, timestamp=None):
    """
    Create execution log entry object for the provided execution status.
    """
    return {
        "timestamp": timestamp or date_utils.get_datetime_utc_now(),
        "status": status,
    }

def create_execution_object(
    liveaction, action_db=None, runnertype_db=None, publish=True
):
    if not action_db:
        action_db = action_utils.get_action_by_ref(liveaction.action)

    if not runnertype_db:
        runnertype_db = RunnerType.get_by_name(action_db.runner_type["name"])

    attrs = {
        "action": vars(ActionAPI.from_model(action_db)),
        "parameters": liveaction["parameters"],
        "runner": vars(RunnerTypeAPI.from_model(runnertype_db)),
    }
    attrs.update(_decompose_liveaction(liveaction))

    if "rule" in liveaction.context:
        rule = reference.get_model_from_ref(Rule, liveaction.context.get("rule", {}))
        attrs["rule"] = vars(RuleAPI.from_model(rule))

    if "trigger_instance" in liveaction.context:
        trigger_instance_id = liveaction.context.get("trigger_instance", {})
        trigger_instance_id = trigger_instance_id.get("id", None)
        trigger_instance = TriggerInstance.get_by_id(trigger_instance_id)
        trigger = reference.get_model_by_resource_ref(
            db_api=Trigger, ref=trigger_instance.trigger
        )
        trigger_type = reference.get_model_by_resource_ref(
            db_api=TriggerType, ref=trigger.type
        )
        trigger_instance = reference.get_model_from_ref(
            TriggerInstance, liveaction.context.get("trigger_instance", {})
        )
        attrs["trigger_instance"] = vars(
            TriggerInstanceAPI.from_model(trigger_instance)
        )
        attrs["trigger"] = vars(TriggerAPI.from_model(trigger))
        attrs["trigger_type"] = vars(TriggerTypeAPI.from_model(trigger_type))

    parent = _get_parent_execution(liveaction)
    if parent:
        attrs["parent"] = str(parent.id)

    attrs["log"] = [_create_execution_log_entry(liveaction["status"])]

    # TODO: This object initialization takes 20-30or so ms
    execution = ActionExecutionDB(**attrs)
    # TODO: Do 100% research this is fully safe and unique in distributed setups
    execution.id = ObjectId()
    execution.web_url = _get_web_url_for_execution(str(execution.id))

    # NOTE: User input data is already validate as part of the API request,
    # other data is set by us. Skipping validation here makes operation 10%-30% faster
    execution = ActionExecution.add_or_update(
        execution, publish=publish, validate=False
    )

    if parent and str(execution.id) not in parent.children:
        values = {}
        values["push__children"] = str(execution.id)
        ActionExecution.update(parent, **values)

    return execution

def _get_parent_execution(child_liveaction_db):
    parent_execution_id = child_liveaction_db.context.get("parent", {}).get(
        "execution_id", None
    )

    if parent_execution_id:
        try:
            return ActionExecution.get_by_id(parent_execution_id)
        except:
            LOG.exception(
                "No valid execution object found in db for id: %s" % parent_execution_id
            )
            return None

    return None

def _get_web_url_for_execution(execution_id):
    base_url = cfg.CONF.webui.webui_base_url
    return "%s/#/history/%s/general" % (base_url, execution_id)

def update_execution(liveaction_db, publish=True, set_result_size=False):
    """
    :param set_result_size: True to calculate size of the serialized result field value and set it
                            on the "result_size" database field.
    """
    execution = ActionExecution.get(liveaction__id=str(liveaction_db.id))

    with coordination.get_coordinator().get_lock(str(liveaction_db.id).encode()):
        # Skip execution object update when action is already in completed state.
        if execution.status in action_constants.LIVEACTION_COMPLETED_STATES:
            LOG.debug(
                "[%s] Action is already in completed state: %s. Skipping execution update to state: %s."
                % (execution.id, execution.status, liveaction_db.status)
            )
            return execution

        decomposed = _decompose_liveaction(liveaction_db)

        kw = {}
        for k, v in six.iteritems(decomposed):
            kw["set__" + k] = v

        if liveaction_db.status != execution.status:
            # Note: If the status changes we store this transition in the "log" attribute of action
            # execution
            kw["push__log"] = _create_execution_log_entry(liveaction_db.status)

        if set_result_size:
            # Sadly with the current ORM abstraction there is no better way to achieve updating
            # result_size and we need to serialize the value again - luckily that operation is fast.
            # To put things into perspective - on 4 MB result dictionary it only takes 7 ms which is
            # negligible compared to other DB operations duration (and for smaller results it takes
            # in sub ms range).
            with Timer(key="action.executions.calculate_result_size"):
                result_size = len(
                    ActionExecutionDB.result._serialize_field_value(
                        liveaction_db.result
                    )
                )
                kw["set__result_size"] = result_size

        execution = ActionExecution.update(execution, publish=publish, **kw)
        return execution

def abandon_execution_if_incomplete(liveaction_id, publish=True):
    """
    Marks execution as abandoned if it is still incomplete. Abandoning an
    execution implies that its end state is unknown and cannot anylonger
    be determined. This method should only be called if the owning process
    is certain it can no longer determine status of an execution.
    """
    liveaction_db = action_utils.get_liveaction_by_id(liveaction_id)

    # No need to abandon and already complete action
    if liveaction_db.status in action_constants.LIVEACTION_COMPLETED_STATES:
        raise ValueError(
            "LiveAction %s already in a completed state %s."
            % (liveaction_id, liveaction_db.status)
        )

    # Update status to reflect execution being abandoned.
    liveaction_db = action_utils.update_liveaction_status(
        status=action_constants.LIVEACTION_STATUS_ABANDONED,
        liveaction_db=liveaction_db,
        result={},
    )

    execution_db = update_execution(liveaction_db, publish=publish)

    LOG.info(
        "Marked execution %s as %s.",
        execution_db.id,
        action_constants.LIVEACTION_STATUS_ABANDONED,
    )

    # Invoke post run on the action to execute post run operations such as callback.
    runners_utils.invoke_post_run(liveaction_db)

    return execution_db

def is_execution_canceled(execution_id):
    try:
        execution = ActionExecution.get_by_id(execution_id)
        return execution.status == action_constants.LIVEACTION_STATUS_CANCELED
    except:
        return False  # XXX: What to do here?

def get_parent_context(liveaction_db):
    """
    Returns context of the parent execution.

    :return: If found the parent context else None.
    :rtype: dict
    """
    context = getattr(liveaction_db, "context", None)
    if not context:
        return None
    return context.get("parent", None)

class AscendingSortedDescendantView(object):
    def __init__(self):
        self._result = []

    def add(self, child):
        self._result.append(child)

    @property
    def result(self):
        return sorted(self._result, key=lambda execution: execution.start_timestamp)

class DFSDescendantView(object):
    def __init__(self):
        self._result = []

    def add(self, child):
        self._result.append(child)

    @property
    def result(self):
        return self._result

DESCENDANT_VIEWS = {
    "sorted": AscendingSortedDescendantView,
    "default": DFSDescendantView,
}

def get_descendants(actionexecution_id, descendant_depth=-1, result_fmt=None):
    """
    Returns all descendant executions upto the specified descendant_depth for
    the supplied actionexecution_id.
    """
    descendants = DESCENDANT_VIEWS.get(result_fmt, DFSDescendantView)()
    children = ActionExecution.query(
        parent=actionexecution_id, **{"order_by": ["start_timestamp"]}
    )
    LOG.debug("Found %s children for id %s.", len(children), actionexecution_id)
    current_level = [(child, 1) for child in children]

    while current_level:
        parent, level = current_level.pop(0)
        parent_id = str(parent.id)
        descendants.add(parent)
        if not parent.children:
            continue
        if level != -1 and level == descendant_depth:
            continue
        children = ActionExecution.query(
            parent=parent_id, **{"order_by": ["start_timestamp"]}
        )
        LOG.debug("Found %s children for id %s.", len(children), parent_id)
        # prepend for DFS
        for idx in range(len(children)):
            current_level.insert(idx, (children[idx], level + 1))
    return descendants.result


text:
use std::fmt;
use std::path::Path;
use std::ptr;
use std::slice;
use std::str;

use rocks_sys as ll;

use crate::env::{Env, Logger};
use crate::to_raw::ToRaw;
use crate::{Error, Result};

/// Persistent cache interface for caching IO pages on a persistent medium. The
/// cache interface is specifically designed for persistent read cache.
pub struct PersistentCache {
    raw: *mut ll::rocks_persistent_cache_t,
}

impl ToRaw<ll::rocks_persistent_cache_t> for PersistentCache {
    fn raw(&self) -> *mut ll::rocks_persistent_cache_t {
        self.raw
    }
}

impl Drop for PersistentCache {
    fn drop(&mut self) {
        unsafe { ll::rocks_persistent_cache_destroy(self.raw) }
    }
}

impl Clone for PersistentCache {
    /// Duplicated PersistentCache inner shared_ptr
    fn clone(&self) -> Self {
        PersistentCache {
            raw: unsafe { ll::rocks_persistent_cache_clone(self.raw) },
        }
    }
}

impl fmt::Debug for PersistentCache {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("PersistentCache")
            .field("options", &self.get_printable_options())
            .finish()
    }
}

impl PersistentCache {
    /// Factor method to create a new persistent cache
    pub fn new<P: AsRef<Path>>(
        env: &Env,
        path: P,
        size: u64,
        log: Option<&Logger>,
        optimized_for_nvm: bool,
    ) -> Result<PersistentCache> {
        let path_str = path.as_ref().to_str().expect("valid path");
        let mut status = ptr::null_mut::<ll::rocks_status_t>();
        unsafe {
            let raw = ll::rocks_new_persistent_cache(
                env.raw(),
                path_str.as_ptr() as *const _,
                path_str.len(),
                size,
                log.map(|logger| logger.raw()).unwrap_or_else(ptr::null_mut),
                optimized_for_nvm as u8,
                &mut status,
            );
            Error::from_ll(status).map(|()| PersistentCache { raw: raw })
        }
    }

    pub fn get_printable_options(&self) -> String {
        unsafe {
            let cxx_string = ll::rocks_persistent_cache_get_printable_options(self.raw);
            let ptr = ll::cxx_string_data(cxx_string) as *const u8;
            let len = ll::cxx_string_size(cxx_string);
            let ret = str::from_utf8_unchecked(slice::from_raw_parts(ptr, len)).into();
            ll::cxx_string_destroy(cxx_string);
            ret
        }
    }
}

#[test]
fn test_persistent_cache() {
    let tmp_dir = ::tempdir::TempDir::new_in("", "rocks").unwrap();
    // let logger = Env::default_instance()
    //     .create_logger(tmp_dir.path().join("test.logfiles"))
    //     .unwrap();
    // NOTE: from RocksdB, size should be big enough
    let pcache = PersistentCache::new(Env::default_instance(), tmp_dir.path(), 1 << 30, None, true).unwrap();

    assert!(format!("{:?}", pcache).contains("is_compressed: 1"));
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="3dp">
    <ImageView
        android:id="@+id/apps_list_image"
        android:layout_width="65dp"
        android:layout_height="65dp"
        android:contentDescription="@string/image_description"/>
    <TextView
        android:id="@+id/apps_list_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="15dp"
        android:layout_marginLeft="15dp"
        android:layout_gravity="center"
        android:textSize="@dimen/big_size"
        android:textStyle="bold" />
</LinearLayout>


text:
<?php

/*
 * This file is part of the Basecamp Classic API Wrapper for PHP 5.3+ package
 *
 * (c) Christian Hoegl <chrigu@sirprize.me>
 */

namespace Sirprize\Basecamp\Person\Collection\Observer;

use Sirprize\Basecamp\Person\Collection;
use Sirprize\Basecamp\Person\Collection\Observer\Abstrakt;

/**
 * Class to observe and print state changes of the observed person
 */
class Stout extends Abstrakt
{

    public function onStartSuccess(Collection $collection)
    {
        print $this->_getOnStartSuccessMessage($collection)."\n";
    }

    public function onStartError(Collection $collection)
    {
        print $this->_getOnStartErrorMessage($collection)."\n";
    }

}


text:
using System.Collections.Generic;

namespace Raccoon.Input {
    public class ControllersManager<T, S> {
        #region Private Members

        private List<int> _indexes = new List<int>();
        private Dictionary<int, Controller<T, S>> _controllers = new Dictionary<int, Controller<T, S>>();

        #endregion Private Members

        #region Constructors

        public ControllersManager() {
        }

        #endregion Constructors

        #region Public Properties

        public int? MaxAllowedControllers { get; set; }
        public int RegisteredControllers { get { return _controllers.Count; } }

        public int ConnectedControllers {
            get {
                int count = 0;

                foreach (Controller<T, S> controller in _controllers.Values) {
                    if (controller.IsConnected) {
                        count += 1;
                    }
                }

                return count;
            }
        }

        public int DisconnectedControllers {
            get {
                int count = 0;

                foreach (Controller<T, S> controller in _controllers.Values) {
                    if (!controller.IsConnected) {
                        count += 1;
                    }
                }

                return count;
            }
        }

        #endregion Public Properties

        #region Public Methods

        public void Update(int delta) {
            foreach (Controller<T, S> controller in _controllers.Values) {
                if (!controller.Enabled || !controller.IsConnected) {
                    continue;
                }

                controller.Update(delta);
            }
        }

        public int? FindControllerIndex(Controller<T, S> controller) {
            foreach (KeyValuePair<int, Controller<T, S>> entry in _controllers) {
                if (entry.Value == controller) {
                    return entry.Key;
                }
            }

            return null;
        }

        public Controller<T, S> RequestController(int customIndex) {
            RequestNextControllerIndex(customIndex);
            Controller<T, S> controller = new Controller<T, S>();
            _controllers.Add(customIndex, controller);
            return controller;
        }

        public Controller<T, S> RequestController(out int index) {
            index = RequestNextControllerIndex();
            Controller<T, S> controller = new Controller<T, S>();
            _controllers.Add(index, controller);
            return controller;
        }

        public Controller<T, S> RequestController() {
            return RequestController(out _);
        }

        public bool RemoveController(int index) {
            _indexes.Remove(index);
            return _controllers.Remove(index);
        }

        public bool RemoveController(Controller<T, S> controller) {
            int index = -1;

            foreach (KeyValuePair<int, Controller<T, S>> entry in _controllers) {
                if (entry.Value == controller) {
                    index = entry.Key;
                }
            }

            if (index < 0) {
                return false;
            }

            return RemoveController(index);
        }

        public void RemoveAllControllers() {
            _controllers.Clear();
            _indexes.Clear();
        }

        public void ConnectController(int index) {
            if (!_controllers.TryGetValue(index, out Controller<T, S> controller)) {
                throw new System.ArgumentException($"There is no Controller registered at index {index}.");
            }

            controller.Connect();
        }

        public void ConnectController(Controller<T, S> controller) {
            if (controller == null) {
                throw new System.ArgumentNullException(nameof(controller));
            }

            if (!FindControllerIndex(controller).HasValue) {
                throw new System.ArgumentException("Controller isn't registered.");
            }

            controller.Connect();
        }

        public void DisconnectController(int index) {
            if (!_controllers.TryGetValue(index, out Controller<T, S> controller)) {
                throw new System.ArgumentException($"There is no Controller registered at index {index}.");
            }

            controller.Disconnect();
        }

        public void DisconnectController(Controller<T, S> controller) {
            if (controller == null) {
                throw new System.ArgumentNullException(nameof(controller));
            }

            if (!FindControllerIndex(controller).HasValue) {
                throw new System.ArgumentException("Controller isn't registered.");
            }

            controller.Disconnect();
        }

        #endregion Public Methods

        #region Private Methods

        private int RequestNextControllerIndex(int? customIndex = null) {
            if (MaxAllowedControllers.HasValue && _controllers.Count >= MaxAllowedControllers.Value) {
                throw new System.InvalidOperationException($"Max allowed controllers reached.\nMax: {MaxAllowedControllers.Value}\nRegistered: {RegisteredControllers}\nConnected: {ConnectedControllers}\nDisconnected: {DisconnectedControllers}");
            }

            int index = customIndex.GetValueOrDefault(0),
                n;

            for (n = 0; n < _indexes.Count; n++) {
                int registeredIndex = _indexes[n];

                if (registeredIndex == index) {
                    // try next one
                    index += 1;

                    continue;
                } else if (registeredIndex > index) {
                    // accept index
                    break;
                }
            }

            _indexes.Insert(n, index);
            return index;
        }

        #endregion Private Methods
    }
}


text:
using Microsoft.Xna.Framework;
using StardewValley;
using SObject = StardewValley.Object;

namespace Pathoschild.Stardew.Automate.Framework.Machines.Objects
{
    /// A mushroom box that accepts input and provides output.
    /// <remarks>Derived from <see cref="SObject.DayUpdate"/> (search for 'case 128') and <see cref="SObject.minutesElapsed"/> (search for 'Mushroom Box').</remarks>
    internal class MushroomBoxMachine : GenericObjectMachine<SObject>
    {
        /*********
        ** Public methods
        *********/
        /// Construct an instance.
        /// <param name="machine">The underlying machine.</param>
        /// <param name="location">The location containing the machine.</param>
        /// <param name="tile">The tile covered by the machine.</param>
        public MushroomBoxMachine(SObject machine, GameLocation location, Vector2 tile)
            : base(machine, location, tile) { }

        /// Get the machine's processing state.
        public override MachineState GetState()
        {
            return this.GetGenericState(emptyState: MachineState.Processing);
        }

        /// Get the output item.
        public override ITrackedStack? GetOutput()
        {
            return this.GetTracked(this.Machine.heldObject.Value, onEmpty: this.Reset);
        }

        /// Provide input to the machine.
        /// <param name="input">The available items.</param>
        /// <returns>Returns whether the machine started processing an item.</returns>
        public override bool SetInput(IStorage input)
        {
            return false; // no input needed
        }

        /*********
        ** Private methods
        *********/
        /// Reset the machine so it's ready to accept a new input.
        /// <param name="item">The output item that was taken.</param>
        private void Reset(Item item)
        {
            this.GenericReset(item);
            this.Machine.showNextIndex.Value = false;
        }
    }
}


text:
package com.twitter.finagle.addr

import com.twitter.concurrent.{Offer, Broker}
import com.twitter.finagle.builder.Cluster
import com.twitter.finagle.Addr
import com.twitter.finagle.stats.{StatsReceiver, NullStatsReceiver}
import com.twitter.finagle.util.DefaultTimer
import com.twitter.util.{Future, Time, Timer, Duration, Var}
import scala.collection.immutable.Queue
import java.net.SocketAddress

private[finagle] object StabilizingAddr {
  private[finagle/*(testing*/] object State extends Enumeration {
    type Health = Value
    // explicitly define intuitive ids as they
    // are exported for stats.
    val Healthy = Value(1)
    val Unknown = Value(0)
    val Unhealthy = Value(-1)
  }

  private def qcontains[T](q: Queue[(T, _)], elem: T): Boolean =
    q exists { case (e, _) => e == elem }

  /**
   * A StabilizingAddr conservatively removes elements from a bound
   * Addr depending on the source health (exposed through `pulse`).
   * More specifically, removes are delayed until the source is in a
   * healthy state for at least `grace` period.
   *
   * @param addr An offer for underlying address updates.
   * @param pulse An offer for communicating group health.
   *        Invariant: The offer should communicate Health in FIFO order
   *        with respect to time.
   * @param grace The duration that must elapse before an element
   *        is removed from the group.
   */
  def apply(
    addr: Offer[Addr],
    pulse: Offer[State.Health],
    grace: Duration,
    statsReceiver: StatsReceiver = NullStatsReceiver,
    timer: Timer = DefaultTimer.twitter
  ): Offer[Addr] = new Offer[Addr] {
    import State._

    implicit val injectTimer = timer

    @volatile var nq = 0
    @volatile var healthStat = Healthy.id

    val health = statsReceiver.addGauge("health") { healthStat }
    val limbo = statsReceiver.addGauge("limbo") { nq }
    val stabilized = new Broker[Addr]

    /**
     * Exclusively maintains the elements in current
     * based on adds, removes, and health transitions.
     * Removes are delayed for grace period and each health
     * transition resets the grace period.
     */
    def loop(
        remq: Queue[(SocketAddress, Time)],
        h: Health,
        active: Set[SocketAddress],
        needPush: Boolean,
        srcAddr: Addr): Future[Unit] = {
      nq = remq.size
      Offer.select(
        pulse map { newh =>
          healthStat = newh.id

          // If our health transitions into healthy, reset removal
          // times foreach elem in remq.
          newh match {
            case newh if h == newh =>
              loop(remq, newh, active, needPush, srcAddr)
            case Healthy =>
              // Transitioned to healthy: push back
              val newTime = Time.now + grace
              val newq = remq map { case (elem, _) => (elem, newTime) }
              loop(newq, Healthy, active, needPush, srcAddr)
            case newh =>
              loop(remq, newh, active, needPush, srcAddr)
          }
        },

        addr map {
          case addr@Addr.Bound(newSet, _) =>
            // Update our pending queue so that newly added
            // entries aren't later removed.
            var q = remq filter { case (e, _) => !(newSet contains e) }

            // Add newly removed elements to the remove queue.
            val until = Time.now + grace
            for (el <- active &~ newSet if !qcontains(q, el))
              q = q enqueue (el, until)

            loop(q, h, active ++ newSet, true, addr)

          case addr =>
            // A nonbound address will enqueue all active members
            // for removal, so that if we become bound again, we can
            // continue on merrily.
            val until = Time.now + grace
            val q = remq enqueue (active map(el => (el, until)))

            loop(q, h, active, true, addr)
        },

        if (h != Healthy || remq.isEmpty) Offer.never
        else {
          // Note: remq is ordered by 'until' time.
          val ((elem, until), nextq) = remq.dequeue
          Offer.timeout(until - Time.now) map { _ =>
            loop(nextq, h, active - elem, true, srcAddr)
          }
        },

        if (!needPush) Offer.never else {
          // We always bind if active is nonempty. Otherwise we
          // pass through the current active address.
          val attrs = srcAddr match {
            case Addr.Bound(_, attrs) => attrs
            case _ => Addr.Metadata.empty
          }
          val addr =
            if (active.nonEmpty) Addr.Bound(active, attrs)
            else srcAddr
          stabilized.send(addr) map { _ =>
            loop(remq, h, active, false, srcAddr)
          }
        }
      )
    }

    loop(Queue.empty, Healthy, Set.empty, false, Addr.Pending)

    // Defer to the underlying Offer.
    def prepare() = stabilized.recv.prepare()
  }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>numpy.rollaxis — NumPy v1.8 Manual</title>
    <link rel="stylesheet" href="../../_static/pythonista.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />

    <link rel="author" title="About these documents" href="../../about.html" />
    <link rel="top" title="NumPy v1.8 Manual" href="../../index.html" />
    <link rel="up" title="Array manipulation routines" href="../routines.array-manipulation.html" />
    <link rel="next" title="numpy.swapaxes" href="numpy.swapaxes.html" />
    <link rel="prev" title="numpy.ndarray.flatten" href="numpy.ndarray.flatten.html" />
    <link rel="shortcut icon" type="image/png" href="../../_static/py.png" />
    <meta name = "viewport" content = "width=device-width,initial-scale=1.0,user-scalable=no;">

Navigation

          index

          next |

          previous |

NumPy v1.8 Manual »

NumPy Reference »

Routines »

Array manipulation routines »

numpy.rollaxis¶

<tt class="descclassname">numpy.</tt><tt class="descname">rollaxis</tt><big>(</big>a, axis, start=0<big>)</big>[source]¶

Roll the specified axis backwards, until it lies in a given position.

<col class="field-name" />
<col class="field-body" />

Parameters:
a : ndarray

Input array.

axis : int

The axis to roll backwards.  The positions of the other axes do not
change relative to one another.

start : int, optional

The axis is rolled until it lies before this position.  The default,
0, results in a “complete” roll.

Returns:
res : ndarray

Output array.

See also

<tt class="xref py py-obj docutils literal">roll</tt>

Roll the elements of an array by a number of positions along a given axis.

Examples

>>> a = np.ones((3,4,5,6))
>>> np.rollaxis(a, 3, 1).shape
(3, 6, 4, 5)
>>> np.rollaxis(a, 2).shape
(5, 3, 4, 6)
>>> np.rollaxis(a, 1, 4).shape
(3, 5, 6, 4)

    © Copyright 2008-2009, The Scipy community.

    The Python Software Foundation is a non-profit corporation.
    Please donate.

    Last updated on May 03, 2016.
    Found a bug?

    Created using Sphinx 1.2.1.


text:
class BlocklyInterpreter::CoreBlocks::ProceduresIfReturnBlock < BlocklyInterpreter::Block
  include BlocklyInterpreter::DSLGenerator

  self.block_type = :procedures_ifreturn

  def execute_statement(execution_context)
    if values['CONDITION'].value(execution_context).present?
      return_value = values['VALUE'].value(execution_context) if values['VALUE']
      execution_context.early_return!(return_value)
    end
  end

  def to_dsl
    block_contents = [method_call_with_possible_block("condition", "", values['CONDITION'])]
    block_contents << method_call_with_block_or_nothing("return_value", "", values['VALUE'])

    method_call_with_possible_block("procedures_ifreturn", "", block_contents.compact)
  end

  module DSLMethods
    class ProceduresIfReturnBlockBuilder < BlocklyInterpreter::DSL::BlockBuilder
      def initialize(block_type)
        super
        mutation_attr :value, 0
      end

      def condition(&proc)
        value :CONDITION, &proc
      end

      def return_value(&proc)
        mutation_attr :value, 1
        value :VALUE, &proc
      end
    end

    def procedures_ifreturn(&proc)
      builder = BlocklyInterpreter::CoreBlocks::ProceduresIfReturnBlock::DSLMethods::ProceduresIfReturnBlockBuilder.new("procedures_ifreturn")

      @blocks << builder.tap do |builder|
        builder.instance_exec(&proc) if proc
      end
    end
  end
end