text:
<!--

********************************************************************************

WARNING:

    DO NOT EDIT "couchdb/README.md"

    IT IS AUTO-GENERATED

    (from the other files in "couchdb/" combined with a set of templates)

********************************************************************************

-->

# Supported tags and respective `Dockerfile` links

-	[`latest`, `2.1.1`, `2.1`, `2` (*2.1.1/Dockerfile*)](https://github.com/apache/couchdb-docker/blob/1a7c4254c158a194ff195da6ebfed910d24a95b7/2.1.1/Dockerfile)
-	[`1.7.1`, `1.7`, `1` (*1.7.1/Dockerfile*)](https://github.com/apache/couchdb-docker/blob/029760550b8af66f49bf439ddbabfbd040e9727c/1.7.1/Dockerfile)
-	[`1.7.1-couchperuser`, `1.7-couchperuser`, `1-couchperuser` (*1.7.1-couchperuser/Dockerfile*)](https://github.com/apache/couchdb-docker/blob/029760550b8af66f49bf439ddbabfbd040e9727c/1.7.1-couchperuser/Dockerfile)

# Quick reference

-	**Where to get help**:
	[the Docker Community Forums](https://forums.docker.com/), [the Docker Community Slack](https://blog.docker.com/2016/11/introducing-docker-community-directory-docker-community-slack/), or [Stack Overflow](https://stackoverflow.com/search?tab=newest&q=docker)

-	**Where to file issues**:
	[https://github.com/apache/couchdb-docker/issues](https://github.com/apache/couchdb-docker/issues)

-	**Maintained by**:
	[Apache CouchDB](https://github.com/apache/couchdb-docker)

-	**Supported architectures**: ([more info](https://github.com/docker-library/official-images#architectures-other-than-amd64))
	[`amd64`](https://hub.docker.com/r/amd64/couchdb/)

-	**Published image artifact details**:
	[repo-info repo's `repos/couchdb/` directory](https://github.com/docker-library/repo-info/blob/master/repos/couchdb) ([history](https://github.com/docker-library/repo-info/commits/master/repos/couchdb))
	(image metadata, transfer size, etc)

-	**Image updates**:
	[official-images PRs with label `library/couchdb`](https://github.com/docker-library/official-images/pulls?q=label%3Alibrary%2Fcouchdb)
	[official-images repo's `library/couchdb` file](https://github.com/docker-library/official-images/blob/master/library/couchdb) ([history](https://github.com/docker-library/official-images/commits/master/library/couchdb))

-	**Source of this description**:
	[docs repo's `couchdb/` directory](https://github.com/docker-library/docs/tree/master/couchdb) ([history](https://github.com/docker-library/docs/commits/master/couchdb))

-	**Supported Docker versions**:
	[the latest release](https://github.com/docker/docker-ce/releases/latest) (down to 1.6 on a best-effort basis)

# What is Apache CouchDB?

Apache CouchDB™ lets you access your data where you need it by defining the Couch Replication Protocol that is implemented by a variety of projects and products that span every imaginable computing environment from globally distributed server-clusters, over mobile phones to web browsers. Software that is compatible with the Couch Replication Protocol include: PouchDB, Buttant, and Couchbase Lite.

Store your data safely, on your own servers, or with any leading cloud provider. Your web- and native applications love CouchDB, because it speaks JSON natively and supports binary for all your data storage needs. The Couch Replication Protocol lets your data flow seamlessly between server clusters to mobile phones and web browsers, enabling a compelling, offline-first user-experience while maintaining high performance and strong reliability. CouchDB comes with a developer-friendly query language, and optionally MapReduce for simple, efficient, and comprehensive data retrieval.

> [couchdb.apache.org](https://couchdb.apache.org)

![logo](https://raw.githubusercontent.com/docker-library/docs/d14b6718efb17e85f7a72ceb5de0718786367884/couchdb/logo.png)

## How to use this image

### Start a CouchDB instance

```console
$ docker run -d --name my-couchdb couchdb
```

This image includes `EXPOSE 5984` (the CouchDB port), so standard container linking will make it automatically available to the linked containers.

### Using the instance

In order to use the running instance from an application, link the container

```console
$ docker run --name my-couchdb-app --link my-couchdb:couch couchdb
```

Please note that CouchDB no longer autocreates system tables for you, so you will have to create `_global_changes`, `_metadata`, `_replicator` and `_users` manually (the admin interface has a "Setup" menu that does this for you).

The node will also start in [admin party mode](http://guide.couchdb.org/draft/security.html#party)!

For the `2.1` image, configuration is stored at `/opt/couchdb/etc/`.

See the [official docs](http://docs.couchdb.org/en/2.1.0/) for infomation on using and configuring CouchDB.

### Exposing the port to the outside world

If you want to expose the port to the outside world, run

```console
$ docker run -p 5984:5984 -d couchdb
```

CouchDB listens on port 5984 for requests and the image includes `EXPOSE 5984`. The flag `-p 5984:5984` exposes this port on the host.

*WARNING*: Do not do this until you have established an admin user and setup permissions correctly on any databases you have created.

## Persistent Data

There are several ways to store data used by applications that run in Docker containers. We encourage users of the `couchdb` images to familiarize themselves with the options available, including:

-	Let Docker manage the storage of your database data [by writing the database files to disk on the host system using its own internal volume management](https://docs.docker.com/engine/tutorials/dockervolumes/#adding-a-data-volume). This is the default and is easy and fairly transparent to the user. The downside is that the files may be hard to locate for tools and applications that run directly on the host system, i.e. outside containers.
-	Create a data directory on the host system (outside the container) and [mount this to a directory visible from inside the container](https://docs.docker.com/engine/tutorials/dockervolumes/#mount-a-host-directory-as-a-data-volume). This places the database files in a known location on the host system, and makes it easy for tools and applications on the host system to access the files. The downside is that the user needs to make sure that the directory exists, and that e.g. directory permissions and other security mechanisms on the host system are set up correctly.

CouchDB uses `/opt/couchdb/data` to store its data, and is exposed as a volume.

CouchDB uses `/opt/couchdb/etc` to store its configuration.

### Using host directories

You can map the container's volumes to a directory on the host, so that the data is kept between runs of the container. This example uses your current directory, but that is in general not the correct place to store your persistent data!

```console
$ docker run -d -v $(pwd):/opt/couchdb/data --name my-couchdb couchdb
```

## Specifying the admin user in the environment

You can use the two environment variables `COUCHDB_USER` and `COUCHDB_PASSWORD` to set up the admin user.

```console
$ docker run -e COUCHDB_USER=admin -e COUCHDB_PASSWORD=password -d couchdb
```

Note that if you are setting up a clustered CouchDB, you will want to pre-hash this password and use the identical hashed text across all nodes to ensure sessions work correctly when a load balancer is placed in front of the cluster. Hashing can be accomplished by running the container with the `/opt/couchdb/etc/local.d` directory mounted as a volume, allowing CouchDB to hash the password you set, then copying out the hashed version and using this value in the future.

## Using your own CouchDB configuration file

The CouchDB configuration is specified in `.ini` files in `/opt/couchdb/etc`. Take a look at the [CouchDB configuration documentation](http://docs.couchdb.org/en/2.1.0/config/index.html) to learn more about CouchDB's configuration structure.

If you want to use a customized CouchDB configuration, you can create your configuration file in a directory on the host machine and then mount that directory as `/opt/couchdb/etc/local.d` inside the `couchdb` container.

```console
$ docker run --name my-couchdb -v /my/custom-config-dir:/opt/couchdb/etc/local.d -d couchdb
```

You can also use `couchdb` as the base image for your own couchdb instance and provie your own version of the `local.ini` config file:

Example Dockerfile:

```dockerfile
FROM couchdb

COPY local.ini /opt/couchdb/etc/
```

and then build and run

```console
$ docker build -t you/awesome-couchdb .
$ docker run -d -p 5984:5984 you/awesome-couchdb
```

## Logging

By default containers run from this image only log to `stdout`. You can enable logging to file in the [configuration](http://docs.couchdb.org/en/2.1.0/config/logging.html).

For example in `local.ini`:

```ini
[log]
writer = file
file = /opt/couchdb/log/couch.log
```

## Erlang Version

This image uses Erlang `17.3` from Debian Jessie's repository. Debian's version patches a critical bug in Erlang `17.3` and is good to use with CouchDB.

# License

Apache CouchDB is licensed under the [Apache License](https://github.com/apache/couchdb/blob/master/LICENSE).

As with all Docker images, these likely also contain other software which may be under other licenses (such as Bash, etc from the base distribution, along with any direct or indirect dependencies of the primary software being contained).

Some additional license information which was able to be auto-detected might be found in [the `repo-info` repository's `couchdb/` directory](https://github.com/docker-library/repo-info/tree/master/repos/couchdb).

As for any pre-built image usage, it is the image user's responsibility to ensure that any use of this image complies with any relevant licenses for all software contained within.


text:
#include "pybulletphysics.h"

static void
Vector3_dealloc(bulletphysics_Vector3Object* self)
{
	if (self->vector)
        	delete(self->vector);
        self->ob_type->tp_free((PyObject*)self);
}

static PyObject*
Vector3_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
	float x = 0.0;
	float y = 0.0;
	float z = 0.0;
	if (!PyArg_ParseTuple(args, "fff", &x, &y, &z)) {
        	return NULL;
    	}

        bulletphysics_Vector3Object *self = (bulletphysics_Vector3Object *)type->tp_alloc(type, 0);
        if (self != NULL) {
                self->vector = new btVector3(x, y, z);
        }
        return (PyObject *)self;
}

PyTypeObject bulletphysics_Vector3Type = {
    PyObject_HEAD_INIT(NULL)
    0,                         /*ob_size*/
    "bulletphysics.Vector3", /*tp_name*/
    sizeof(bulletphysics_Vector3Object), /*tp_basicsize*/
    0,                         /*tp_itemsize*/
    (destructor)Vector3_dealloc,    /*tp_dealloc*/
    0,                         /*tp_print*/
    0,                         /*tp_getattr*/
    0,                         /*tp_setattr*/
    0,                         /*tp_compare*/
    0,                         /*tp_repr*/
    0,                         /*tp_as_number*/
    0,                         /*tp_as_sequence*/
    0,                         /*tp_as_mapping*/
    0,                         /*tp_hash */
    0,                         /*tp_call*/
    0,                         /*tp_str*/
    0,                         /*tp_getattro*/
    0,                         /*tp_setattro*/
    0,                         /*tp_as_buffer*/
    Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_CHECKTYPES, /*tp_flags*/
    "Vector3 object",           /* tp_doc */
};

PyObject *new_pyvector3_from_vector(btVector3 v) {
	bulletphysics_Vector3Object *py_vector3 = (bulletphysics_Vector3Object *)bulletphysics_Vector3Type.tp_alloc(&bulletphysics_Vector3Type, 0);
	if (py_vector3) {
		py_vector3->vector = new btVector3(v.getX(), v.getY(), v.getZ());
		Py_INCREF(py_vector3);
	}
	return (PyObject *)py_vector3;
}

static PyObject *
Vector3_rotate(bulletphysics_Vector3Object *self, PyObject *args, PyObject *kwds) {
	bulletphysics_Vector3Object *py_vector3 = NULL;
	float angle = 0.0;
	if (!PyArg_ParseTuple(args, "Of", &py_vector3, &angle)) {
                return NULL;
        }
	pybulletphysics_checktype(py_vector3, Vector3);
	return new_pyvector3_from_vector( self->vector->rotate(*(py_vector3->vector), angle) );
}

static PyObject *
Vector3_add(bulletphysics_Vector3Object *self, PyObject *py_vector3) {
	pybulletphysics_checktype(py_vector3, Vector3);
	return new_pyvector3_from_vector( *self->vector + *(((bulletphysics_Vector3Object *)py_vector3)->vector));
}

static PyObject *
Vector3_mul(bulletphysics_Vector3Object *self, PyObject *py_v) {
        pybulletphysics_checktype(py_v, Vector3);
        return new_pyvector3_from_vector( *self->vector * *(((bulletphysics_Vector3Object *)py_v)->vector));
}

static PyObject *
Vector3_getX(bulletphysics_Vector3Object *self, PyObject *args, PyObject *kwds) {
        return PyFloat_FromDouble(self->vector->getX());
}

static PyObject *
Vector3_getY(bulletphysics_Vector3Object *self, PyObject *args, PyObject *kwds) {
        return PyFloat_FromDouble(self->vector->getY());
}

static PyObject *
Vector3_getZ(bulletphysics_Vector3Object *self, PyObject *args, PyObject *kwds) {
        return PyFloat_FromDouble(self->vector->getZ());
}

static PyObject *
Vector3_length(bulletphysics_Vector3Object *self, PyObject *args, PyObject *kwds) {
        return PyFloat_FromDouble(self->vector->length());
}

static PyMethodDef Vector3_methods[] = {
    {"getX", (PyCFunction)Vector3_getX, METH_VARARGS, NULL },
    {"getY", (PyCFunction)Vector3_getY, METH_VARARGS, NULL },
    {"getZ", (PyCFunction)Vector3_getZ, METH_VARARGS, NULL },
    {"rotate", (PyCFunction)Vector3_rotate, METH_VARARGS, NULL },
    {"length", (PyCFunction)Vector3_length, METH_VARARGS, NULL },
    {NULL, NULL, 0, NULL}
};

PyNumberMethods Vector3_number_methods;

void pybulletphysics_add_Vector3(PyObject *module) {
	memset(&Vector3_number_methods, 0, sizeof(PyNumberMethods));
	bulletphysics_Vector3Type.tp_as_number = &Vector3_number_methods;

	Vector3_number_methods.nb_add = (binaryfunc)Vector3_add;
	Vector3_number_methods.nb_multiply = (binaryfunc)Vector3_mul;

	bulletphysics_Vector3Type.tp_methods = Vector3_methods;
	bulletphysics_Vector3Type.tp_new = Vector3_new;

        if (PyType_Ready(&bulletphysics_Vector3Type) < 0)
                return;

	Py_INCREF(&bulletphysics_Vector3Type);

        PyModule_AddObject(module, "Vector3", (PyObject *)&bulletphysics_Vector3Type);
}

redpajama_set_name: RedPajamaGithub


text:
## Установка

 Перейти в директорию проекта и выполнить:

 ```
 npm install
 bower install
 gulp webserver
 ```

## Требования

 Необходимо чтоб был установлен node > 4 и gulp


text:
/* Camera module
 *
 * https://github.com/raspberrypi/userland/blob/master/host_applications/linux/apps/raspicam/RaspiCamDocs.odt
 *
 * these experiments will start to break request/response
 * patterns and help us to start to support streaming too
 * */

var exec = require('child_process').exec;
var spawn = require('child_process').spawn;
var fs = require('fs');

module.exports = function(device) {
  return {
    'arm': {
      fn: device.camera.arm.bind(device.camera)
    },
    'disarm': {
      fn: device.camera.disarm.bind(device.camera)
    },
    'get still (320x240)': {
      fn: function(cb) {
        device.camera.getStill(function(err, stream) {
          if (err !== null) {
            cb(err);
          } else {
            var buf = "";
            var base64 = spawn('base64');
            stream.pipe(base64.stdin);
            base64.stdout.on('data', function(data) {
              buf += data.toString();
            });
            base64.on('close', function() {
              cb(null, {
                contentType: 'image/jpg (base64)',
                content: buf
              });
            });
          }
        });
      }
    },
    'get rgb triplets (64x48)': {
      fn: function(cb) {
        return cb("this code needs to be adapted to the new pattern. see get still implementation for more"); /*
        exec('/opt/vc/bin/raspiyuv -w 64 -h 48 -o /tmp/still.rgb', function(err, stdout, stderr){
          if (err !== null) {
            cb({
              stderr: stderr,
              message: err.message,
              stack: err.stack
            }, null);
          } else {
            exec('node /opt/netpocketos/opt/device/features/camera/rgbMatrix.js /tmp/still.rgb 64 48', function(err2, stdout2, stderr2){
              if (err2 !== null) {
                cb({
                  stderr: stderr2,
                  message: err2.message,
                  stack: err2.stack
                }, null);
              } else {
                cb(null, {
                  contentType: 'text/plain',
                  content: stdout2
                });
              }
            });
          }
        });*/
      }
    }
  };
};


text:
"""Script for unittesting the utils module"""

import errno
import fcntl
import glob
import mock
import operator
import os
import os.path
import random
import re
import shutil
import signal
import socket
import stat
import tempfile
import time
import unittest
import warnings

import testutils
from ganeti import constants
from ganeti import compat
from ganeti import utils
from ganeti import errors
from ganeti import constants
from ganeti.utils import RunCmd, \
     FirstFree, \
     RunParts

class TestParseCpuMask(unittest.TestCase):
  """Test case for the ParseCpuMask function."""

  def testWellFormed(self):
    self.assertEqual(utils.ParseCpuMask(""), [])
    self.assertEqual(utils.ParseCpuMask("1"), [1])
    self.assertEqual(utils.ParseCpuMask("0-2,4,5-5"), [0,1,2,4,5])

  def testInvalidInput(self):
    for data in ["garbage", "0,", "0-1-2", "2-1", "1-a"]:
      self.assertRaises(errors.ParseError, utils.ParseCpuMask, data)

class TestParseMultiCpuMask(unittest.TestCase):
  """Test case for the ParseMultiCpuMask function."""

  def testWellFormed(self):
    self.assertEqual(utils.ParseMultiCpuMask(""), [])
    self.assertEqual(utils.ParseMultiCpuMask("1"), [[1]])
    self.assertEqual(utils.ParseMultiCpuMask("0-2,4,5-5"), [[0, 1, 2, 4, 5]])
    self.assertEqual(utils.ParseMultiCpuMask("all"), [[-1]])
    self.assertEqual(utils.ParseMultiCpuMask("0-2:all:4,6-8"),
      [[0, 1, 2], [-1], [4, 6, 7, 8]])

  def testInvalidInput(self):
    for data in ["garbage", "0,", "0-1-2", "2-1", "1-a", "all-all"]:
      self.assertRaises(errors.ParseError, utils.ParseCpuMask, data)

class TestGetMounts(unittest.TestCase):
  """Test case for GetMounts()."""

  TESTDATA = (
    "rootfs /     rootfs rw 0 0\n"
    "none   /sys  sysfs  rw,nosuid,nodev,noexec,relatime 0 0\n"
    "none   /proc proc   rw,nosuid,nodev,noexec,relatime 0 0\n")

  def setUp(self):
    self.tmpfile = tempfile.NamedTemporaryFile()
    utils.WriteFile(self.tmpfile.name, data=self.TESTDATA)

  def testGetMounts(self):
    self.assertEqual(utils.GetMounts(filename=self.tmpfile.name),
      [
        ("rootfs", "/", "rootfs", "rw"),
        ("none", "/sys", "sysfs", "rw,nosuid,nodev,noexec,relatime"),
        ("none", "/proc", "proc", "rw,nosuid,nodev,noexec,relatime"),
      ])

class TestFirstFree(unittest.TestCase):
  """Test case for the FirstFree function"""

  def test(self):
    """Test FirstFree"""
    self.failUnlessEqual(FirstFree([0, 1, 3]), 2)
    self.failUnlessEqual(FirstFree([]), None)
    self.failUnlessEqual(FirstFree([3, 4, 6]), 0)
    self.failUnlessEqual(FirstFree([3, 4, 6], base=3), 5)
    self.failUnlessRaises(AssertionError, FirstFree, [0, 3, 4, 6], base=3)

class TestTimeFunctions(unittest.TestCase):
  """Test case for time functions"""

  def runTest(self):
    self.assertEqual(utils.SplitTime(1), (1, 0))
    self.assertEqual(utils.SplitTime(1.5), (1, 500000))
    self.assertEqual(utils.SplitTime(1218448917.4809151), (1218448917, 480915))
    self.assertEqual(utils.SplitTime(123.48012), (123, 480120))
    self.assertEqual(utils.SplitTime(123.9996), (123, 999600))
    self.assertEqual(utils.SplitTime(123.9995), (123, 999500))
    self.assertEqual(utils.SplitTime(123.9994), (123, 999400))
    self.assertEqual(utils.SplitTime(123.999999999), (123, 999999))

    self.assertRaises(AssertionError, utils.SplitTime, -1)

    self.assertEqual(utils.MergeTime((1, 0)), 1.0)
    self.assertEqual(utils.MergeTime((1, 500000)), 1.5)
    self.assertEqual(utils.MergeTime((1218448917, 500000)), 1218448917.5)

    self.assertEqual(round(utils.MergeTime((1218448917, 481000)), 3),
                     1218448917.481)
    self.assertEqual(round(utils.MergeTime((1, 801000)), 3), 1.801)

    self.assertRaises(AssertionError, utils.MergeTime, (0, -1))
    self.assertRaises(AssertionError, utils.MergeTime, (0, 1000000))
    self.assertRaises(AssertionError, utils.MergeTime, (0, 9999999))
    self.assertRaises(AssertionError, utils.MergeTime, (-1, 0))
    self.assertRaises(AssertionError, utils.MergeTime, (-9999, 0))

class FieldSetTestCase(unittest.TestCase):
  """Test case for FieldSets"""

  def testSimpleMatch(self):
    f = utils.FieldSet("a", "b", "c", "def")
    self.failUnless(f.Matches("a"))
    self.failIf(f.Matches("d"), "Substring matched")
    self.failIf(f.Matches("defghi"), "Prefix string matched")
    self.failIf(f.NonMatching(["b", "c"]))
    self.failIf(f.NonMatching(["a", "b", "c", "def"]))
    self.failUnless(f.NonMatching(["a", "d"]))

  def testRegexMatch(self):
    f = utils.FieldSet("a", "b([0-9]+)", "c")
    self.failUnless(f.Matches("b1"))
    self.failUnless(f.Matches("b99"))
    self.failIf(f.Matches("b/1"))
    self.failIf(f.NonMatching(["b12", "c"]))
    self.failUnless(f.NonMatching(["a", "1"]))

class TestForceDictType(unittest.TestCase):
  """Test case for ForceDictType"""
  KEY_TYPES = {
    "a": constants.VTYPE_INT,
    "b": constants.VTYPE_BOOL,
    "c": constants.VTYPE_STRING,
    "d": constants.VTYPE_SIZE,
    "e": constants.VTYPE_MAYBE_STRING,
    }

  def _fdt(self, dict, allowed_values=None):
    if allowed_values is None:
      utils.ForceDictType(dict, self.KEY_TYPES)
    else:
      utils.ForceDictType(dict, self.KEY_TYPES, allowed_values=allowed_values)

    return dict

  def testSimpleDict(self):
    self.assertEqual(self._fdt({}), {})
    self.assertEqual(self._fdt({"a": 1}), {"a": 1})
    self.assertEqual(self._fdt({"a": "1"}), {"a": 1})
    self.assertEqual(self._fdt({"a": 1, "b": 1}), {"a":1, "b": True})
    self.assertEqual(self._fdt({"b": 1, "c": "foo"}), {"b": True, "c": "foo"})
    self.assertEqual(self._fdt({"b": 1, "c": False}), {"b": True, "c": ""})
    self.assertEqual(self._fdt({"b": "false"}), {"b": False})
    self.assertEqual(self._fdt({"b": "False"}), {"b": False})
    self.assertEqual(self._fdt({"b": False}), {"b": False})
    self.assertEqual(self._fdt({"b": "true"}), {"b": True})
    self.assertEqual(self._fdt({"b": "True"}), {"b": True})
    self.assertEqual(self._fdt({"d": "4"}), {"d": 4})
    self.assertEqual(self._fdt({"d": "4M"}), {"d": 4})
    self.assertEqual(self._fdt({"e": None, }), {"e": None, })
    self.assertEqual(self._fdt({"e": "Hello World", }), {"e": "Hello World", })
    self.assertEqual(self._fdt({"e": False, }), {"e": "", })
    self.assertEqual(self._fdt({"b": "hello", }, ["hello"]), {"b": "hello"})

  def testErrors(self):
    self.assertRaises(errors.TypeEnforcementError, self._fdt, {"a": "astring"})
    self.assertRaises(errors.TypeEnforcementError, self._fdt, {"b": "hello"})
    self.assertRaises(errors.TypeEnforcementError, self._fdt, {"c": True})
    self.assertRaises(errors.TypeEnforcementError, self._fdt, {"d": "astring"})
    self.assertRaises(errors.TypeEnforcementError, self._fdt, {"d": "4 L"})
    self.assertRaises(errors.TypeEnforcementError, self._fdt, {"e": object(), })
    self.assertRaises(errors.TypeEnforcementError, self._fdt, {"e": [], })
    self.assertRaises(errors.TypeEnforcementError, self._fdt, {"x": None, })
    self.assertRaises(errors.TypeEnforcementError, self._fdt, [])
    self.assertRaises(errors.ProgrammerError, utils.ForceDictType,
                      {"b": "hello"}, {"b": "no-such-type"})

class TestValidateServiceName(unittest.TestCase):
  def testValid(self):
    testnames = [
      0, 1, 2, 3, 1024, 65000, 65534, 65535,
      "ganeti",
      "gnt-masterd",
      "HELLO_WORLD_SVC",
      "hello.world.1",
      "0", "80", "1111", "65535",
      ]

    for name in testnames:
      self.assertEqual(utils.ValidateServiceName(name), name)

  def testInvalid(self):
    testnames = [
      -15756, -1, 65536, 133428083,
      "", "Hello World!", "!", "'", "\"", "\t", "\n", "`",
      "-8546", "-1", "65536",
      (129 * "A"),
      ]

    for name in testnames:
      self.assertRaises(errors.OpPrereqError, utils.ValidateServiceName, name)

class TestReadLockedPidFile(unittest.TestCase):
  def setUp(self):
    self.tmpdir = tempfile.mkdtemp()

  def tearDown(self):
    shutil.rmtree(self.tmpdir)

  def testNonExistent(self):
    path = utils.PathJoin(self.tmpdir, "nonexist")
    self.assert_(utils.ReadLockedPidFile(path) is None)

  def testUnlocked(self):
    path = utils.PathJoin(self.tmpdir, "pid")
    utils.WriteFile(path, data="123")
    self.assert_(utils.ReadLockedPidFile(path) is None)

  def testLocked(self):
    path = utils.PathJoin(self.tmpdir, "pid")
    utils.WriteFile(path, data="123")

    fl = utils.FileLock.Open(path)
    try:
      fl.Exclusive(blocking=True)

      self.assertEqual(utils.ReadLockedPidFile(path), 123)
    finally:
      fl.Close()

    self.assert_(utils.ReadLockedPidFile(path) is None)

  def testError(self):
    path = utils.PathJoin(self.tmpdir, "foobar", "pid")
    utils.WriteFile(utils.PathJoin(self.tmpdir, "foobar"), data="")
    # open(2) should return ENOTDIR
    self.assertRaises(EnvironmentError, utils.ReadLockedPidFile, path)

class TestFindMatch(unittest.TestCase):
  def test(self):
    data = {
      "aaaa": "Four A",
      "bb": {"Two B": True},
      re.compile(r"^x(foo|bar|bazX)([0-9]+)$"): (1, 2, 3),
      }

    self.assertEqual(utils.FindMatch(data, "aaaa"), ("Four A", []))
    self.assertEqual(utils.FindMatch(data, "bb"), ({"Two B": True}, []))

    for i in ["foo", "bar", "bazX"]:
      for j in range(1, 100, 7):
        self.assertEqual(utils.FindMatch(data, "x%s%s" % (i, j)),
                         ((1, 2, 3), [i, str(j)]))

  def testNoMatch(self):
    self.assert_(utils.FindMatch({}, "") is None)
    self.assert_(utils.FindMatch({}, "foo") is None)
    self.assert_(utils.FindMatch({}, 1234) is None)

    data = {
      "X": "Hello World",
      re.compile("^(something)$"): "Hello World",
      }

    self.assert_(utils.FindMatch(data, "") is None)
    self.assert_(utils.FindMatch(data, "Hello World") is None)

class TestTryConvert(unittest.TestCase):
  def test(self):
    for src, fn, result in [
      ("1", int, 1),
      ("a", int, "a"),
      ("", bool, False),
      ("a", bool, True),
      ]:
      self.assertEqual(utils.TryConvert(fn, src), result)

class TestVerifyDictOptions(unittest.TestCase):
  def setUp(self):
    self.defaults = {
      "first_key": "foobar",
      "foobar": {
        "key1": "value2",
        "key2": "value1",
        },
      "another_key": "another_value",
      }

  def test(self):
    some_keys = {
      "first_key": "blubb",
      "foobar": {
        "key2": "foo",
        },
      }
    utils.VerifyDictOptions(some_keys, self.defaults)

  def testInvalid(self):
    some_keys = {
      "invalid_key": "blubb",
      "foobar": {
        "key2": "foo",
        },
      }
    self.assertRaises(errors.OpPrereqError, utils.VerifyDictOptions,
                      some_keys, self.defaults)

  def testNestedInvalid(self):
    some_keys = {
      "foobar": {
        "key2": "foo",
        "key3": "blibb"
        },
      }
    self.assertRaises(errors.OpPrereqError, utils.VerifyDictOptions,
                      some_keys, self.defaults)

  def testMultiInvalid(self):
    some_keys = {
        "foobar": {
          "key1": "value3",
          "key6": "Right here",
        },
        "invalid_with_sub": {
          "sub1": "value3",
        },
      }
    self.assertRaises(errors.OpPrereqError, utils.VerifyDictOptions,
                      some_keys, self.defaults)

class TestValidateDeviceNames(unittest.TestCase):
  def testEmpty(self):
    utils.ValidateDeviceNames("NIC", [])
    utils.ValidateDeviceNames("disk", [])

  def testNoName(self):
    nics = [{}, {}]
    utils.ValidateDeviceNames("NIC", nics)

  def testInvalidName(self):
    self.assertRaises(errors.OpPrereqError, utils.ValidateDeviceNames,
                      "disk", [{constants.IDISK_NAME: "42"}])
    self.assertRaises(errors.OpPrereqError, utils.ValidateDeviceNames,
                      "NIC", [{constants.INIC_NAME: "42"}])

  def testUsedName(self):
    disks = [{constants.IDISK_NAME: "name1"}, {constants.IDISK_NAME: "name1"}]
    self.assertRaises(errors.OpPrereqError, utils.ValidateDeviceNames,
                      "disk", disks)

def Disk(dev_type):
  return mock.Mock(dev_type=dev_type)

def Drbd():
  return Disk(constants.DT_DRBD8)

def Rbd():
  return Disk(constants.DT_RBD)

class AllDiskTemplateTest(unittest.TestCase):
  def testAllDiskless(self):
    self.assertTrue(utils.AllDiskOfType([], [constants.DT_DISKLESS]))

  def testOrDiskless(self):
    self.assertTrue(utils.AllDiskOfType(
        [], [constants.DT_DISKLESS, constants.DT_DRBD8]))

  def testOrDrbd(self):
    self.assertTrue(utils.AllDiskOfType(
        [Drbd()], [constants.DT_DISKLESS, constants.DT_DRBD8]))

  def testOrRbd(self):
    self.assertTrue(utils.AllDiskOfType(
        [Rbd()], [constants.DT_RBD, constants.DT_DRBD8]))

  def testNotRbd(self):
    self.assertFalse(utils.AllDiskOfType(
        [Rbd()], [constants.DT_DRBD8]))

  def testNotDiskless(self):
    self.assertFalse(utils.AllDiskOfType(
        [], [constants.DT_DRBD8]))

  def testNotRbdDiskless(self):
    self.assertFalse(utils.AllDiskOfType(
        [Rbd()], [constants.DT_DISKLESS]))

  def testHeterogeneous(self):
    self.assertFalse(utils.AllDiskOfType(
        [Rbd(), Drbd()], [constants.DT_DRBD8]))

  def testHeterogeneousDiskless(self):
    self.assertFalse(utils.AllDiskOfType(
        [Rbd(), Drbd()], [constants.DT_DISKLESS]))

class AnyDiskTemplateTest(unittest.TestCase):
  def testAnyDiskless(self):
    self.assertTrue(utils.AnyDiskOfType([], [constants.DT_DISKLESS]))

  def testOrDiskless(self):
    self.assertTrue(utils.AnyDiskOfType(
        [], [constants.DT_DISKLESS, constants.DT_DRBD8]))

  def testOrDrbd(self):
    self.assertTrue(utils.AnyDiskOfType(
        [Drbd()], [constants.DT_DISKLESS, constants.DT_DRBD8]))

  def testOrRbd(self):
    self.assertTrue(utils.AnyDiskOfType(
        [Rbd()], [constants.DT_RBD, constants.DT_DRBD8]))

  def testNotRbd(self):
    self.assertFalse(utils.AnyDiskOfType(
        [Rbd()], [constants.DT_DRBD8]))

  def testNotDiskless(self):
    self.assertFalse(utils.AnyDiskOfType(
        [], [constants.DT_DRBD8]))

  def testNotRbdDiskless(self):
    self.assertFalse(utils.AnyDiskOfType(
        [Rbd()], [constants.DT_DISKLESS]))

  def testHeterogeneous(self):
    self.assertTrue(utils.AnyDiskOfType(
        [Rbd(), Drbd()], [constants.DT_DRBD8]))

  def testHeterogeneousDiskless(self):
    self.assertFalse(utils.AnyDiskOfType(
        [Rbd(), Drbd()], [constants.DT_DISKLESS]))

class GetDiskTemplateTest(unittest.TestCase):
  def testUnique(self):
    self.assertEqual(utils.GetDiskTemplate([Rbd()]), constants.DT_RBD)

  def testDiskless(self):
    self.assertEqual(utils.GetDiskTemplate([]), constants.DT_DISKLESS)

  def testMultiple(self):
    self.assertEqual(utils.GetDiskTemplate([Rbd(), Rbd()]),
                     constants.DT_RBD)

  def testMixed(self):
    self.assertEqual(utils.GetDiskTemplate([Rbd(), Drbd()]),
                     constants.DT_MIXED)

if __name__ == "__main__":
  testutils.GanetiTestProgram()


text:
<?php

namespace Symfony\Component\Security\Http\Firewall;

use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Http\Event\SwitchUserEvent;
use Symfony\Component\Security\Http\SecurityEvents;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;

/**
 * SwitchUserListener allows a user to impersonate another one temporarily
 * (like the Unix su command).
 *
 * @author Fabien Potencier <fabien@symfony.com>
 *
 * @final
 */
class SwitchUserListener extends AbstractListener
{
    const EXIT_VALUE = '_exit';

    private $tokenStorage;
    private $provider;
    private $userChecker;
    private $firewallName;
    private $accessDecisionManager;
    private $usernameParameter;
    private $role;
    private $logger;
    private $dispatcher;
    private $stateless;

    public function __construct(TokenStorageInterface $tokenStorage, UserProviderInterface $provider, UserCheckerInterface $userChecker, string $firewallName, AccessDecisionManagerInterface $accessDecisionManager, LoggerInterface $logger = null, string $usernameParameter = '_switch_user', string $role = 'ROLE_ALLOWED_TO_SWITCH', EventDispatcherInterface $dispatcher = null, bool $stateless = false)
    {
        if ('' === $firewallName) {
            throw new \InvalidArgumentException('$firewallName must not be empty.');
        }

        $this->tokenStorage = $tokenStorage;
        $this->provider = $provider;
        $this->userChecker = $userChecker;
        $this->firewallName = $firewallName;
        $this->accessDecisionManager = $accessDecisionManager;
        $this->usernameParameter = $usernameParameter;
        $this->role = $role;
        $this->logger = $logger;
        $this->dispatcher = $dispatcher;
        $this->stateless = $stateless;
    }

    /**
     * {@inheritdoc}
     */
    public function supports(Request $request): ?bool
    {
        // usernames can be falsy
        $username = $request->get($this->usernameParameter);

        if (null === $username || '' === $username) {
            $username = $request->headers->get($this->usernameParameter);
        }

        // if it's still "empty", nothing to do.
        if (null === $username || '' === $username) {
            return false;
        }

        $request->attributes->set('_switch_user_username', $username);

        return true;
    }

    /**
     * Handles the switch to another user.
     *
     * @throws \LogicException if switching to a user failed
     */
    public function authenticate(RequestEvent $event)
    {
        $request = $event->getRequest();

        $username = $request->attributes->get('_switch_user_username');
        $request->attributes->remove('_switch_user_username');

        if (null === $this->tokenStorage->getToken()) {
            throw new AuthenticationCredentialsNotFoundException('Could not find original Token object.');
        }

        if (self::EXIT_VALUE === $username) {
            $this->tokenStorage->setToken($this->attemptExitUser($request));
        } else {
            try {
                $this->tokenStorage->setToken($this->attemptSwitchUser($request, $username));
            } catch (AuthenticationException $e) {
                // Generate 403 in any conditions to prevent user enumeration vulnerabilities
                throw new AccessDeniedException('Switch User failed: '.$e->getMessage(), $e);
            }
        }

        if (!$this->stateless) {
            $request->query->remove($this->usernameParameter);
            $request->server->set('QUERY_STRING', http_build_query($request->query->all(), '', '&'));
            $response = new RedirectResponse($request->getUri(), 302);

            $event->setResponse($response);
        }
    }

    /**
     * Attempts to switch to another user and returns the new token if successfully switched.
     *
     * @throws \LogicException
     * @throws AccessDeniedException
     */
    private function attemptSwitchUser(Request $request, string $username): ?TokenInterface
    {
        $token = $this->tokenStorage->getToken();
        $originalToken = $this->getOriginalToken($token);

        if (null !== $originalToken) {
            if ($token->getUsername() === $username) {
                return $token;
            }

            // User already switched, exit before seamlessly switching to another user
            $token = $this->attemptExitUser($request);
        }

        $currentUsername = $token->getUsername();
        $nonExistentUsername = '_'.md5(random_bytes(8).$username);

        // To protect against user enumeration via timing measurements
        // we always load both successfully and unsuccessfully
        try {
            $user = $this->provider->loadUserByUsername($username);

            try {
                $this->provider->loadUserByUsername($nonExistentUsername);
            } catch (\Exception $e) {
            }
        } catch (AuthenticationException $e) {
            $this->provider->loadUserByUsername($currentUsername);

            throw $e;
        }

        if (false === $this->accessDecisionManager->decide($token, [$this->role], $user)) {
            $exception = new AccessDeniedException();
            $exception->setAttributes($this->role);

            throw $exception;
        }

        if (null !== $this->logger) {
            $this->logger->info('Attempting to switch to user.', ['username' => $username]);
        }

        $this->userChecker->checkPostAuth($user);

        $roles = $user->getRoles();
        $roles[] = 'ROLE_PREVIOUS_ADMIN';
        $token = new SwitchUserToken($user, $user->getPassword(), $this->firewallName, $roles, $token);

        if (null !== $this->dispatcher) {
            $switchEvent = new SwitchUserEvent($request, $token->getUser(), $token);
            $this->dispatcher->dispatch($switchEvent, SecurityEvents::SWITCH_USER);
            // use the token from the event in case any listeners have replaced it.
            $token = $switchEvent->getToken();
        }

        return $token;
    }

    /**
     * Attempts to exit from an already switched user and returns the original token.
     *
     * @throws AuthenticationCredentialsNotFoundException
     */
    private function attemptExitUser(Request $request): TokenInterface
    {
        if (null === ($currentToken = $this->tokenStorage->getToken()) || null === $original = $this->getOriginalToken($currentToken)) {
            throw new AuthenticationCredentialsNotFoundException('Could not find original Token object.');
        }

        if (null !== $this->dispatcher && $original->getUser() instanceof UserInterface) {
            $user = $this->provider->refreshUser($original->getUser());
            $switchEvent = new SwitchUserEvent($request, $user, $original);
            $this->dispatcher->dispatch($switchEvent, SecurityEvents::SWITCH_USER);
            $original = $switchEvent->getToken();
        }

        return $original;
    }

    private function getOriginalToken(TokenInterface $token): ?TokenInterface
    {
        if ($token instanceof SwitchUserToken) {
            return $token->getOriginalToken();
        }

        return null;
    }
}


text:
package org.tenidwa.collections.utils;

import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.stream.Stream;
import org.junit.Assert;
import org.junit.Test;

public final class StreamIterableTest {
    @Test
    public void containsRightElements() {
        final Iterator<Integer> iterator = new StreamIterable<>(
            Arrays.asList(1, 2, 3, 4).stream()
        )
            .iterator();
        Assert.assertTrue(iterator.hasNext());
        Assert.assertEquals(1, (int) iterator.next());
        Assert.assertTrue(iterator.hasNext());
        Assert.assertEquals(2, (int) iterator.next());
        Assert.assertTrue(iterator.hasNext());
        Assert.assertEquals(3, (int) iterator.next());
        Assert.assertTrue(iterator.hasNext());
        Assert.assertEquals(4, (int) iterator.next());
        Assert.assertFalse(iterator.hasNext());
    }

    @Test(expected = NoSuchElementException.class)
    public void canWorkWithEmptyStream() {
        new StreamIterable<>(Stream.of())
            .iterator()
            .next();
    }

}


text:
/**
 * @fileoverview Rule to check the spacing around the * in generator functions.
 * @author Jamund Ferguson
 */

"use strict";

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

module.exports = {
    meta: {
        docs: {
            description: "enforce consistent spacing around `*` operators in generator functions",
            category: "ECMAScript 6",
            recommended: false
        },

        fixable: "whitespace",

        schema: [
            {
                oneOf: [
                    {
                        enum: ["before", "after", "both", "neither"]
                    },
                    {
                        type: "object",
                        properties: {
                            before: { type: "boolean" },
                            after: { type: "boolean" }
                        },
                        additionalProperties: false
                    }
                ]
            }
        ]
    },

    create(context) {

        const mode = (function(option) {
            if (!option || typeof option === "string") {
                return {
                    before: { before: true, after: false },
                    after: { before: false, after: true },
                    both: { before: true, after: true },
                    neither: { before: false, after: false }
                }[option || "before"];
            }
            return option;
        }(context.options[0]));

        const sourceCode = context.getSourceCode();

        /**
         * Checks if the given token is a star token or not.
         *
         * @param {Token} token - The token to check.
         * @returns {boolean} `true` if the token is a star token.
         */
        function isStarToken(token) {
            return token.value === "*" && token.type === "Punctuator";
        }

        /**
         * Gets the generator star token of the given function node.
         *
         * @param {ASTNode} node - The function node to get.
         * @returns {Token} Found star token.
         */
        function getStarToken(node) {
            return sourceCode.getFirstToken(
                (node.parent.method || node.parent.type === "MethodDefinition") ? node.parent : node,
                isStarToken
            );
        }

        /**
         * Checks the spacing between two tokens before or after the star token.
         * @param {string} side Either "before" or "after".
         * @param {Token} leftToken `function` keyword token if side is "before", or
         *     star token if side is "after".
         * @param {Token} rightToken Star token if side is "before", or identifier
         *     token if side is "after".
         * @returns {void}
         */
        function checkSpacing(side, leftToken, rightToken) {
            if (!!(rightToken.range[0] - leftToken.range[1]) !== mode[side]) {
                const after = leftToken.value === "*";
                const spaceRequired = mode[side];
                const node = after ? leftToken : rightToken;
                const type = spaceRequired ? "Missing" : "Unexpected";
                const message = "{{type}} space {{side}} *.";
                const data = {
                    type,
                    side
                };

                context.report({
                    node,
                    message,
                    data,
                    fix(fixer) {
                        if (spaceRequired) {
                            if (after) {
                                return fixer.insertTextAfter(node, " ");
                            }
                            return fixer.insertTextBefore(node, " ");
                        }
                        return fixer.removeRange([leftToken.range[1], rightToken.range[0]]);
                    }
                });
            }
        }

        /**
         * Enforces the spacing around the star if node is a generator function.
         * @param {ASTNode} node A function expression or declaration node.
         * @returns {void}
         */
        function checkFunction(node) {
            if (!node.generator) {
                return;
            }

            const starToken = getStarToken(node);

            // Only check before when preceded by `function`|`static` keyword
            const prevToken = sourceCode.getTokenBefore(starToken);

            if (prevToken.value === "function" || prevToken.value === "static") {
                checkSpacing("before", prevToken, starToken);
            }

            const nextToken = sourceCode.getTokenAfter(starToken);

            checkSpacing("after", starToken, nextToken);
        }

        return {
            FunctionDeclaration: checkFunction,
            FunctionExpression: checkFunction
        };

    }
};


text:
/* $chaos: queue.c,v 1.4 2002/10/04 19:01:21 per Exp $ */
/* Author: Per Lundberg <per@chaosdev.org>
           Georg Kraml <georg@purists.org> */

/* Copyright 2002 chaos development. */
/* Use freely under the terms listed in the file LICENSE. */

#include <storm/defines.h>
#include <storm/queue.h>

/*
 *  queue_init: Initialize queue.
 *
 *  Parameters:
 *
 *    q		Pointer to a queue, or NULL if the user wishes to leave
 *		it to queue_init to allocate the queue.
 *
 *  Return values:
 *
 *    non-NULL  Queue has been initialized.
 *
 *    NULL	Insufficient memory.
 */
struct queue *queue_init(struct queue *q)
{
  if (q || (q = malloc(sizeof(struct queue))) != NULL) {
    q->begin = NULL;
    q->end = &q->begin;
  }
  return q;
}

/*
 *  queue_insert: append an item to the queue.
 *
 *  Parameters:
 *
 *    q		Pointer to a queue. It is assumed the queue has been
 *		initialized by a call to queue_init.
 *
 *    d		Item to be appended.
 *
 *  Return values:
 *
 *    1 	The item has been appended.
 *
 *    0		The item could not be appended. Either the queue
 *              pointer provided was NULL, or the function was unable
 *              to allocate the amount of memory needed for a new
 *              queue item.
 */
int queue_insert(struct queue *q, QDATUM d)
{
  if (!q || !(*q->end = malloc(sizeof(struct qentry)))) return 0;
  (*q->end)->d = d;
  (*q->end)->next = NULL;
  q->end = &((*q->end)->next);
  return 1;
}

/*
 *  queue_remove: remove an item from the queue.
 *
 *  Parameters:
 *
 *    q		Pointer to a queue.
 *
 *    d		Pointer to the QDATUM variable that will hold the datum
 *		corresponding to the queue item.
 *
 *  Return values:
 *
 *    non-NULL	An item has been removed. The variable that d points
 *              to now contains the datum associated with the item
 *              in question.
 *
 *    NULL	No item could be removed. Either the queue pointer
 *              provided was NULL, or the queue was empty. The memory
 *              location that d points to has not been modified.
 */
QDATUM *queue_remove(struct queue *q, QDATUM *d)
{
  struct qentry *tmp;

  if (!q || !q->begin) return NULL;
  tmp = q->begin;
  if (!(q->begin = q->begin->next)) q->end = &q->begin;
  *d = tmp->d;
  free(tmp);
  return d;
}

/*
 *  queue_peek: access an item without removing it from the queue.
 *
 *  Parameters:
 *
 *    q		Pointer to a queue.
 *
 *    d		Pointer to the QDATUM variable that will hold the datum
 *		associated with the first item in the queue, i. e.,
 *		the item that would be removed had queue_remove been called
 *		instead of queue_peek.
 *
 *  Return values:
 *
 *    See qremove.
 */
QDATUM *queue_peek(struct queue *q, QDATUM *d)
{
  if (!q || !q->begin) return NULL;
  *d = q->begin->d;
  return d;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using System.Collections.ObjectModel;
using ArcGIS.Desktop.Mapping;
using System.Windows.Data;
using ArcGIS.Desktop.Catalog;
using ArcGIS.Core.Data;
using ArcGIS.Desktop.Core;
using System.Windows.Input;
using ArcGIS.Desktop.Core.Events;
using ArcGIS.Core.Geometry;
using ArcGIS.Desktop.Framework.Dialogs;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using System.Windows.Threading;

namespace OpenMapViews
{
    internal class OpenMapviewsDockpaneViewModel : DockPane
    {
        private const string _dockPaneID = "OpenMapViews_OpenMapviewsDockpane";

        /// <summary>
        /// used to lock collections for use by multiple threads
        /// </summary>
        private readonly object _lockCollection = new object();
        private ObservableCollection<MapviewItem> _listOfMapviews = new ObservableCollection<MapviewItem>();
        private MapviewItem _selectedMapview;

        private string _temporaryPath = string.Empty;

        /// <summary>
        /// CTor
        /// </summary>
        public OpenMapviewsDockpaneViewModel()
        {
            BindingOperations.EnableCollectionSynchronization(ListOfMapviews, _lockCollection);

            // create a simulated list of mapviews
            // either when a project is opened or if a project is already open
            ProjectOpenedEvent.Subscribe((ProjectEventArgs e) => { CreateMapviewItemsAsync(); });
            if (Project.Current != null) CreateMapviewItemsAsync();

            ProjectClosedEvent.Subscribe((ProjectEventArgs e) =>
            {
                // cleanup temp folder
                if (!string.IsNullOrEmpty(_temporaryPath)) System.IO.Directory.Delete(_temporaryPath, true);
                _temporaryPath = string.Empty;
            });
        }

        public ObservableCollection<MapviewItem> ListOfMapviews
        {
            get { return _listOfMapviews; }
        }

        /// <summary>
        /// Because we need a type of 'index' that allows create a set of maps and
        /// corresponding mapviews.  The 'index' is then displayed in a datagrid on a dockpane.
        /// Selecting an item on the datagrid will either show or hide the associated mapview pane
        /// </summary>
        private void CreateMapviewItemsAsync()
        {
            if (Project.Current == null)
            {
                lock (_lockCollection)
                {
                    ListOfMapviews.Clear();
                }
                return;
            }
            IEnumerable<GDBProjectItem> gdbProjectItems = Project.Current.GetItems<GDBProjectItem>();
            QueuedTask.Run(() =>
            {
                lock (_lockCollection)
                {
                    ListOfMapviews.Clear();
                }
                bool bFound = false;
                if (string.IsNullOrEmpty(_temporaryPath)) _temporaryPath = System.IO.Path.GetTempPath();
                foreach (GDBProjectItem gdbProjectItem in gdbProjectItems)
                {
                    using (Datastore datastore = gdbProjectItem.GetDatastore())
                    {
                        //Unsupported datastores (non File GDB and non Enterprise GDB) will be of type UnknownDatastore
                        if (datastore is UnknownDatastore)
                            continue;

                        Geodatabase geodatabase = datastore as Geodatabase;
                        // Use the geodatabase.
                        try
                        {
                            var statesFeature = geodatabase.GetDefinition<FeatureClassDefinition>("states");
                            var shortNameIdx = statesFeature.FindField("STATE_ABBR");
                            var fipsNumberIdx = statesFeature.FindField("STATE_FIPS");
                            var geoIdx = statesFeature.FindField(statesFeature.GetShapeField());
                            if (shortNameIdx >= 0 && fipsNumberIdx >= 0)
                            {
                                using (FeatureClass fcStates = geodatabase.OpenDataset<FeatureClass>(statesFeature.GetName()))
                                {
                                    var fcRowCursor = fcStates.Search(new QueryFilter { SubFields= "STATE_ABBR,STATE_FIPS,Shape", WhereClause = "1 = 1", PostfixClause = "order by STATE_ABBR" });
                                    while (fcRowCursor.MoveNext())
                                    {
                                        using (Row row = fcRowCursor.Current)
                                        {
                                            var mapName = row[shortNameIdx].ToString();
                                            var mapNumber = Convert.ToUInt16(row[fipsNumberIdx]);
                                            var geometry = row[geoIdx] as Geometry;
                                            lock (_lockCollection)
                                            {
                                                if (!ListOfMapviews.Any((x) => x.MapName == mapName))
                                                {
                                                    ListOfMapviews.Add(new MapviewItem
                                                    {
                                                        MapName = mapName,
                                                        MapNumber = mapNumber,
                                                        Extent = geometry.Extent.Expand(1.1, 1.1, true)
                                                    });
                                                }
                                            }
                                            bFound = true;
                                        }
                                    }
                                }
                            }
                        }
                        catch
                        {
                            // no state feature class found
                        }
                    }
                }
                if (!bFound)
                {
                    lock (_lockCollection)
                    {
                        ListOfMapviews.Add(new MapviewItem { MapName = "No 'States' Feature class" });
                    }
                }
            });
        }

        /// <summary>
        /// a map view item was selected -> create the Map and display the map pane
        /// </summary>
        public MapviewItem SelectedMapview
        {
            get { return _selectedMapview; }
            set
            {
                SetProperty(ref _selectedMapview, value, () => SelectedMapview);
                if (_selectedMapview != null)
                {
                    System.Diagnostics.Debug.WriteLine("SelectedMapview start");
                    CreateAndViewMapPane(_selectedMapview);
                    System.Diagnostics.Debug.WriteLine("SelectedMapview end");
                }
            }
        }

        /// <summary>
        /// Creates a new mapviewpane (and a map as well if need-be) or closes the mapviewpane if it already exists
        /// </summary>
        /// <param name="selectedMapview"></param>
        private async void CreateAndViewMapPane(MapviewItem selectedMapview)
        {
            try
            {
                System.Diagnostics.Debug.WriteLine("CreateAndViewMapPane start");
                var newMapName = selectedMapview.MapviewName;
                {
                    var mapPanes = ProApp.Panes.OfType<IMapPane>();
                    foreach (Pane pane in mapPanes)
                    {
                        if (pane.Caption == newMapName)
                        {
                            ProApp.Panes.ClosePane(pane.InstanceID);
                            UpdateHasMapView(selectedMapview.MapName, false);
                            return;
                        }
                    }
                }
                var newExtent = selectedMapview.Extent;
                // we need to find or create a map with a given selectedMapview.MapviewName
                // 1: does the map already exist?
                MapProjectItem mapProjItem = Project.Current.GetItems<MapProjectItem>().FirstOrDefault(item =>
                                                                item.Name.Equals(newMapName));
                if (mapProjItem != null)
                {
                    // we found the existing MapProjectItem
                    var mapPanes = ProApp.Panes.OfType<IMapPane>();
                    foreach (Pane pane in mapPanes)
                    {
                        if (pane.Caption == newMapName)
                        {
                            ProApp.Panes.ClosePane(pane.InstanceID);
                            UpdateHasMapView(selectedMapview.MapName, false);
                            return;
                        }
                    }
                    //Opening the map in a mapview
                    await QueuedTask.Run(async () =>
                    {
                        await ProApp.Panes.CreateMapPaneAsync(mapProjItem.GetMap());
                    });
                    UpdateHasMapView(selectedMapview.MapName, true);
                }
                else
                {
                    await CreateMapThruCopy(newMapName, newExtent);
                    UpdateHasMapView(selectedMapview.MapName, true);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($@"An error occurred in CreateAndViewMapPane: {ex.ToString()}");
            }
            finally
            {
                System.Diagnostics.Debug.WriteLine("CreateAndViewMapPane end");
            }
        }

        /// <summary>
        /// Takes a map as a template and makes a copy of that map with a given new map name and extent
        /// </summary>
        /// <param name="newMapName"></param>
        /// <param name="newExtent"></param>
        /// <returns></returns>
        private async Task CreateMapThruCopy(string newMapName, Envelope newExtent)
        {
            // we have to create a new Map from any existing Map and then
            // add it as MapProjectItem item
            MapProjectItem mapTemplateProjItem = Project.Current.GetItems<MapProjectItem>().FirstOrDefault();
            var newMapPane = await QueuedTask.Run(async () =>
            {
                var mapTemplate = mapTemplateProjItem.GetMap();
                var theNewMap = MapFactory.Instance.CopyMap(mapTemplate);
                var defMap = theNewMap.GetDefinition();
                defMap.DefaultExtent = newExtent;
                defMap.Name = newMapName;
                theNewMap.SetDefinition(defMap);
                return await ProApp.Panes.CreateMapPaneAsync(theNewMap);
            });
        }

        /// <summary>
        /// Checks or Unchecks the "HasViewPane" checkbox.  Then clears the current selection
        /// </summary>
        /// <param name="MapName"></param>
        /// <param name="newHasMapView"></param>
        private void UpdateHasMapView (string MapName, bool newHasMapView)
        {
            Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() =>
               {
                   lock (_lockCollection)
                   {
                       if (SelectedMapview != null)
                       {
                           System.Diagnostics.Debug.WriteLine("UpdateHasMapView start");
                           SelectedMapview.HasViewPane = newHasMapView;
                           // clear the selection
                           SelectedMapview = null;
                           System.Diagnostics.Debug.WriteLine("UpdateHasMapView end");
                       }
                   }
               }));
        }

        #region Helpers

        /// <summary>
        /// Replaces the class content of a given json class tag
        /// </summary>
        /// <param name="json"></param>
        /// <param name="className"></param>
        /// <param name="newClassContent"></param>
        /// <param name="fileName">Used in case of exception</param>
        /// <returns>updated json string</returns>
        private string ReplaceJsonClass(string json, string className, string newClassContent, string fileName)
        {
            var searchPattern = $@"""{className}"" : {{";
            var idx = json.IndexOf(searchPattern);
            if (idx < 0) throw new Exception($"A format problem was encounter in the mapx file: {fileName}");
            idx--;
            idx += searchPattern.Length;
            var idxEnd = FindClosingTag (json, idx);
            var changedContent = json.Remove(idx, idxEnd - idx);
            return changedContent.Insert(idx, newClassContent);
        }

        private int FindClosingTag(string json, int idx)
        {
            var idxCloseTag = idx;
            var idxEnd = json.Length;
            var indent = 0;
            while (idxCloseTag < idxEnd)
            {
                switch (json[idxCloseTag])
                {
                    case '{':
                        indent++;
                        break;
                    case '}':
                        indent--;
                        if (indent == 0)
                        {
                            // closing tag
                            return idxCloseTag + 1;
                        }
                        break;
                }
                idxCloseTag++;
            }
            return idxCloseTag;
        }

        /// <summary>
        /// Replaces the string content of a given json tag
        /// </summary>
        /// <param name="json"></param>
        /// <param name="stringName"></param>
        /// <param name="newStringContent"></param>
        /// <param name="fileName">Used in case of exception</param>
        /// <returns>updated json string</returns>
        private string ReplaceJsonString(string json, string stringName, string newStringContent, string fileName)
        {
            var searchPattern = $@"""{stringName}"" : """;
            var idx = json.IndexOf(searchPattern);
            if (idx < 0) throw new Exception($"A format problem was encounter in the mapx file: {fileName}");
            idx += searchPattern.Length;
            var idxEnd = json.IndexOf(@"""", idx);
            var changedContent = json.Remove(idx, idxEnd - idx);
            return changedContent.Insert(idx, newStringContent);
        }

        #endregion Helpers

        /// <summary>
        /// Show the DockPane.
        /// </summary>
        internal static void Show()
        {
            DockPane pane = FrameworkApplication.DockPaneManager.Find(_dockPaneID);
            if (pane == null)
                return;

            pane.Activate();
        }

        /// <summary>
        /// Text shown near the top of the DockPane.
        /// </summary>
        private string _heading = "Select to show/hide view Map";
        public string Heading
        {
            get { return _heading; }
            set
            {
                SetProperty(ref _heading, value, () => Heading);
            }
        }
    }

    /// <summary>
    /// Button implementation to show the DockPane.
    /// </summary>
    internal class OpenMapviewsDockpane_ShowButton : Button
    {
        protected override void OnClick()
        {
            OpenMapviewsDockpaneViewModel.Show();
        }
    }
}


text:
package com.mapsindoors.stdapp.helpers;

import com.mapsindoors.stdapp.BuildConfig;

public class AppDevSettings
{

	public static final boolean ENABLE_MI_DEV_DEBUG = BuildConfig.DEBUG;

	public static final boolean ENABLE_ANALYTICS = !BuildConfig.DEBUG;

	public static final boolean ENABLE_LEAKCANARY = BuildConfig.DEBUG;

	public static final boolean ENABLE_OS_STRICTMODE = false;

	public static final boolean DEBUG_PICASSO_ENABLED = false;
}


text:
@interface PodsDummy_Pods_MAGPdfGenerator_Example : NSObject
@end
@implementation PodsDummy_Pods_MAGPdfGenerator_Example
@end


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="shortcut icon" href="../../assets/icons/icon.ico" type="image/ico">

<link rel="stylesheet" href="../../fractal/css/default.css?cachebust=1.4.0" type="text/css">

<link rel="stylesheet" href="../../assets/styles/theme.css?cachebust=1.4.0" type="text/css">

<link rel="stylesheet" href="../../fractal/css/highlight.css?cachebust=1.4.0" type="text/css">

<title>Preface: Default | Bits of 24 ways</title>

    <button class="Header-button Header-navToggle" data-action="toggle-sidebar">

            <svg height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg">
    <path d="M0 0h24v24H0z" fill="none"/>
    <path d="M19 6.4L17.6 5 12 10.6 6.4 5 5 6.4 10.6 12 5 17.6 6.4 19 12 13.4 17.6 19 19 17.6 13.4 12z"/>
</svg>

            <svg height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg">
    <path d="M0 0h24v24H0z" fill="none"/>
    <path d="M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z"/>
</svg>

    </button>
    Bits of 24 ways

            Preface: Default
            <svg fill="#000000" height="22" viewBox="0 0 24 24" width="22" xmlns="http://www.w3.org/2000/svg">
    <path d="M0 0h24v24H0z" fill="none"/>
    <path d="M19 4H5c-1.11 0-2 .9-2 2v12c0 1.1.89 2 2 2h4v-2H5V8h14v10h-4v2h4c1.1 0 2-.9 2-2V6c0-1.1-.89-2-2-2zm-7 6l-4 4h3v6h2v-6h3l-4-4z"/>
</svg>

            HTML

            View

            Context

            Assets

            Info

            Notes

<header class="c-preface">
    <h1 class="c-preface__title">Preface title
    </h1>
    <div class="c-preface__main">
        <div class="s-prose">
            <p>Preface content</p>

        </div>
    </div>
</header>

<header class="c-preface{{ "  h-card" if microformats }}">
  <h1 class="c-preface__title{{ "  p-name" if microformats }}">
    {%- if titleIcon -%}
      {% include titleIcon + ".svg" %}
    {%- endif -%}
    {{ title }}
  </h1>
  {%- if content -%}
  <div class="c-preface__main{{ "  p-note" if microformats }}">
    <div class="s-prose">
      {%- if avatar -%}
        {% render "@avatar", avatar %}
      {%- endif -%}
      {{ content | markdown | safe }}
    </div>
  </div>
  {%- endif -%}
</header>

{
  "site": {
    "title": "24 ways",
    "handle": "24ways",
    "description": "24 ways is the advent calendar for web geeks. Each day throughout December we publish a daily dose of web design and development goodness to bring you all a little Christmas cheer.",
    "url": "https://24ways.org",
    "feed": "https://feeds.feedburner.com/24ways",
    "theme_color": "#f04"
  },
  "theme": {
    "year": [
      348,
      344,
      340,
      336,
      332,
      328,
      324,
      320,
      316,
      312,
      308,
      304,
      300,
      296,
      292,
      288
    ],
    "day": [
      360,
      353,
      346,
      339,
      332,
      325,
      318,
      311,
      304,
      297,
      290,
      283,
      276,
      269,
      262,
      255,
      248,
      241,
      234,
      227,
      220,
      213,
      206,
      199
    ]
  },
  "title": "Preface title",
  "content": "Preface content"
}

            File:
            <select class="FileBrowser-select" id="filebrowser-select">

                <option value="file-dee8600d1ba310da0ff02ed02a3a93e1">preface.css</option>

            </select>

                    Content:

.c-preface {
  overflow: hidden;
  display: flex;
  flex-direction: column;
  padding: map(spaces, medium) map(spaces, large) calc(map(spaces, large) / 2);
  background-color: $color-year;
  background-color: var(--color-year, $color-year);
  background-image: inline('diamond.svg');
  background-repeat: repeat;

  @media (--from-medium-screen) {
    min-height: 9rem;
  }

  @media (--from-large-screen) {
    padding-top: map(spaces, xxlarge);
    padding-left: 25%;
  }
}

.c-preface__title {
  @apply --typeset-title;

  display: flex;
  align-items: flex-start;
  position: relative;
  margin-top: auto;
  color: map(colors, primary, light);

  svg {
    width: 1em;
    height: 1em;
    margin-right: map(spaces, small);
  }
}

.c-preface__main {
  position: relative;
  margin-top: map(spaces, small);
  color: color(white a(75%));

  .s-prose p:first-of-type {
    @apply --typeset-lede;
  }

  .s-prose p:last-of-type {
    margin-bottom: 0;
  }

  .c-avatar {
    width: 50%;
    float: right;
    margin-top: -7.5%;
    margin-right: -7.5%;

    @media (--from-large-screen) {
      width: auto;
      float: left;
      margin-left: -33%;
      margin-right: map(spaces, medium);
    }
  }

  a {
    border-bottom: 1px solid color(white a(25%));
    color: white;

    &:hover {
      border-bottom-color: color(white a(25%));
    }
  }
}

                    URL:
                    /components/raw/preface/preface.css

                    Filesystem Path:
                    src/components/common/preface/preface.css

                    Size:
                    1.4 KB

            Handle:
            @preface--default

            Variants (3):

                    Default
                ,

                    Topic
                ,

                    Author

            Preview:

With layout <svg fill="#000000" height="22" viewBox="0 0 24 24" width="22" xmlns="http://www.w3.org/2000/svg">
    <path d="M0 0h24v24H0z" fill="none"/>
    <path d="M19 4H5c-1.11 0-2 .9-2 2v12c0 1.1.89 2 2 2h4v-2H5V8h14v10h-4v2h4c1.1 0 2-.9 2-2V6c0-1.1-.89-2-2-2zm-7 6l-4 4h3v6h2v-6h3l-4-4z"/>
</svg>

Component only <svg fill="#000000" height="22" viewBox="0 0 24 24" width="22" xmlns="http://www.w3.org/2000/svg">
    <path d="M0 0h24v24H0z" fill="none"/>
    <path d="M19 4H5c-1.11 0-2 .9-2 2v12c0 1.1.89 2 2 2h4v-2H5V8h14v10h-4v2h4c1.1 0 2-.9 2-2V6c0-1.1-.89-2-2-2zm-7 6l-4 4h3v6h2v-6h3l-4-4z"/>
</svg>

            Filesystem Path:
            src/components/common/preface/preface.html

            References (1):

                @avatar

            Referenced by (11):

                @content-template,

                @content-template--404,

                @content-template--sponsorship,

                @index-template,

                @index-template--archives,

                @index-template--authors,

                @listing-template,

                @listing-template--topic,

                @listing-template--archive,

                @listing-template--author,

                @listing-template--search-results

There are no notes for this item.

    <form action="" class="Search" data-behaviour="search">
        Search
        <input class="Search-input" id="search-input" type="search" placeholder="Search…" data-role="input">
        <button type="button" data-behaviour="clear-search" class="Search-clearButton" aria-label="Clear search" hidden>
            <svg height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg">
    <path d="M0 0h24v24H0z" fill="none"/>
    <path d="M19 6.4L17.6 5 12 10.6 6.4 5 5 6.4 10.6 12 5 17.6 6.4 19 12 13.4 17.6 19 19 17.6 13.4 12z"/>
</svg>

        </button>
    </form>

components

        <button type="button" data-behaviour="collapse-tree" class="Tree-collapse" title="Collapse tree" aria-label="Collapse tree" hidden>
            <svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="m9 11c-.6 0-1 .4-1 1s.4 1 1 1h6c.6 0 1-.4 1-1s-.4-1-1-1z"/><path d="m19 21h-14c-1.1 0-2-.9-2-2v-14c0-1.1.9-2 2-2h14c1.1 0 2 .9 2 2v14c0 1.1-.9 2-2 2zm-14-16v14h14v-14z"/></svg>

        </button>

                OG Image

            <button class="Tree-collectionLabel" data-role="toggle" aria-expanded="true" aria-controls="tree-components-collection-utilities-items">
                Utilities
            </button>

                Hidden

            <button class="Tree-collectionLabel" data-role="toggle" aria-expanded="true" aria-controls="tree-components-collection-common-items">
                Common
            </button>

                Article

                Author

                Avatar

                Backdrop

                Button

                Comment

                Comment Form

                Continue

                Field

            <button class="Tree-collectionLabel" data-role="toggle" aria-expanded="true" aria-controls="tree-components-collection-listing-items">
                Listing
            </button>

                Default

                Inset

                Authors

                Meta

                Preface

                Promo

                Search Form

                Section

                Summary

            <button class="Tree-collectionLabel" data-role="toggle" aria-expanded="true" aria-controls="tree-components-collection-global-items">
                Global
            </button>

                Banner

                Contentinfo

                Menu

                Search

                Site Nav

                Topics Nav

                Traverse Nav

            <button class="Tree-collectionLabel" data-role="toggle" aria-expanded="true" aria-controls="tree-components-collection-scopes-items">
                Scopes
            </button>

                Embed

                Gallery

                Note

            <button class="Tree-collectionLabel" data-role="toggle" aria-expanded="true" aria-controls="tree-components-collection-prose-items">
                Prose
            </button>

                Default

                Article

                Syntax

            <button class="Tree-collectionLabel" data-role="toggle" aria-expanded="true" aria-controls="tree-components-collection-templates-items">
                Templates
            </button>

                Article Template

            <button class="Tree-collectionLabel" data-role="toggle" aria-expanded="true" aria-controls="tree-components-collection-content-template-items">
                Content Template
            </button>

                About

                404

                Sponsorship

            <button class="Tree-collectionLabel" data-role="toggle" aria-expanded="true" aria-controls="tree-components-collection-index-template-items">
                Index Template
            </button>

                Topics

                Archives

                Authors

            <button class="Tree-collectionLabel" data-role="toggle" aria-expanded="true" aria-controls="tree-components-collection-listing-template-items">
                Listing Template
            </button>

                Home

                Topic

                Archive

                Author

                Search Results

documentation

        <button type="button" data-behaviour="collapse-tree" class="Tree-collapse" title="Collapse tree" aria-label="Collapse tree" hidden>
            <svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="m9 11c-.6 0-1 .4-1 1s.4 1 1 1h6c.6 0 1-.4 1-1s-.4-1-1-1z"/><path d="m19 21h-14c-1.1 0-2-.9-2-2v-14c0-1.1.9-2 2-2h14c1.1 0 2 .9 2 2v14c0 1.1-.9 2-2 2zm-14-16v14h14v-14z"/></svg>

        </button>

                Design tokens


text:
package google

import (
	"fmt"
	"strings"
	"testing"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
	"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
)

func TestAccMonitoringGroup_monitoringGroupBasicExample(t *testing.T) {
	t.Parallel()

	context := map[string]interface{}{
		"random_suffix": randString(t, 10),
	}

	vcrTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckMonitoringGroupDestroyProducer(t),
		Steps: []resource.TestStep{
			{
				Config: testAccMonitoringGroup_monitoringGroupBasicExample(context),
			},
			{
				ResourceName:      "google_monitoring_group.basic",
				ImportState:       true,
				ImportStateVerify: true,
			},
		},
	})
}

func testAccMonitoringGroup_monitoringGroupBasicExample(context map[string]interface{}) string {
	return Nprintf(`
resource "google_monitoring_group" "basic" {
  display_name = "tf-test MonitoringGroup%{random_suffix}"

  filter = "resource.metadata.region=\"europe-west2\""
}
`, context)
}

func TestAccMonitoringGroup_monitoringGroupSubgroupExample(t *testing.T) {
	t.Parallel()

	context := map[string]interface{}{
		"random_suffix": randString(t, 10),
	}

	vcrTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckMonitoringGroupDestroyProducer(t),
		Steps: []resource.TestStep{
			{
				Config: testAccMonitoringGroup_monitoringGroupSubgroupExample(context),
			},
			{
				ResourceName:      "google_monitoring_group.subgroup",
				ImportState:       true,
				ImportStateVerify: true,
			},
		},
	})
}

func testAccMonitoringGroup_monitoringGroupSubgroupExample(context map[string]interface{}) string {
	return Nprintf(`
resource "google_monitoring_group" "parent" {
  display_name = "tf-test MonitoringParentGroup%{random_suffix}"
  filter       = "resource.metadata.region=\"europe-west2\""
}

resource "google_monitoring_group" "subgroup" {
  display_name = "tf-test MonitoringSubGroup%{random_suffix}"
  filter       = "resource.metadata.region=\"europe-west2\""
  parent_name  =  google_monitoring_group.parent.name
}
`, context)
}

func testAccCheckMonitoringGroupDestroyProducer(t *testing.T) func(s *terraform.State) error {
	return func(s *terraform.State) error {
		for name, rs := range s.RootModule().Resources {
			if rs.Type != "google_monitoring_group" {
				continue
			}
			if strings.HasPrefix(name, "data.") {
				continue
			}

			config := googleProviderConfig(t)

			url, err := replaceVarsForTest(config, rs, "{{MonitoringBasePath}}v3/{{name}}")
			if err != nil {
				return err
			}

			billingProject := ""

			if config.BillingProject != "" {
				billingProject = config.BillingProject
			}

			_, err = sendRequest(config, "GET", billingProject, url, config.userAgent, nil, isMonitoringConcurrentEditError)
			if err == nil {
				return fmt.Errorf("MonitoringGroup still exists at %s", url)
			}
		}

		return nil
	}
}


text:
import { Injectable } from '@angular/core';
import { MdSnackBar, MdSnackBarRef } from '@angular/material';

@Injectable()
export class SnackbarService {

  constructor (
    private snackbar: MdSnackBar
  ) { }

  /**
   * Opens a success snackbar.
   *
   * @param   {string}                        message The message to show in the snackbar.
   * @param   {string}                        action  The label for the snackbar action.
   * @returns {MdSnackBarRef<SimpleSnackBar>}
   */
  success (message: string, action?: any) {
    return this._snackbar('success', message, action);
  }

  /**
   * Opens an info snackbar.
   *
   * @param   {string}                        message The message to show in the snackbar.
   * @param   {string}                        action  The label for the snackbar action.
   * @returns {MdSnackBarRef<SimpleSnackBar>}
   */
  info (message: string, action?: any) {
    return this._snackbar('info', message, action);
  }

  /**
   * Opens a warning snackbar.
   *
   * @param   {string}                        message The message to show in the snackbar.
   * @param   {string}                        action  The label for the snackbar action.
   * @returns {MdSnackBarRef<SimpleSnackBar>}
   */
  warning (message: string, action?: any) {
    return this._snackbar('warning', message, action);
  }

  /**
   * Opens an error snackbar.
   *
   * @param   {string}                        message The message to show in the snackbar.
   * @param   {string}                        action  The label for the snackbar action.
   * @returns {MdSnackBarRef<SimpleSnackBar>}
   */
  error (message: string, action?: any) {
    return this._snackbar('error', message, action);
  }

  _snackbar (type: string, message: string, action?: any) {
    return this.snackbar.open(message, action, {
      duration: 3000
    });
  }
}


text:
/*
 * This file contains macro definitions for the Decoding category of
 * the macros used by the generic scaleloop function.
 *
 * This implementation can decode the pixel information associated
 * with Java DirectColorModel objects where the color masks are
 * guaranteed to be at least 8-bits wide each.  It is slightly more
 * efficient then the generic DCM parsing code since it does not need
 * to store or test component scaling values.  This implementation
 * examines some of the private fields of the DirectColorModel
 * object and decodes the red, green, blue, and possibly alpha values
 * directly rather than calling the getRGB method on the Java object.
 */

/*
 * These definitions vector the standard macro names to the "DCM8"
 * versions of those macros only if the "DecodeDeclared" keyword has
 * not yet been defined elsewhere.  The "DecodeDeclared" keyword is
 * also defined here to claim ownership of the primary implementation
 * even though this file does not rely on the definitions in any other
 * files.
 */
#ifndef DecodeDeclared
#define DeclareDecodeVars       DeclareDCM8Vars
#define InitPixelDecode(CM)     InitPixelDCM8(unhand(CM))
#define PixelDecode             PixelDCM8Decode
#define DecodeDeclared
#endif

#include "java_awt_image_DirectColorModel.h"

#define DeclareDCM8Vars                                         \
    IfAlpha(unsigned int alpha_off;)                            \
    unsigned int red_off, green_off, blue_off;

#define InitPixelDCM8(CM)                                               \
    do {                                                                \
        Classjava_awt_image_DirectColorModel *dcm =                     \
            (Classjava_awt_image_DirectColorModel *) CM;                \
        red_off = dcm->red_offset;                                      \
        green_off = dcm->green_offset;                                  \
        blue_off = dcm->blue_offset;                                    \
        IfAlpha(alpha_off = (dcm->alpha_mask == 0                       \
                             ? -1                                       \
                             : dcm->alpha_offset);)                     \
    } while (0)

#define PixelDCM8Decode(CM, pixel, red, green, blue, alpha)             \
    do {                                                                \
        IfAlpha(alpha = ((alpha_off < 0)                                \
                         ? 255                                          \
                         : (pixel >> alpha_off) & 0xff);)               \
        red = (pixel >> red_off) & 0xff;                                \
        green = (pixel >> green_off) & 0xff;                            \
        blue = (pixel >> blue_off) & 0xff;                              \
    } while (0)


text:
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using Glass.Mapper.Pipelines.ObjectConstruction;
using Glass.Mapper.Sc.Configuration;
using Sitecore.Data;
using Sitecore.Data.Items;

namespace Glass.Mapper.Sc.Pipelines.ObjectConstruction
{
    public class EnforcedTemplateCheck : AbstractObjectConstructionTask
    {
        private static ConcurrentDictionary<string, bool> _cache;

        static EnforcedTemplateCheck()
        {
            _cache = new ConcurrentDictionary<string, bool>();
        }

        public EnforcedTemplateCheck()
        {
            Name = "EnforcedTemplateCheck";
        }

        public override void Execute(ObjectConstructionArgs args)
        {
            if (args.Result == null)
            {
                var options = args.Options as GetItemOptions;

                if (options != null)
                {
                    PerformTemplateCheck(args, options.TemplateId, options.EnforceTemplate);
                }
                else
                {
                    base.Execute(args);
                }
            }
        }

        protected virtual void PerformTemplateCheck(ObjectConstructionArgs args, ID templateId, SitecoreEnforceTemplate enforceTemplate)
        {
            if (!enforceTemplate.IsEnabled())
            {
                base.Execute(args);
            }
            else
            {
                if (ID.IsNullOrEmpty(templateId))
                {
                    throw new MapperException("Cannot EnforceTemplate with Null TemplateID");
                }
                else
                {

                    var scArgs = args.AbstractTypeCreationContext as SitecoreTypeCreationContext;

                    var key = "{0} {1} {2}".Formatted(templateId, scArgs.Item.TemplateID,
                        enforceTemplate);
                    var result = false;

                    if (_cache.ContainsKey(key))
                    {
                        result = _cache[key];
                    }
                    else
                    {
                        var item = scArgs.Item;

                        if (enforceTemplate == SitecoreEnforceTemplate.TemplateAndBase)
                        {
                            result = TemplateAndBaseCheck(item.Template, templateId);
                        }
                        else if (enforceTemplate == SitecoreEnforceTemplate.Template)
                        {
                            result = item.TemplateID == templateId;
                        }

                        _cache.TryAdd(key, result);
                    }

                    if (result)
                    {
                        base.Execute(args);
                    }
                }
            }
        }

        protected virtual bool TemplateAndBaseCheck(TemplateItem template, ID templateId)
        {
            if (template.ID == templateId)
            {
                return true;
            }

            return template.BaseTemplates.Any(baseTemplate => TemplateAndBaseCheck(baseTemplate, templateId));
        }
    }
}