text:
package com.intellij.openapi.util.io;

import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.win32.FileInfo;
import com.intellij.openapi.util.io.win32.IdeaWin32;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.TimeoutUtil;
import org.jetbrains.annotations.NotNull;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.File;
import java.util.Arrays;

import static com.intellij.openapi.util.io.IoTestUtil.assertTimestampsEqual;
import static org.junit.Assert.*;
import static org.junit.Assume.assumeTrue;

public class FileAttributesReadingTest {
  private final byte[] myTestData = new byte[]{'t', 'e', 's', 't'};
  private File myTempDirectory;

  @BeforeClass
  public static void checkMediator() throws Exception {
    final String expectedName = SystemInfo.isWindows ? "IdeaWin32" : "JnaUnix";
    assertEquals(expectedName, FileSystemUtil.getMediatorName());
  }

  @Before
  public void setUp() throws Exception {
    myTempDirectory = FileUtil.createTempDirectory(getClass().getSimpleName() + ".", ".tmp");
  }

  @After
  public void tearDown() throws Exception {
    if (myTempDirectory != null) {
      FileUtil.delete(myTempDirectory);
    }
  }

  @Test
  public void missingFile() throws Exception {
    final File file = FileUtil.createTempFile(myTempDirectory, "test.", ".txt", false);

    final FileAttributes attributes = FileSystemUtil.getAttributes(file);
    assertNull(attributes);

    final String target = FileSystemUtil.resolveSymLink(file);
    assertNull(target);
  }

  @Test
  public void regularFile() throws Exception {
    final File file = FileUtil.createTempFile(myTempDirectory, "test.", ".txt");
    FileUtil.writeToFile(file, myTestData);

    assertFileAttributes(file);

    final String target = FileSystemUtil.resolveSymLink(file);
    assertEquals(file.getPath(), target);
  }

  @Test
  public void directory() throws Exception {
    final File file = FileUtil.createTempDirectory(myTempDirectory, "test.", ".tmp");

    final FileAttributes attributes = getAttributes(file);
    assertEquals(FileAttributes.Type.DIRECTORY, attributes.type);
    assertEquals(0, attributes.flags);
    assertEquals(file.length(), attributes.length);
    assertTimestampsEqual(file.lastModified(), attributes.lastModified);
    assertTrue(attributes.isWritable());
    if (SystemInfo.isWindows) {
      assertDirectoriesEqual(file);
    }

    final String target = FileSystemUtil.resolveSymLink(file);
    assertEquals(file.getPath(), target);
  }

  @Test
  public void root() throws Exception {
    final File file = new File(SystemInfo.isWindows ? "C:\\" : "/");

    final FileAttributes attributes = getAttributes(file);
    assertEquals(FileAttributes.Type.DIRECTORY, attributes.type);
    if (SystemInfo.isWindows) {
      assertDirectoriesEqual(file);
    }
  }

  @Test
  public void badNames() throws Exception {
    final File file = FileUtil.createTempFile(myTempDirectory, "test.", ".txt");
    FileUtil.writeToFile(file, myTestData);

    assertFileAttributes(new File(file.getPath() + StringUtil.repeat(File.separator, 3)));
    assertFileAttributes(new File(file.getPath().replace(File.separator, StringUtil.repeat(File.separator, 3))));
    assertFileAttributes(new File(file.getPath().replace(File.separator, File.separator + "." + File.separator)));
    assertFileAttributes(
      new File(myTempDirectory, File.separator + ".." + File.separator + myTempDirectory.getName() + File.separator + file.getName()));

    if (SystemInfo.isUnix) {
      final File backSlashFile = FileUtil.createTempFile(myTempDirectory, "test\\", "\\txt");
      FileUtil.writeToFile(backSlashFile, myTestData);
      assertFileAttributes(backSlashFile);
    }
  }

  @Test
  public void special() throws Exception {
    assumeTrue(SystemInfo.isUnix);
    final File file = new File("/dev/null");

    final FileAttributes attributes = getAttributes(file);
    assertEquals(FileAttributes.Type.SPECIAL, attributes.type);
    assertEquals(0, attributes.flags);
    assertEquals(0, attributes.length);
    assertTrue(attributes.isWritable());

    final String target = FileSystemUtil.resolveSymLink(file);
    assertEquals(file.getPath(), target);
  }

  @Test
  public void linkToFile() throws Exception {
    assumeTrue(SystemInfo.areSymLinksSupported);

    final File file = FileUtil.createTempFile(myTempDirectory, "test.", ".txt");
    FileUtil.writeToFile(file, myTestData);
    assertTrue(file.setLastModified(file.lastModified() - 5000));
    assertTrue(file.setWritable(false, false));
    final File link = IoTestUtil.createSymLink(file.getPath(), new File(myTempDirectory, "link").getPath());

    final FileAttributes attributes = getAttributes(link);
    assertEquals(FileAttributes.Type.FILE, attributes.type);
    assertEquals(FileAttributes.SYM_LINK, attributes.flags);
    assertEquals(myTestData.length, attributes.length);
    assertTimestampsEqual(file.lastModified(), attributes.lastModified);
    assertFalse(attributes.isWritable());

    final String target = FileSystemUtil.resolveSymLink(link);
    assertEquals(file.getPath(), target);
  }

  @Test
  public void doubleLink() throws Exception {
    assumeTrue(SystemInfo.areSymLinksSupported);

    final File file = FileUtil.createTempFile(myTempDirectory, "test.", ".txt");
    FileUtil.writeToFile(file, myTestData);
    assertTrue(file.setLastModified(file.lastModified() - 5000));
    assertTrue(file.setWritable(false, false));
    final File link1 = IoTestUtil.createSymLink(file.getPath(), new File(myTempDirectory, "link1").getPath());
    final File link2 = IoTestUtil.createSymLink(link1.getPath(), new File(myTempDirectory, "link2").getPath());

    final FileAttributes attributes = getAttributes(link2);
    assertEquals(FileAttributes.Type.FILE, attributes.type);
    assertEquals(FileAttributes.SYM_LINK, attributes.flags);
    assertEquals(myTestData.length, attributes.length);
    assertTimestampsEqual(file.lastModified(), attributes.lastModified);
    assertFalse(attributes.isWritable());

    final String target = FileSystemUtil.resolveSymLink(link2);
    assertEquals(file.getPath(), target);
  }

  @Test
  public void linkToDirectory() throws Exception {
    assumeTrue(SystemInfo.areSymLinksSupported);

    final File file = FileUtil.createTempDirectory(myTempDirectory, "test.", ".tmp");
    if (SystemInfo.isUnix) assertTrue(file.setWritable(false, false));
    assertTrue(file.setLastModified(file.lastModified() - 5000));
    final File link = IoTestUtil.createSymLink(file.getPath(), new File(myTempDirectory, "link").getPath());

    final FileAttributes attributes = getAttributes(link);
    assertEquals(FileAttributes.Type.DIRECTORY, attributes.type);
    assertEquals(FileAttributes.SYM_LINK, attributes.flags);
    assertEquals(file.length(), attributes.length);
    assertTimestampsEqual(file.lastModified(), attributes.lastModified);
    if (SystemInfo.isUnix) assertFalse(attributes.isWritable());

    final String target = FileSystemUtil.resolveSymLink(link);
    assertEquals(file.getPath(), target);
  }

  @Test
  public void missingLink() throws Exception {
    assumeTrue(SystemInfo.areSymLinksSupported);

    final File file = FileUtil.createTempFile(myTempDirectory, "test.", ".txt", false);
    final File link = IoTestUtil.createSymLink(file.getPath(), new File(myTempDirectory, "link").getPath(), false);

    final FileAttributes attributes = getAttributes(link);
    assertNull(attributes.type);
    assertEquals(FileAttributes.SYM_LINK, attributes.flags);
    assertEquals(0, attributes.length);

    final String target = FileSystemUtil.resolveSymLink(link);
    assertNull(target, target);
  }

  @Test
  public void selfLink() throws Exception {
    assumeTrue(SystemInfo.areSymLinksSupported);

    final File dir = FileUtil.createTempDirectory(myTempDirectory, "test.", ".dir");
    final File link = IoTestUtil.createSymLink(dir.getPath(), new File(dir, "link").getPath());

    final FileAttributes attributes = getAttributes(link);
    assertEquals(FileAttributes.Type.DIRECTORY, attributes.type);
    assertEquals(FileAttributes.SYM_LINK, attributes.flags);
    assertTimestampsEqual(dir.lastModified(), attributes.lastModified);

    final String target = FileSystemUtil.resolveSymLink(link);
    assertEquals(dir.getPath(), target);
  }

  @Test
  public void junction() throws Exception {
    assumeTrue(SystemInfo.isWindows);

    final File target = FileUtil.createTempDirectory(myTempDirectory, "temp.", ".dir");
    final File path = FileUtil.createTempFile(myTempDirectory, "junction.", ".dir", false);
    final File junction = IoTestUtil.createJunction(target.getPath(), path.getAbsolutePath());

    FileAttributes attributes = getAttributes(junction);
    assertEquals(FileAttributes.Type.DIRECTORY, attributes.type);
    assertEquals(0, attributes.flags);
    assertTrue(attributes.isWritable());

    final String resolved1 = FileSystemUtil.resolveSymLink(junction);
    assertEquals(SystemInfo.isWinVistaOrNewer ? target.getPath() : junction.getPath(), resolved1);

    FileUtil.delete(target);

    attributes = getAttributes(junction);
    assertEquals(FileAttributes.Type.DIRECTORY, attributes.type);
    assertEquals(0, attributes.flags);
    assertTrue(attributes.isWritable());

    final String resolved2 = FileSystemUtil.resolveSymLink(junction);
    assertEquals(SystemInfo.isWinVistaOrNewer ? null : junction.getPath(), resolved2);
  }

  @Test
  public void hiddenDir() throws Exception {
    assumeTrue(SystemInfo.isWindows);
    File dir = IoTestUtil.createTestDir(myTempDirectory, "dir");
    FileAttributes attributes = getAttributes(dir);
    assertFalse(attributes.isHidden());
    IoTestUtil.setHidden(dir.getPath(), true);
    attributes = getAttributes(dir);
    assertTrue(attributes.isHidden());
  }

  @Test
  public void hiddenFile() throws Exception {
    assumeTrue(SystemInfo.isWindows);
    File file = IoTestUtil.createTestFile(myTempDirectory, "file");
    FileAttributes attributes = getAttributes(file);
    assertFalse(attributes.isHidden());
    IoTestUtil.setHidden(file.getPath(), true);
    attributes = getAttributes(file);
    assertTrue(attributes.isHidden());
  }

  @Test
  public void notSoHiddenRoot() throws Exception {
    if (SystemInfo.isWindows) {
      File absRoot = new File("C:\\");
      FileAttributes absAttributes = getAttributes(absRoot);
      assertFalse(absAttributes.isHidden());

      File relRoot = new File("C:");
      FileAttributes relAttributes = getAttributes(relRoot);
      assertFalse(relAttributes.isHidden());
    }
    else {
      File absRoot = new File("/");
      FileAttributes absAttributes = getAttributes(absRoot);
      assertFalse(absAttributes.isHidden());
    }
  }

  @Test
  public void wellHiddenFile() throws Exception {
    assumeTrue(SystemInfo.isWindows);
    final File file = new File("C:\\Documents and Settings\\desktop.ini");
    assumeTrue(file.exists());

    final FileAttributes attributes = getAttributes(file, false);
    assertEquals(FileAttributes.Type.FILE, attributes.type);
    assertEquals(FileAttributes.HIDDEN, attributes.flags);
    assertEquals(file.length(), attributes.length);
    assertTimestampsEqual(file.lastModified(), attributes.lastModified);
  }

  @Test
  public void extraLongName() throws Exception {
    final String prefix = StringUtil.repeatSymbol('a', 128) + ".";
    final File dir = FileUtil.createTempDirectory(
      FileUtil.createTempDirectory(
        FileUtil.createTempDirectory(
          FileUtil.createTempDirectory(
            myTempDirectory, prefix, ".dir"),
          prefix, ".dir"),
        prefix, ".dir"),
      prefix, ".dir");
    final File file = FileUtil.createTempFile(dir, prefix, ".txt");
    assertTrue(file.exists());
    FileUtil.writeToFile(file, myTestData);

    assertFileAttributes(file);
    if (SystemInfo.isWindows) {
      assertDirectoriesEqual(dir);
    }

    final String target = FileSystemUtil.resolveSymLink(file);
    assertEquals(file.getPath(), target);
  }

  @Test
  public void subst() throws Exception {
    assumeTrue(SystemInfo.isWindows);

    FileUtil.createTempFile(myTempDirectory, "test.", ".txt");  // just to populate a directory
    final File substRoot = IoTestUtil.createSubst(myTempDirectory.getPath());
    try {
      final FileAttributes attributes = getAttributes(substRoot);
      assertEquals(FileAttributes.Type.DIRECTORY, attributes.type);
      assertDirectoriesEqual(substRoot);

      final File[] children = substRoot.listFiles();
      assertNotNull(children);
      assertEquals(1, children.length);
      final File file = children[0];
      final String target = FileSystemUtil.resolveSymLink(file);
      assertEquals(file.getPath(), target);
    }
    finally {
      IoTestUtil.deleteSubst(substRoot.getPath());
    }
  }

  @Test
  public void hardLink() throws Exception {
    final File target = FileUtil.createTempFile(myTempDirectory, "test.", ".txt");
    final File link = IoTestUtil.createHardLink(target.getPath(), myTempDirectory.getPath() + "/link");

    FileAttributes attributes = getAttributes(link, SystemInfo.areSymLinksSupported);  // ignore XP
    assertEquals(FileAttributes.Type.FILE, attributes.type);
    assertEquals(target.length(), attributes.length);
    assertTimestampsEqual(target.lastModified(), attributes.lastModified);

    FileUtil.writeToFile(target, myTestData);
    assertTrue(target.setLastModified(attributes.lastModified - 5000));
    assertTrue(target.length() > 0);
    assertTimestampsEqual(attributes.lastModified - 5000, target.lastModified());

    attributes = getAttributes(link, SystemInfo.areSymLinksSupported);  // ignore XP
    assertEquals(FileAttributes.Type.FILE, attributes.type);
    assertEquals(target.length(), attributes.length);
    assertTimestampsEqual(target.lastModified(), attributes.lastModified);

    final String resolved = FileSystemUtil.resolveSymLink(link);
    assertEquals(link.getPath(), resolved);
  }

  @Test
  public void stamps() throws Exception {
    FileAttributes attributes = FileSystemUtil.getAttributes(myTempDirectory);
    assumeTrue(attributes != null && attributes.lastModified > (attributes.lastModified/1000)*1000);

    long t1 = System.currentTimeMillis();
    TimeoutUtil.sleep(10);
    File file = IoTestUtil.createTestFile(myTempDirectory, "test.txt");
    TimeoutUtil.sleep(10);
    long t2 = System.currentTimeMillis();
    attributes = getAttributes(file);
    assertTrue(attributes.lastModified + " not in " + t1 + ".." + t2, t1 <= attributes.lastModified && attributes.lastModified <= t2);

    t1 = System.currentTimeMillis();
    TimeoutUtil.sleep(10);
    FileUtil.writeToFile(file, myTestData);
    TimeoutUtil.sleep(10);
    t2 = System.currentTimeMillis();
    attributes = getAttributes(file);
    assertTrue(attributes.lastModified + " not in " + t1 + ".." + t2, t1 <= attributes.lastModified && attributes.lastModified <= t2);

    ProcessBuilder cmd = SystemInfo.isWindows ? new ProcessBuilder("attrib", "-A", file.getPath()) : new ProcessBuilder("chmod", "644", file.getPath());
    assertEquals(0, cmd.start().waitFor());
    attributes = getAttributes(file);
    assertTrue(attributes.lastModified + " not in " + t1 + ".." + t2, t1 <= attributes.lastModified && attributes.lastModified <= t2);
  }

  @NotNull
  private static FileAttributes getAttributes(@NotNull final File file) {
    return getAttributes(file, true);
  }

  @NotNull
  private static FileAttributes getAttributes(@NotNull final File file, final boolean checkList) {
    final FileAttributes attributes = FileSystemUtil.getAttributes(file);
    assertNotNull(attributes);
    System.out.println(attributes + ": " + file);

    if (SystemInfo.isWindows && checkList) {
      final String parent = file.getParent();
      if (parent != null) {
        final FileInfo[] infos = IdeaWin32.getInstance().listChildren(parent);
        assertNotNull(infos);
        for (FileInfo info : infos) {
          if (file.getName().equals(info.getName())) {
            assertEquals(attributes, info.toFileAttributes());
            return attributes;
          }
        }
        fail(file + " not listed");
      }
    }

    return attributes;
  }

  private static void assertFileAttributes(@NotNull final File file) {
    final FileAttributes attributes = getAttributes(file);
    assertEquals(FileAttributes.Type.FILE, attributes.type);
    assertEquals(0, attributes.flags);
    assertEquals(file.length(), attributes.length);
    assertTimestampsEqual(file.lastModified(), attributes.lastModified);
    assertTrue(attributes.isWritable());
  }

  private static void assertDirectoriesEqual(@NotNull final File dir) {
    final String[] list1 = dir.list();
    assertNotNull(list1);
    final FileInfo[] list2 = IdeaWin32.getInstance().listChildren(dir.getPath());
    assertNotNull(list2);
    if (list1.length + 2 != list2.length) {
      assertEquals(Arrays.toString(list1), Arrays.toString(list2));
    }
  }
}


text:
package org.fanout.gripcontrol;

import org.junit.Test;

import javax.xml.bind.DatatypeConverter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import static org.junit.Assert.assertEquals;

public class HttpResponseFormatTest {
    @Test
    public void testHttpResponseFormat() throws UnsupportedEncodingException {
        HttpResponseFormat format = new HttpResponseFormat("body");
        assertEquals(format.name(), "http-response");
        Map<String, Object> export = (Map<String, Object>)format.export();
        assertEquals(export.get("body"), "body");
        format = new HttpResponseFormat("body".getBytes("utf-8"));
        export = (Map<String, Object>)format.export();
        assertEquals(export.get("body"), "body");
        byte[] byteData = {(byte) Integer.parseInt("10001111", 2), (byte) Integer.parseInt("10111111", 2)};
        format = new HttpResponseFormat(byteData);
        export = (Map<String, Object>)format.export();
        assertEquals(export.get("body-bin"), DatatypeConverter.printBase64Binary(byteData));
        Map<String, String> headers = new HashMap<String, String>();
        format = new HttpResponseFormat("body", headers, "code", "reason");
        assertEquals(format.name(), "http-response");
        export = (Map<String, Object>)format.export();
        assertEquals(export.get("code"), "code");
        assertEquals(export.get("headers"), headers);
        assertEquals(export.get("reason"), "reason");
        assertEquals(export.get("body"), "body");
        format = new HttpResponseFormat("body".getBytes("utf-8"), headers, "code", "reason");
        export = (Map<String, Object>)format.export();
        assertEquals(export.get("code"), "code");
        assertEquals(export.get("headers"), headers);
        assertEquals(export.get("reason"), "reason");
        assertEquals(export.get("body"), "body");
        format = new HttpResponseFormat(byteData, headers, "code", "reason");
        export = (Map<String, Object>)format.export();
        assertEquals(export.get("code"), "code");
        assertEquals(export.get("headers"), headers);
        assertEquals(export.get("reason"), "reason");
        assertEquals(export.get("body-bin"), DatatypeConverter.printBase64Binary(byteData));
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.guvnor.ala.ui.client.wizard.pipeline.item;

import java.util.ArrayList;
import java.util.Collection;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import javax.enterprise.context.Dependent;
import javax.inject.Inject;

import org.guvnor.ala.ui.client.util.AbstractHasContentChangeHandlers;
import org.guvnor.ala.ui.model.PipelineKey;
import org.jboss.errai.common.client.api.IsElement;
import org.uberfire.client.mvp.UberElement;

@Dependent
public class PipelineItemPresenter
        extends AbstractHasContentChangeHandlers {

    public interface View
            extends UberElement<PipelineItemPresenter> {

        boolean isSelected();

        void unSelect();

        void setPipelineName(String name);
    }

    private final View view;

    private final Collection<PipelineItemPresenter> others = new ArrayList<>();
    private PipelineKey pipeline;

    @Inject
    public PipelineItemPresenter(final View view) {
        this.view = view;
    }

    @PostConstruct
    public void init() {
        view.init(this);
    }

    public void setup(final PipelineKey pipeline) {
        this.pipeline = pipeline;
        view.setPipelineName(pipeline.getId());
    }

    public PipelineKey getPipeline() {
        return pipeline;
    }

    public void addOthers(final Collection<PipelineItemPresenter> items) {
        others.addAll(items.stream()
                              .filter(other -> !other.equals(this))
                              .collect(Collectors.toList())
        );
    }

    public boolean isSelected() {
        return view.isSelected();
    }

    public IsElement getView() {
        return view;
    }

    public void onContentChange() {
        if (view.isSelected()) {
            unSelectOthers();
        }
        fireChangeHandlers();
    }

    private void unSelectOthers() {
        others.forEach(PipelineItemPresenter::unSelect);
    }

    private void unSelect() {
        view.unSelect();
    }
}


text:
<?php

namespace Zend\Cache\Storage\Adapter;

use Memcached as MemcachedResource;
use stdClass;
use Traversable;
use Zend\Cache\Exception;
use Zend\Cache\Storage\AvailableSpaceCapableInterface;
use Zend\Cache\Storage\Capabilities;
use Zend\Cache\Storage\FlushableInterface;
use Zend\Cache\Storage\TotalSpaceCapableInterface;

class Memcached extends AbstractAdapter implements
    AvailableSpaceCapableInterface,
    FlushableInterface,
    TotalSpaceCapableInterface
{
    /**
     * Major version of ext/memcached
     *
     * @var null|int
     */
    protected static $extMemcachedMajorVersion;

    /**
     * Has this instance be initialized
     *
     * @var bool
     */
    protected $initialized = false;

    /**
     * The memcached resource manager
     *
     * @var null|MemcachedResourceManager
     */
    protected $resourceManager;

    /**
     * The memcached resource id
     *
     * @var null|string
     */
    protected $resourceId;

    /**
     * The namespace prefix
     *
     * @var string
     */
    protected $namespacePrefix = '';

    /**
     * Constructor
     *
     * @param  null|array|Traversable|MemcachedOptions $options
     * @throws Exception\ExceptionInterface
     */
    public function __construct($options = null)
    {
        if (static::$extMemcachedMajorVersion === null) {
            $v = (string) phpversion('memcached');
            static::$extMemcachedMajorVersion = ($v !== '') ? (int) $v[0] : 0;
        }

        if (static::$extMemcachedMajorVersion < 1) {
            throw new Exception\ExtensionNotLoadedException('Need ext/memcached version >= 1.0.0');
        }

        parent::__construct($options);

        // reset initialized flag on update option(s)
        $initialized = & $this->initialized;
        $this->getEventManager()->attach('option', function ($event) use (& $initialized) {
            $initialized = false;
        });
    }

    /**
     * Initialize the internal memcached resource
     *
     * @return MemcachedResource
     */
    protected function getMemcachedResource()
    {
        if (!$this->initialized) {
            $options = $this->getOptions();

            // get resource manager and resource id
            $this->resourceManager = $options->getResourceManager();
            $this->resourceId      = $options->getResourceId();

            // init namespace prefix
            $namespace = $options->getNamespace();
            if ($namespace !== '') {
                $this->namespacePrefix = $namespace . $options->getNamespaceSeparator();
            } else {
                $this->namespacePrefix = '';
            }

            // update initialized flag
            $this->initialized = true;
        }

        return $this->resourceManager->getResource($this->resourceId);
    }

    /* options */

    /**
     * Set options.
     *
     * @param  array|Traversable|MemcachedOptions $options
     * @return Memcached
     * @see    getOptions()
     */
    public function setOptions($options)
    {
        if (!$options instanceof MemcachedOptions) {
            $options = new MemcachedOptions($options);
        }

        return parent::setOptions($options);
    }

    /**
     * Get options.
     *
     * @return MemcachedOptions
     * @see setOptions()
     */
    public function getOptions()
    {
        if (!$this->options) {
            $this->setOptions(new MemcachedOptions());
        }
        return $this->options;
    }

    /* FlushableInterface */

    /**
     * Flush the whole storage
     *
     * @return bool
     */
    public function flush()
    {
        $memc = $this->getMemcachedResource();
        if (!$memc->flush()) {
            throw $this->getExceptionByResultCode($memc->getResultCode());
        }
        return true;
    }

    /* TotalSpaceCapableInterface */

    /**
     * Get total space in bytes
     *
     * @return int|float
     */
    public function getTotalSpace()
    {
        $memc  = $this->getMemcachedResource();
        $stats = $memc->getStats();
        if ($stats === false) {
            throw new Exception\RuntimeException($memc->getResultMessage());
        }

        $mem = array_pop($stats);
        return $mem['limit_maxbytes'];
    }

    /* AvailableSpaceCapableInterface */

    /**
     * Get available space in bytes
     *
     * @return int|float
     */
    public function getAvailableSpace()
    {
        $memc  = $this->getMemcachedResource();
        $stats = $memc->getStats();
        if ($stats === false) {
            throw new Exception\RuntimeException($memc->getResultMessage());
        }

        $mem = array_pop($stats);
        return $mem['limit_maxbytes'] - $mem['bytes'];
    }

    /* reading */

    /**
     * Internal method to get an item.
     *
     * @param  string  $normalizedKey
     * @param  bool $success
     * @param  mixed   $casToken
     * @return mixed Data on success, null on failure
     * @throws Exception\ExceptionInterface
     */
    protected function internalGetItem(& $normalizedKey, & $success = null, & $casToken = null)
    {
        $memc        = $this->getMemcachedResource();
        $internalKey = $this->namespacePrefix . $normalizedKey;

        if (func_num_args() > 2) {
            $result = $memc->get($internalKey, null, $casToken);
        } else {
            $result = $memc->get($internalKey);
        }

        $success = true;
        if ($result === false) {
            $rsCode = $memc->getResultCode();
            if ($rsCode == MemcachedResource::RES_NOTFOUND) {
                $result = null;
                $success = false;
            } elseif ($rsCode) {
                $success = false;
                throw $this->getExceptionByResultCode($rsCode);
            }
        }

        return $result;
    }

    /**
     * Internal method to get multiple items.
     *
     * @param  array $normalizedKeys
     * @return array Associative array of keys and values
     * @throws Exception\ExceptionInterface
     */
    protected function internalGetItems(array & $normalizedKeys)
    {
        $memc = $this->getMemcachedResource();

        foreach ($normalizedKeys as & $normalizedKey) {
            $normalizedKey = $this->namespacePrefix . $normalizedKey;
        }

        $result = $memc->getMulti($normalizedKeys);
        if ($result === false) {
            throw $this->getExceptionByResultCode($memc->getResultCode());
        }

        // remove namespace prefix from result
        if ($result && $this->namespacePrefix !== '') {
            $tmp            = array();
            $nsPrefixLength = strlen($this->namespacePrefix);
            foreach ($result as $internalKey => & $value) {
                $tmp[substr($internalKey, $nsPrefixLength)] = & $value;
            }
            $result = $tmp;
        }

        return $result;
    }

    /**
     * Internal method to test if an item exists.
     *
     * @param  string $normalizedKey
     * @return bool
     * @throws Exception\ExceptionInterface
     */
    protected function internalHasItem(& $normalizedKey)
    {
        $memc  = $this->getMemcachedResource();
        $value = $memc->get($this->namespacePrefix . $normalizedKey);
        if ($value === false) {
            $rsCode = $memc->getResultCode();
            if ($rsCode == MemcachedResource::RES_SUCCESS) {
                return true;
            } elseif ($rsCode == MemcachedResource::RES_NOTFOUND) {
                return false;
            } else {
                throw $this->getExceptionByResultCode($rsCode);
            }
        }

        return true;
    }

    /**
     * Internal method to test multiple items.
     *
     * @param  array $normalizedKeys
     * @return array Array of found keys
     * @throws Exception\ExceptionInterface
     */
    protected function internalHasItems(array & $normalizedKeys)
    {
        $memc = $this->getMemcachedResource();

        foreach ($normalizedKeys as & $normalizedKey) {
            $normalizedKey = $this->namespacePrefix . $normalizedKey;
        }

        $result = $memc->getMulti($normalizedKeys);
        if ($result === false) {
            throw $this->getExceptionByResultCode($memc->getResultCode());
        }

        // Convert to a simgle list
        $result = array_keys($result);

        // remove namespace prefix
        if ($result && $this->namespacePrefix !== '') {
            $nsPrefixLength = strlen($this->namespacePrefix);
            foreach ($result as & $internalKey) {
                $internalKey = substr($internalKey, $nsPrefixLength);
            }
        }

        return $result;
    }

    /**
     * Get metadata of multiple items
     *
     * @param  array $normalizedKeys
     * @return array Associative array of keys and metadata
     * @throws Exception\ExceptionInterface
     */
    protected function internalGetMetadatas(array & $normalizedKeys)
    {
        $memc = $this->getMemcachedResource();

        foreach ($normalizedKeys as & $normalizedKey) {
            $normalizedKey = $this->namespacePrefix . $normalizedKey;
        }

        $result = $memc->getMulti($normalizedKeys);
        if ($result === false) {
            throw $this->getExceptionByResultCode($memc->getResultCode());
        }

        // remove namespace prefix and use an empty array as metadata
        if ($this->namespacePrefix !== '') {
            $tmp            = array();
            $nsPrefixLength = strlen($this->namespacePrefix);
            foreach (array_keys($result) as $internalKey) {
                $tmp[substr($internalKey, $nsPrefixLength)] = array();
            }
            $result = $tmp;
        } else {
            foreach ($result as & $value) {
                $value = array();
            }
        }

        return $result;
    }

    /* writing */

    /**
     * Internal method to store an item.
     *
     * @param  string $normalizedKey
     * @param  mixed  $value
     * @return bool
     * @throws Exception\ExceptionInterface
     */
    protected function internalSetItem(& $normalizedKey, & $value)
    {
        $memc       = $this->getMemcachedResource();
        $expiration = $this->expirationTime();
        if (!$memc->set($this->namespacePrefix . $normalizedKey, $value, $expiration)) {
            throw $this->getExceptionByResultCode($memc->getResultCode());
        }

        return true;
    }

    /**
     * Internal method to store multiple items.
     *
     * @param  array $normalizedKeyValuePairs
     * @return array Array of not stored keys
     * @throws Exception\ExceptionInterface
     */
    protected function internalSetItems(array & $normalizedKeyValuePairs)
    {
        $memc       = $this->getMemcachedResource();
        $expiration = $this->expirationTime();

        $namespacedKeyValuePairs = array();
        foreach ($normalizedKeyValuePairs as $normalizedKey => & $value) {
            $namespacedKeyValuePairs[$this->namespacePrefix . $normalizedKey] = & $value;
        }

        if (!$memc->setMulti($namespacedKeyValuePairs, $expiration)) {
            throw $this->getExceptionByResultCode($memc->getResultCode());
        }

        return array();
    }

    /**
     * Add an item.
     *
     * @param  string $normalizedKey
     * @param  mixed  $value
     * @return bool
     * @throws Exception\ExceptionInterface
     */
    protected function internalAddItem(& $normalizedKey, & $value)
    {
        $memc       = $this->getMemcachedResource();
        $expiration = $this->expirationTime();
        if (!$memc->add($this->namespacePrefix . $normalizedKey, $value, $expiration)) {
            if ($memc->getResultCode() == MemcachedResource::RES_NOTSTORED) {
                return false;
            }
            throw $this->getExceptionByResultCode($memc->getResultCode());
        }

        return true;
    }

    /**
     * Internal method to replace an existing item.
     *
     * @param  string $normalizedKey
     * @param  mixed  $value
     * @return bool
     * @throws Exception\ExceptionInterface
     */
    protected function internalReplaceItem(& $normalizedKey, & $value)
    {
        $memc       = $this->getMemcachedResource();
        $expiration = $this->expirationTime();
        if (!$memc->replace($this->namespacePrefix . $normalizedKey, $value, $expiration)) {
            $rsCode = $memc->getResultCode();
            if ($rsCode == MemcachedResource::RES_NOTSTORED) {
                return false;
            }
            throw $this->getExceptionByResultCode($rsCode);
        }

        return true;
    }

    /**
     * Internal method to set an item only if token matches
     *
     * @param  mixed  $token
     * @param  string $normalizedKey
     * @param  mixed  $value
     * @return bool
     * @throws Exception\ExceptionInterface
     * @see    getItem()
     * @see    setItem()
     */
    protected function internalCheckAndSetItem(& $token, & $normalizedKey, & $value)
    {
        $memc       = $this->getMemcachedResource();
        $expiration = $this->expirationTime();
        $result     = $memc->cas($token, $this->namespacePrefix . $normalizedKey, $value, $expiration);

        if ($result === false) {
            $rsCode = $memc->getResultCode();
            if ($rsCode !== 0 && $rsCode != MemcachedResource::RES_DATA_EXISTS) {
                throw $this->getExceptionByResultCode($rsCode);
            }
        }

        return $result;
    }

    /**
     * Internal method to remove an item.
     *
     * @param  string $normalizedKey
     * @return bool
     * @throws Exception\ExceptionInterface
     */
    protected function internalRemoveItem(& $normalizedKey)
    {
        $memc   = $this->getMemcachedResource();
        $result = $memc->delete($this->namespacePrefix . $normalizedKey);

        if ($result === false) {
            $rsCode = $memc->getResultCode();
            if ($rsCode == MemcachedResource::RES_NOTFOUND) {
                return false;
            } elseif ($rsCode != MemcachedResource::RES_SUCCESS) {
                throw $this->getExceptionByResultCode($rsCode);
            }
        }

        return true;
    }

    /**
     * Internal method to remove multiple items.
     *
     * @param  array $normalizedKeys
     * @return array Array of not removed keys
     * @throws Exception\ExceptionInterface
     */
    protected function internalRemoveItems(array & $normalizedKeys)
    {
        // support for removing multiple items at once has been added in ext/memcached-2.0.0
        if (static::$extMemcachedMajorVersion < 2) {
            return parent::internalRemoveItems($normalizedKeys);
        }

        $memc = $this->getMemcachedResource();

        foreach ($normalizedKeys as & $normalizedKey) {
            $normalizedKey = $this->namespacePrefix . $normalizedKey;
        }

        $rsCodes = $memc->deleteMulti($normalizedKeys);

        $missingKeys = array();
        foreach ($rsCodes as $key => $rsCode) {
            if ($rsCode !== true && $rsCode != MemcachedResource::RES_SUCCESS) {
                if ($rsCode != MemcachedResource::RES_NOTFOUND) {
                    throw $this->getExceptionByResultCode($rsCode);
                }
                $missingKeys[] = $key;
            }
        }

        // remove namespace prefix
        if ($missingKeys && $this->namespacePrefix !== '') {
            $nsPrefixLength = strlen($this->namespacePrefix);
            foreach ($missingKeys as & $missingKey) {
                $missingKey = substr($missingKey, $nsPrefixLength);
            }
        }

        return $missingKeys;
    }

    /**
     * Internal method to increment an item.
     *
     * @param  string $normalizedKey
     * @param  int    $value
     * @return int|bool The new value on success, false on failure
     * @throws Exception\ExceptionInterface
     */
    protected function internalIncrementItem(& $normalizedKey, & $value)
    {
        $memc        = $this->getMemcachedResource();
        $internalKey = $this->namespacePrefix . $normalizedKey;
        $value       = (int) $value;
        $newValue    = $memc->increment($internalKey, $value);

        if ($newValue === false) {
            $rsCode = $memc->getResultCode();

            // initial value
            if ($rsCode == MemcachedResource::RES_NOTFOUND) {
                $newValue = $value;
                $memc->add($internalKey, $newValue, $this->expirationTime());
                $rsCode = $memc->getResultCode();
            }

            if ($rsCode) {
                throw $this->getExceptionByResultCode($rsCode);
            }
        }

        return $newValue;
    }

    /**
     * Internal method to decrement an item.
     *
     * @param  string $normalizedKey
     * @param  int    $value
     * @return int|bool The new value on success, false on failure
     * @throws Exception\ExceptionInterface
     */
    protected function internalDecrementItem(& $normalizedKey, & $value)
    {
        $memc        = $this->getMemcachedResource();
        $internalKey = $this->namespacePrefix . $normalizedKey;
        $value       = (int) $value;
        $newValue    = $memc->decrement($internalKey, $value);

        if ($newValue === false) {
            $rsCode = $memc->getResultCode();

            // initial value
            if ($rsCode == MemcachedResource::RES_NOTFOUND) {
                $newValue = -$value;
                $memc->add($internalKey, $newValue, $this->expirationTime());
                $rsCode = $memc->getResultCode();
            }

            if ($rsCode) {
                throw $this->getExceptionByResultCode($rsCode);
            }
        }

        return $newValue;
    }

    /* status */

    /**
     * Internal method to get capabilities of this adapter
     *
     * @return Capabilities
     */
    protected function internalGetCapabilities()
    {
        if ($this->capabilities === null) {
            $this->capabilityMarker = new stdClass();
            $this->capabilities     = new Capabilities(
                $this,
                $this->capabilityMarker,
                array(
                    'supportedDatatypes' => array(
                        'NULL'     => true,
                        'boolean'  => true,
                        'integer'  => true,
                        'double'   => true,
                        'string'   => true,
                        'array'    => true,
                        'object'   => 'object',
                        'resource' => false,
                    ),
                    'supportedMetadata'  => array(),
                    'minTtl'             => 1,
                    'maxTtl'             => 0,
                    'staticTtl'          => true,
                    'ttlPrecision'       => 1,
                    'useRequestTime'     => false,
                    'expiredRead'        => false,
                    'maxKeyLength'       => 255,
                    'namespaceIsPrefix'  => true,
                )
            );
        }

        return $this->capabilities;
    }

    /* internal */

    /**
     * Get expiration time by ttl
     *
     * Some storage commands involve sending an expiration value (relative to
     * an item or to an operation requested by the client) to the server. In
     * all such cases, the actual value sent may either be Unix time (number of
     * seconds since January 1, 1970, as an integer), or a number of seconds
     * starting from current time. In the latter case, this number of seconds
     * may not exceed 60*60*24*30 (number of seconds in 30 days); if the
     * expiration value is larger than that, the server will consider it to be
     * real Unix time value rather than an offset from current time.
     *
     * @return int
     */
    protected function expirationTime()
    {
        $ttl = $this->getOptions()->getTtl();
        if ($ttl > 2592000) {
            return time() + $ttl;
        }
        return $ttl;
    }

    /**
     * Generate exception based of memcached result code
     *
     * @param int $code
     * @return Exception\RuntimeException
     * @throws Exception\InvalidArgumentException On success code
     */
    protected function getExceptionByResultCode($code)
    {
        switch ($code) {
            case MemcachedResource::RES_SUCCESS:
                throw new Exception\InvalidArgumentException(
                    "The result code '{$code}' (SUCCESS) isn't an error"
                );

            default:
                return new Exception\RuntimeException($this->getMemcachedResource()->getResultMessage());
        }
    }
}


text:
var vows = require('vows');
var assert = require('assert');
var softwareversion = require('index');

vows.describe('junction-softwareversion').addBatch({

  'module': {
    'should export middleware': function () {
      assert.isFunction(softwareversion);
      assert.isFunction(softwareversion.softwareVersion);
      assert.isFunction(softwareversion.softwareVersionResultParser);
    },
  },

}).export(module);


text:
<?php declare(strict_types=1);

namespace DrdPlus\Tests\Skills\Combined;

use DrdPlus\Skills\Combined\FirstAid;

class FirstAidTest extends CombinedSkillTest
{
    /**
     * @test
     */
    public function I_can_get_minimal_wounds_left_after_first_aid_heal()
    {
        $firstAid = new FirstAid($this->createProfessionFirstLevel());
        self::assertSame(5, $firstAid->getMinimalWoundsLeftAfterFirstAidHeal());
        $firstAid->increaseSkillRank($this->createSkillPoint());
        self::assertSame(3, $firstAid->getMinimalWoundsLeftAfterFirstAidHeal());
        $firstAid->increaseSkillRank($this->createSkillPoint());
        self::assertSame(2, $firstAid->getMinimalWoundsLeftAfterFirstAidHeal());
        $firstAid->increaseSkillRank($this->createSkillPoint());
        self::assertSame(1, $firstAid->getMinimalWoundsLeftAfterFirstAidHeal());
    }

    /**
     * @test
     */
    public function I_can_get_healing_power_to_basic_wounds()
    {
        $firstAid = new FirstAid($this->createProfessionFirstLevel());
        self::assertSame(-20, $firstAid->getHealingPowerToBasicWounds());
        $firstAid->increaseSkillRank($this->createSkillPoint());
        self::assertSame(-6, $firstAid->getHealingPowerToBasicWounds());
        $firstAid->increaseSkillRank($this->createSkillPoint());
        self::assertSame(-4, $firstAid->getHealingPowerToBasicWounds());
        $firstAid->increaseSkillRank($this->createSkillPoint());
        self::assertSame(-2, $firstAid->getHealingPowerToBasicWounds());
    }

    /**
     * @test
     */
    public function I_can_get_bleeding_lowering_value()
    {
        $firstAid = new FirstAid($this->createProfessionFirstLevel());
        self::assertSame(0, $firstAid->getBleedingLoweringValue());
        $firstAid->increaseSkillRank($this->createSkillPoint());
        self::assertSame(0, $firstAid->getBleedingLoweringValue());
        $firstAid->increaseSkillRank($this->createSkillPoint());
        self::assertSame(-1, $firstAid->getBleedingLoweringValue());
        $firstAid->increaseSkillRank($this->createSkillPoint());
        self::assertSame(-2, $firstAid->getBleedingLoweringValue());
    }

    /**
     * @test
     */
    public function I_can_get_poison_lowering_value()
    {
        $firstAid = new FirstAid($this->createProfessionFirstLevel());
        self::assertSame(0, $firstAid->getPoisonLoweringValue());
        $firstAid->increaseSkillRank($this->createSkillPoint());
        self::assertSame(0, $firstAid->getPoisonLoweringValue());
        $firstAid->increaseSkillRank($this->createSkillPoint());
        self::assertSame(0, $firstAid->getPoisonLoweringValue());
        $firstAid->increaseSkillRank($this->createSkillPoint());
        self::assertSame(-2, $firstAid->getPoisonLoweringValue());
    }
}


text:
namespace SurgSim
{
namespace Graphics
{

// Wraps the Graphics Model class
class Model : public SurgSim::Framework::Asset
{
};

}
}

#endif


text:
namespace mojo {
namespace internal {
namespace {

ValidationErrorObserverForTesting* g_validation_error_observer = nullptr;
SerializationWarningObserverForTesting* g_serialization_warning_observer =
    nullptr;
bool g_suppress_logging = false;

}  // namespace

const char* ValidationErrorToString(ValidationError error) {
  switch (error) {
    case VALIDATION_ERROR_NONE:
      return "VALIDATION_ERROR_NONE";
    case VALIDATION_ERROR_MISALIGNED_OBJECT:
      return "VALIDATION_ERROR_MISALIGNED_OBJECT";
    case VALIDATION_ERROR_ILLEGAL_MEMORY_RANGE:
      return "VALIDATION_ERROR_ILLEGAL_MEMORY_RANGE";
    case VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER:
      return "VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER";
    case VALIDATION_ERROR_UNEXPECTED_ARRAY_HEADER:
      return "VALIDATION_ERROR_UNEXPECTED_ARRAY_HEADER";
    case VALIDATION_ERROR_ILLEGAL_HANDLE:
      return "VALIDATION_ERROR_ILLEGAL_HANDLE";
    case VALIDATION_ERROR_UNEXPECTED_INVALID_HANDLE:
      return "VALIDATION_ERROR_UNEXPECTED_INVALID_HANDLE";
    case VALIDATION_ERROR_ILLEGAL_POINTER:
      return "VALIDATION_ERROR_ILLEGAL_POINTER";
    case VALIDATION_ERROR_UNEXPECTED_NULL_POINTER:
      return "VALIDATION_ERROR_UNEXPECTED_NULL_POINTER";
    case VALIDATION_ERROR_ILLEGAL_INTERFACE_ID:
      return "VALIDATION_ERROR_ILLEGAL_INTERFACE_ID";
    case VALIDATION_ERROR_UNEXPECTED_INVALID_INTERFACE_ID:
      return "VALIDATION_ERROR_UNEXPECTED_INVALID_INTERFACE_ID";
    case VALIDATION_ERROR_MESSAGE_HEADER_INVALID_FLAGS:
      return "VALIDATION_ERROR_MESSAGE_HEADER_INVALID_FLAGS";
    case VALIDATION_ERROR_MESSAGE_HEADER_MISSING_REQUEST_ID:
      return "VALIDATION_ERROR_MESSAGE_HEADER_MISSING_REQUEST_ID";
    case VALIDATION_ERROR_MESSAGE_HEADER_UNKNOWN_METHOD:
      return "VALIDATION_ERROR_MESSAGE_HEADER_UNKNOWN_METHOD";
    case VALIDATION_ERROR_DIFFERENT_SIZED_ARRAYS_IN_MAP:
      return "VALIDATION_ERROR_DIFFERENT_SIZED_ARRAYS_IN_MAP";
    case VALIDATION_ERROR_UNKNOWN_UNION_TAG:
      return "VALIDATION_ERROR_UNKNOWN_UNION_TAG";
    case VALIDATION_ERROR_UNKNOWN_ENUM_VALUE:
      return "VALIDATION_ERROR_UNKNOWN_ENUM_VALUE";
    case VALIDATION_ERROR_DESERIALIZATION_FAILED:
      return "VALIDATION_ERROR_DESERIALIZATION_FAILED";
    case VALIDATION_ERROR_MAX_RECURSION_DEPTH:
      return "VALIDATION_ERROR_MAX_RECURSION_DEPTH";
  }

  return "Unknown error";
}

void ReportValidationError(ValidationContext* context,
                           ValidationError error,
                           const char* description) {
  if (g_validation_error_observer) {
    g_validation_error_observer->set_last_error(error);
    return;
  }

  if (description) {
    if (!g_suppress_logging) {
      LOG(ERROR) << "Invalid message: " << ValidationErrorToString(error)
                 << " (" << description << ")";
    }
    if (context->message()) {
      context->message()->NotifyBadMessage(
          base::StringPrintf("Validation failed for %s [%s (%s)]",
                             context->description().data(),
                             ValidationErrorToString(error), description));
    }
  } else {
    if (!g_suppress_logging)
      LOG(ERROR) << "Invalid message: " << ValidationErrorToString(error);
    if (context->message()) {
      context->message()->NotifyBadMessage(
          base::StringPrintf("Validation failed for %s [%s]",
                             context->description().data(),
                             ValidationErrorToString(error)));
    }
  }
}

void ReportValidationErrorForMessage(
    mojo::Message* message,
    ValidationError error,
    const char* description) {
  ValidationContext validation_context(
      message->data(), message->data_num_bytes(),
      message->handles()->size(), message,
      description);
  ReportValidationError(&validation_context, error);
}

ScopedSuppressValidationErrorLoggingForTests
    ::ScopedSuppressValidationErrorLoggingForTests()
    : was_suppressed_(g_suppress_logging) {
  g_suppress_logging = true;
}

ScopedSuppressValidationErrorLoggingForTests
    ::~ScopedSuppressValidationErrorLoggingForTests() {
  g_suppress_logging = was_suppressed_;
}

ValidationErrorObserverForTesting::ValidationErrorObserverForTesting(
    const base::Closure& callback)
    : last_error_(VALIDATION_ERROR_NONE), callback_(callback) {
  DCHECK(!g_validation_error_observer);
  g_validation_error_observer = this;
}

ValidationErrorObserverForTesting::~ValidationErrorObserverForTesting() {
  DCHECK(g_validation_error_observer == this);
  g_validation_error_observer = nullptr;
}

bool ReportSerializationWarning(ValidationError error) {
  if (g_serialization_warning_observer) {
    g_serialization_warning_observer->set_last_warning(error);
    return true;
  }

  return false;
}

SerializationWarningObserverForTesting::SerializationWarningObserverForTesting()
    : last_warning_(VALIDATION_ERROR_NONE) {
  DCHECK(!g_serialization_warning_observer);
  g_serialization_warning_observer = this;
}

SerializationWarningObserverForTesting::
    ~SerializationWarningObserverForTesting() {
  DCHECK(g_serialization_warning_observer == this);
  g_serialization_warning_observer = nullptr;
}

}  // namespace internal
}  // namespace mojo


text:
<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use AppBundle\Entity\Imprimante;
use AppBundle\Entity\Cartouche;
use AppBundle\Entity\Commande;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;

class HomeController extends Controller
{
    /**
    * @Route("/", name="homepage")
    * @Security("has_role('ROLE_USER')")
    */
    public function indexAction(Request $request)
    {

        $printers = $this->container->get('app.printer')->findAllPrinters();
        $numberPrinters = $this->container->get('app.printer')->numberOfPrinters();

        $cartridges = $this->container->get('app.cartridge')->findAllCartridges();

        $commandes = $this->container->get('app.commande')->findAllCommandes();

        return $this->render('home/index.html.twig', [
            "printers" => $printers,
            "cartridges" => $cartridges,
            "numberPrinters" => $numberPrinters,
            "commandes" => $commandes,
        ]);
    }
}


text:
<?php

	class Extension_Field_TextBox implements ExtensionInterface {
		public function about() {
			return (object)array(
				'name'			=> 'Text Box',
				'version'		=> '2.0.17',
				'release-date'	=> '2010-04-21',
				'author'		=> (object)array(
					'name'			=> 'R&B Creative',
					'website'		=> 'http://www.randb.com.au/',
					'email'			=> 'me@rowanlewis.com'
				),
				'description' => 'An enhanced text input field.',
				'type'			=> array(
					'Field', 'Core'
				),
			);
		}

		public function getFieldTypes() {
			require_once __DIR__ . '/fields/field.textbox.php';

			return array(
				(object)array(
					'class'		=> 'FieldTextBox',
					'name'		=> __('Text Box')
				)
			);
		}

	/*-------------------------------------------------------------------------
		Utilites:
	-------------------------------------------------------------------------*/

		protected static $addedPublishHeaders = false;
		protected static $addedSettingsHeaders = false;
		protected static $addedFilteringHeaders = false;

		public function addPublishHeaders($page) {
			if ($page and !self::$addedPublishHeaders) {
				$page->insertNodeIntoHead($page->createStylesheetElement(URL . '/extensions/field_textbox/assets/publish.css'));
				$page->insertNodeIntoHead($page->createScriptElement(URL . '/extensions/field_textbox/assets/publish.js'));

				self::$addedPublishHeaders = true;
			}
		}

		public function addSettingsHeaders($page) {
			if ($page and !self::$addedSettingsHeaders) {
				$page->insertNodeIntoHead($page->createStylesheetElement(URL . '/extensions/field_textbox/assets/settings.css'));

				self::$addedSettingsHeaders = true;
			}
		}

		public function addFilteringHeaders($page) {
			if ($page and !self::$addedFilteringHeaders) {
				$page->insertNodeIntoHead($page->createStylesheetElement(URL . '/extensions/field_textbox/assets/filtering.css'));
				$page->insertNodeIntoHead($page->createScriptElement(URL . '/extensions/field_textbox/assets/interface.js'));
				$page->insertNodeIntoHead($page->createScriptElement(URL . '/extensions/field_textbox/assets/filtering.js'));

				self::$addedFilteringHeaders = true;
			}
		}
	}

	return 'Extension_Field_TextBox';


text:
package com.gitevolve.pages

import play.api._
import play.api.mvc._

object Application extends Controller {

  def index = Action {
    Ok(com.gitevolve.pages.html.index())
  }

}


text:
<component name="ProjectRunConfigurationManager">
  <configuration default="false" name="All in taskana-core POSTGRES" type="JUnit" factoryName="JUnit" folderName="lib">
    <module name="taskana-core" />
    <option name="PACKAGE_NAME" value="" />
    <option name="MAIN_CLASS_NAME" value="" />
    <option name="METHOD_NAME" value="" />
    <option name="TEST_OBJECT" value="package" />
    <envs>
      <env name="DB" value="POSTGRES" />
    </envs>
    <method v="2">
      <option name="Make" enabled="true" />
    </method>
  </configuration>
</component>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Malysheva, Karstenia 46(1): 27 (2006)

#### Original name
Hyphodontia syringae Langer

### Remarks
null


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/apigeeconnect/v1/tether.proto

package com.google.cloud.apigeeconnect.v1;

/**
 *
 *
 *

 * HTTP Scheme.
 *

 *
 * Protobuf enum {@code google.cloud.apigeeconnect.v1.Scheme}
 */
public enum Scheme implements com.google.protobuf.ProtocolMessageEnum {
  /**
   *
   *
   *

   * Unspecified scheme.
   *

   *
   * SCHEME_UNSPECIFIED = 0;
   */
  SCHEME_UNSPECIFIED(0),
  /**
   *
   *
   *

   * HTTPS protocol.
   *

   *
   * HTTPS = 1;
   */
  HTTPS(1),
  UNRECOGNIZED(-1),
  ;

  /**
   *
   *
   *

   * Unspecified scheme.
   *

   *
   * SCHEME_UNSPECIFIED = 0;
   */
  public static final int SCHEME_UNSPECIFIED_VALUE = 0;
  /**
   *
   *
   *

   * HTTPS protocol.
   *

   *
   * HTTPS = 1;
   */
  public static final int HTTPS_VALUE = 1;

  public final int getNumber() {
    if (this == UNRECOGNIZED) {
      throw new java.lang.IllegalArgumentException(
          "Can't get the number of an unknown enum value.");
    }
    return value;
  }

  /**
   * @param value The numeric wire value of the corresponding enum entry.
   * @return The enum associated with the given numeric wire value.
   * @deprecated Use {@link #forNumber(int)} instead.
   */
  @java.lang.Deprecated
  public static Scheme valueOf(int value) {
    return forNumber(value);
  }

  /**
   * @param value The numeric wire value of the corresponding enum entry.
   * @return The enum associated with the given numeric wire value.
   */
  public static Scheme forNumber(int value) {
    switch (value) {
      case 0:
        return SCHEME_UNSPECIFIED;
      case 1:
        return HTTPS;
      default:
        return null;
    }
  }

  public static com.google.protobuf.Internal.EnumLiteMap<Scheme> internalGetValueMap() {
    return internalValueMap;
  }

  private static final com.google.protobuf.Internal.EnumLiteMap<Scheme> internalValueMap =
      new com.google.protobuf.Internal.EnumLiteMap<Scheme>() {
        public Scheme findValueByNumber(int number) {
          return Scheme.forNumber(number);
        }
      };

  public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() {
    if (this == UNRECOGNIZED) {
      throw new java.lang.IllegalStateException(
          "Can't get the descriptor of an unrecognized enum value.");
    }
    return getDescriptor().getValues().get(ordinal());
  }

  public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() {
    return getDescriptor();
  }

  public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() {
    return com.google.cloud.apigeeconnect.v1.TetherProto.getDescriptor().getEnumTypes().get(2);
  }

  private static final Scheme[] VALUES = values();

  public static Scheme valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
    if (desc.getType() != getDescriptor()) {
      throw new java.lang.IllegalArgumentException("EnumValueDescriptor is not for this type.");
    }
    if (desc.getIndex() == -1) {
      return UNRECOGNIZED;
    }
    return VALUES[desc.getIndex()];
  }

  private final int value;

  private Scheme(int value) {
    this.value = value;
  }

  // @@protoc_insertion_point(enum_scope:google.cloud.apigeeconnect.v1.Scheme)
}


text:
module RuboCop
  module Formatter
    # This formatter displays just a list of the files with offenses in them,
    # separated by newlines. The output is machine-parsable.
    #
    # Here's the format:
    #
    # /some/file
    # /some/other/file
    class FileListFormatter < BaseFormatter
      def file_finished(file, offenses)
        return if offenses.empty?

        output.printf("%s\n", file)
      end
    end
  end
end


text:
import { AvailableHotels, getHotels, HotelsFilter, HotelsFilterJSON} from '../Hotels';

export default class HotelsModule {
	public getHotels(filter: HotelsFilterJSON): Promise<AvailableHotels> {
		return getHotels(new HotelsFilter(filter));
	}
}


text:
module Fog
  module Compute
    class Ovirt
      class Real
        def attach_volume(id, options)
          raise ArgumentError, "instance id is a required parameter" unless id
          raise ArgumentError, "volume id is a required parameter for attach-volume" unless options.key? :id

          client.attach_volume(id, options[:id])
        end
      end

      class Mock
        def attach_volume(id, options)
          raise ArgumentError, "instance id is a required parameter" unless id
          raise ArgumentError, "volume id is a required parameter for attach-volume" unless options.key? :id
          true
        end
      end
    end
  end
end


text:
package net

import (
	"net"
	"time"
)

var (
	emptyTime time.Time
)

type TimeOutReader struct {
	timeout    int
	connection net.Conn
}

func NewTimeOutReader(timeout int, connection net.Conn) *TimeOutReader {
	return &TimeOutReader{
		timeout:    timeout,
		connection: connection,
	}
}

func (reader *TimeOutReader) Read(p []byte) (n int, err error) {
	deadline := time.Duration(reader.timeout) * time.Second
	reader.connection.SetReadDeadline(time.Now().Add(deadline))
	n, err = reader.connection.Read(p)
	reader.connection.SetReadDeadline(emptyTime)
	return
}


text:
#ifndef FIRESTORE_TEST_ANDROID_UTIL_AUTOID_H_
#define FIRESTORE_TEST_ANDROID_UTIL_AUTOID_H_

#include <string>

namespace firebase {
namespace firestore {
namespace util {

// Generates a random ID suitable for use as a document ID.
std::string CreateAutoId();

}  // namespace util
}  // namespace firestore
}  // namespace firebase

#endif  // FIRESTORE_TEST_ANDROID_UTIL_AUTOID_H_


text:
# jqTweets

A simple jQuery plugin to display a twitter feed with images from
pic.twitter.com and Instagram. Output from this library looks very simmilar to
that produced by the Twitter
["Embedded Timelines"](https://dev.twitter.com/docs/embedded-timelines)
feature.

This code is based on the
[excellent tutorial series at Queeness.com](http://www.queness.com/post/8881/create-a-twitter-feed-with-attached-images-from-media-entities)
Image loading code added by me
([Aaron Snoswell](http://twitter.com/aaronsnoswell)), the author.

## Usage

 1) Include [jQuery](http://jquery.com/) and jquery.jqtweets.js to your html
file.

```html
<script src="js/jquery.js"></script>
<script src="js/jquery.jqtweets.js"></script>
```

 2) Create a div where you would like the tweets to show up.

```html
<div id="mytweets" ></div>
```

 3) Create a jqTweets object, then load some tweets!

```js
var tweets = new jqTweet("YourUsername", "#mytweets", 10);

tweets.loadTweets(function() {
    console.log("Got tweets!");
});
```

Tweets will be fetched from the twitter server and stuffed into your div. Any
images from http://pic.twitter.com/ or http://instagr.am/ will automatically
be asynchronously fetched and stuffed into the feed as well.

jqTweet takes 3 paramaters, the username you would like to fetch tweets for
(without the '@' prefix), the div you would like to place the tweets in (can
be a css identifier, as in the example above, or an actual element), and the
number of tweets you would like to fetch.

You can refresh the twitter feed at any time by calling
`jqTweets.loadTweets` again, which takes an optional completion callback. All
tweet fetching runs asynchronously.

 4) (Optional) If you are expecting images from Instagram in your tweet feed,
add the following css to your page somewhere.

```css
/* Hide tweet images that haven't been fetched from Instagram yet */
img[src=""] {
    display: none;
}
```

## Twitter API Limits

Note that the
[Twitter API terms of service](https://dev.twitter.com/terms/api-terms) and
[rate limiting](https://dev.twitter.com/docs/rate-limiting) apply to this
library - don't do stupid things and don't try and load tweets from Twitter
more than 150 times per day per IP Address.

It is advised that the user add client-side caching to prevent going over this
limit. A library, such as
[easy-app-cache](https://github.com/aaronsnoswell/easy-app-cache) might be
useful for this ;)

## Markup

The tweet markup is desinged to be minimalistic and easy to style. It looks
kinda like the following;

```html
<div id="tweets">
    <div class="tweet">Tweet text goes here... Usernames and hashtags will be automatically linkified
        <div class="tweet_media">
            <a ><img /></a>
            <a ><img /></a>
            <!-- ... for each image attached to the tweet -->
        </div>
    </div>
</div>
```

## License

EAC is released under the MIT license - you're good to use it wherever,
I'd love to know about it though ;)

Happy Coding!


text:
namespace org
{
namespace w3c
{
namespace dom
{
namespace bootstrap
{

css::CSSStyleDeclaration DocumentCSSImp::getOverrideStyle(Element elt, const Nullable<std::u16string>& pseudoElt)
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

}
}
}
}


text:
/**
 *
 * Apply your custom CSS here
 *
*/

body {
}

a {
}
.form-inline .form-group{
        width: 25%;
        margin-left: 30px;
        margin-bottom: 22px;
        color:#000000;
}
.form-group label{
        margin-left: 7px;
        color: black;
        font-weight: bold;
}
.form-control{
        width: 100% !important;
}

.error label{
        color: rgb(209, 113, 72) !important;
}
.error input::-webkit-input-placeholder {
        color: rgb(209, 113, 72);
}
.error input{
        border: 1px solid rgb(209, 113, 72);
}

table{
        font-size: 14px;
        text-align: center;
}
.linker{
        color: #979898;
        padding-left: 0px;
        padding-top: 0px;
        margin-bottom: -7px;
}
.appoint{
        background-color: #b3e8cf;
        padding-bottom: 8px;
        padding-top: 19px;
        color: black;
}
.row.appoint div {
        padding-left: 0px;
}
.appoint-title{
        width: 95%;
        text-align: center;
}

.has-error .help-block{
        color: #da0000;
}
.nav.nav-tabs>li>a {
        border: none;
        background-color: #979898;
        margin-right: 5px;
        padding-left: 20px;
        padding-right: 20px;
        font-weight: bold;
        cursor: pointer;
}
.nav.nav-tabs>li>a:hover {
        border: none;
        background-color: #e4e4e4;
}
table.table tr.filters{
        background-color: #d4dec6;
}
.table-striped>tbody>tr:nth-child(odd) {
        background-color: #f5efb5;
        color: black;
            font-size: 15px;
}
.table-striped>tbody>tr:nth-child(even) {
        background-color: #caffe6;
        color: black;
            font-size: 15px;
}
.table.table-bordered>thead>tr>td, .table.table-bordered>tbody>tr>td, .table.table-bordered>tfood>tr>td, .table.table-bordered>thead>tr>th, .table.table-bordered>tbody>tr>th, .table.table-bordered>tfood>tr>th{
        border-color: #b7b7b7;
}
.table-bordered>thead>tr>th, .table-bordered>tbody>tr>th, .table-bordered>tfoot>tr>th, .table-bordered>thead>tr>td, .table-bordered>tbody>tr>td, .table-bordered>tfoot>tr>td{
        border: 1px solid #a7a7a7;
}
.table-responsive[data-pattern=priority-columns]>.table-bordered {
        border: 1px solid #b7b7b7;
}
.table>caption+thead>tr:first-child>th, .table>colgroup+thead>tr:first-child>th, .table>thead:first-child>tr:first-child>th, .table>caption+thead>tr:first-child>td, .table>colgroup+thead>tr:first-child>td, .table>thead:first-child>tr:first-child>td {
        border-top: 1px solid #b7b7b7;
        background-color: #ffd2d2;
}
.table>caption+thead>tr:first-child>th, .table>colgroup+thead>tr:first-child>th, .table>thead:first-child>tr:first-child>th, .table>caption+thead>tr:first-child>td, .table>colgroup+thead>tr:first-child>td, .table>thead:first-child>tr:first-child>td {
        border-top: 1px solid #b7b7b7;
        background-color: #f9cdcd;
}
.filters .form-control{
        border: 1px solid #afafaf;
}
.table>thead>tr>td, .table>tbody>tr>td, .table>tfood>tr>td, .table>thead>tr>th, .table>tbody>tr>th, .table>tfood>tr>th {
        padding: 6px 15px;
}

table.table tr td:last-child {
        display: inline-flex;
        border: 0;
}
table.table tr td:last-child a {
        padding: 4px;
}
.table>thead:first-child>tr:first-child>th{
        width: 70px;
}
.formm .form-control{
        border: 1px solid #9a9a9a;
        height: 37px;
        color: black;
            font-size: 15px;
}
.portcall {
        color: #0049a0;
        font-size: 16px;
        margin-left: 31px;
        margin-bottom: 12px;
        cursor: pointer;
        text-decoration: underline;
}
.colo.nav.nav-tabs>li>a{
        // background-color: #b9c7a7;
}
.colo.nav.nav-tabs>li.active>a {
        background-color: #b9c7a7;
}
.estimat.nav.nav-tabs>li.active>a {
        border: 0;
        background-color: #e0e0e0;
}
.outterr{
        width: 100%;
        height: 100%;
        padding: 10px;
        background-color: #e0e0e0;
}
html .select2-drop .select2-results li.select2-result-selectable .select2-result-label {
    color: #000000;
    padding-left: 15px;
}
form .form-group .form-control{
        color: black;
            font-size: 15px;
}
.form-group label{
        color: black;
}
.form-control {
    border: 1px solid #bdbcbc;
    color: black;
}
.panel{
        background-color: #ffffd9;
}


text:
.icon-arrow-up--pink {
	background-image: url('../images/icons/arrow-up--pink.png');
	background-repeat: no-repeat;
}
.icon-arrow-down--blue {
	background-image: url('../images/icons/arrow-down--blue.png');
	background-repeat: no-repeat;
}
.icon-arrow-down--white {
	background-image: url('../images/icons/arrow-down--white.png');
	background-repeat: no-repeat;
}
.icon-arrow-down--yellow {
	background-image: url('../images/icons/arrow-down--yellow.png');
	background-repeat: no-repeat;
}
.icon-arrow-left--blue {
	background-image: url('../images/icons/arrow-left--blue.png');
	background-repeat: no-repeat;
}
.icon-arrow-left--white {
	background-image: url('../images/icons/arrow-left--white.png');
	background-repeat: no-repeat;
}
.icon-arrow-left--yellow {
	background-image: url('../images/icons/arrow-left--yellow.png');
	background-repeat: no-repeat;
}
.icon-arrow-right--blue {
	background-image: url('../images/icons/arrow-right--blue.png');
	background-repeat: no-repeat;
}
.icon-arrow-right--white {
	background-image: url('../images/icons/arrow-right--white.png');
	background-repeat: no-repeat;
}
.icon-arrow-right--yellow {
	background-image: url('../images/icons/arrow-right--yellow.png');
	background-repeat: no-repeat;
}
.icon-pdf--blue {
	background-image: url('../images/icons/pdf--blue.png');
	background-repeat: no-repeat;
}
.icon-pdf--pink {
	background-image: url('../images/icons/pdf--pink.png');
	background-repeat: no-repeat;
}
.icon-pdf--yellow {
	background-image: url('../images/icons/pdf--yellow.png');
	background-repeat: no-repeat;
}
.icon-social-fb--yellow {
	background-image: url('../images/icons/social-fb--yellow.png');
	background-repeat: no-repeat;
}
.icon-social-twitter--yellow {
	background-image: url('../images/icons/social-twitter--yellow.png');
	background-repeat: no-repeat;
}


text:
layout: post
title: This Harvard Grad's Site Might Just Be The Future of Music
thumbnail: /img/future-of-music.png
---

    Most major music sites are betting big on the all-inclusive streaming model.

    Artists hate it. They feel they're being payed pennies on the dollar for their music. But it seems to be what listeners want, and labels have capitulated
    to streaming companies like Spotify, Apple, and Google. But maybe it's not the only way?

    Perhaps, in addition to these services, artists will in the future offer their own monthly streaming services
    , with special benefits that appeal to their most loyal followers. Maybe musicians can make music profitable and personal again.

    It's no longer a "maybe".
    Harvard grad and grammy-nominated musician Ryan Leslie recently launched an experiment in these ideas, and by doing so he may have just saved the music
    business from its steady decline.

    Leslie's new club, mzrt.life, is a streaming service dedicated to solely his music.
    For $1 a month, he gives fans access to one new song per month. It's an ever-growing album which Leslie intends to keep going indefinitely, outwardly
    claiming to last a few hundred months/songs.

    For higher subscription fees, fans can message with Ryan
    . For even higher fees, fans can get autographs, call him in his studio while he's recording, fly privately with Leslie to his concerts, and sit in VIP
    seats.

  {{ site.theme.header_text }}

    It's an experiment in varying levels of engagement,
    allowing fans to engage as much, or as little, as they want. Leslie is currently offering plans for $1, 5, 10, 25, 100, and 1000 per month.

    This model is never going to be the major revenue generator for artists.
    It's not going to replace streaming altogether. But this is a clever way to give avid fans a bit more than just an album to listen to, and to guarantee
    some consistent recurring revenue for artists in the process.

    For ages, Spotify has claimed one of its core benefits to artists to be "promotion" and "discovery"
    , but until now, this promotion didn't often lead to tangible benefits – album sales, ticket sales, merchandise.

    This will work especially well for indie bands with small, but loyal followings.

    Mzrt is clearly just an experiment.
    Leslie is running this off of a simple website powered by payment-platform Gumroad. Still, Leslie might have just stumbled upon a model with huge
    potential.

    Would you pay one of your favorite artists for more access, and monthly music?


text:
#import <UIKit/UIKit.h>
#import <Cordova/CDVPlugin.h>
#import <Cordova/CDVShared.h>

@interface GPIBeacon : CDVPlugin <CLLocationManagerDelegate>{
}

@property (nonatomic, strong) CLLocationManager* locationManager;

@property (strong, nonatomic) NSMutableDictionary *regionDict;
@property (strong, nonatomic) NSDictionary *data;

@property (strong, nonatomic) NSDate *lastNigh;
@property (strong, nonatomic) NSDate *lastFar;

//- (BOOL)hasIBeaconSupport;

- (void)addRegion:(CDVInvokedUrlCommand*)command;
- (void)addBeacon:(CDVInvokedUrlCommand*)command;
- (void)addGeofence:(CDVInvokedUrlCommand*)command;
- (void)setDefaults:(CDVInvokedUrlCommand*)command;

- (void)locationManager:(CLLocationManager*)manager
       didFailWithError:(NSError*)error;

@end


text:
using System.Collections.Generic;

namespace Casimodo.Lib.Web.Auth
{

    public class AuthPartQuery
    {
        public string Part { get; set; }
        public string Group { get; set; }
        public string VRole { get; set; }
    }

    public class AuthPartQueryResult
    {
        public string Part { get; set; }
        public string Group { get; set; }

        public List<AuthPermissionQueryResult> Permissions { get; set; } = new List<AuthPermissionQueryResult>();

        public override string ToString()
        {
            return $"{Part} group:{Group}";
        }
    }

    public class AuthPermissionQueryResult
    {
        public string VRole { get; set; }
        public string Action { get; set; }

        public override string ToString()
        {
            return $"{Action} vrole:{VRole}";
        }
    }

    public class AuthPartQueryResultContainer
    {
        public string UserId { get; set; }
        public string UserName { get; set; }
        public string[] UserRoles { get; set; }

        public List<AuthPartQueryResult> Items { get; set; } = new List<AuthPartQueryResult>();
    }
}


text:
import * as React from 'react';

import './Weapon.scss';

export class Weapon extends React.Component<any, any> {
  render() {

    return (

    );
  }
}


text:
using System;
using System.Collections.Generic;

namespace BlockChainSharp.Dto
{
    public class BitcoinTransaction
    {
        public UInt32 TransactionVersionNumber { get; set; }
        public Int64 InputCount { get; set; }
        public Int64 OutputCount { get; set; }
        public List<BitcoinInput> Inputs { get; set; }
        public List<BitcoinOutput> Outputs { get; set; }
        public UInt32 LockTime { get; set; }

        public BitcoinTransaction()
        {
            Inputs = new List<BitcoinInput>();
            Outputs = new List<BitcoinOutput>();
        }
    }
}


text:
import tensorflow as tf

from tensorlayer import logging
from tensorlayer.initializers import constant
from tensorlayer.layers.core import Layer

__all__ = [
    'Scale',
]

class Scale(Layer):
    """The :class:`Scale` class is to multiple a trainable scale value to the layer outputs. Usually be used on the output of binary net.

    Parameters
    ----------
    init_scale : float
        The initial value for the scale factor.
    name : a str
        A unique layer name.

    Examples
    ----------
    >>> inputs = tl.layers.Input([8, 3])
    >>> dense = tl.layers.Dense(n_units=10)(inputs)
    >>> outputs = tl.layers.Scale(init_scale=0.5)(dense)
    >>> model = tl.models.Model(inputs=inputs, outputs=[dense, outputs])
    >>> dense_out, scale_out = model(data, is_train=True)

    """

    def __init__(
        self,
        init_scale=0.05,
        name='scale',
    ):
        super(Scale, self).__init__(name)
        self.init_scale = init_scale

        self.build((None, ))
        self._built = True

        logging.info("Scale  %s: init_scale: %f" % (self.name, self.init_scale))

    def __repr__(self):
        s = '{classname}('
        s += 'init_scale={init_scale},'
        s += 'name={name}'
        s += ")"
        return s.format(classname=self.__class__.__name__, **self.__dict__)

    def build(self, inputs_shape):
        self.scale = self._get_weights("scale", shape=[1], init=constant(value=self.init_scale))

    # @tf.function
    def forward(self, inputs):
        outputs = inputs * self.scale
        return outputs


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Grabacr07.KanColleWrapper.Models.Raw;
using Livet.EventListeners;

namespace Grabacr07.KanColleWrapper.Models
{
	/// <summary>
	/// 艦種を表します。
	/// </summary>
	public class ShipType : RawDataWrapper<kcsapi_mst_stype>, IIdentifiable
	{
		public int Id => this.RawData.api_id;

		public string Name { get; private set; }

		public int SortNumber => this.RawData.api_sortno;

		public ShipType(kcsapi_mst_stype rawData) : base(rawData)
        {
            this.Name = Translation.TranslationHelper.TranslateShipTypeName(this.Id, this.RawData.api_name);

            this.CompositeDisposable.Add(new PropertyChangedEventListener(Globalization.ResourceService.Current)
            {
                (sender, args) =>
                {
                    this.Name = Translation.TranslationHelper.TranslateShipTypeName(this.Id, this.RawData.api_name);
                    this.RaisePropertyChanged(nameof(this.Name));
                }
            });
        }

		public override string ToString()
		{
			return $"ID = {this.Id}, Name = \"{this.Name}\"";
		}

		#region static members

	    public static ShipType Dummy { get; } = new ShipType(new kcsapi_mst_stype
		{
		    api_id = 999,
		    api_sortno = 999,
		    api_name = "不審船",
		});

	    #endregion
	}
}


text:
Fighting with Unique Constraints
--------------------------------
Preconditions:

* Our Person has unique `username` - 2 people cannot register with the same username.
* Our test is run against a remote instance of the app and Persons persist between 2 test runs

The 1st time we run the test everything is great:

```java
@Test public void canRegisterNewUser() {
        String username = "feynman";
        RestService.instance.save(new Person(username));
    }
```

The 2nd time we run it - it fails because user `feynman` already exists in DB. What do we do?

## Option 1: Clear DB between test runs

* Write an external shell script that logs in to the DB and clears it. Ouch! This appears to be more
_complicated_ than it looks.
* The script needs to be run both from CI Server as well as on local machines of devs/testers.
* Won't save when multiple people are running tests at the same time against the same env

## Option 2: Clear tests data before test run

* Again - _complicated_ since for each unique piece of data we need a way to clean it.
* Need to write logic to access DB? If DB is refactored the tests would fail.
* Need to write backdoors in the API? Still additional efforts. And need to keep that API from production some how.
* Still won't save when multiple people are running tests against the same env

## Option 3: Randomization

```java
@Test public void canRegisterNewUser() {
    String username = alphanumeric(1, 20);
    RestService.instance.save(new Person(username));
}
```


text:
/* eslint-disable amphtml-internal/html-template */
/* eslint-disable indent */

const html = require('./app-index/html');

const SCRIPT = `
/**
 * @license
 * Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
 */

'use strict'; {
  customElements.define('amp-viewer',
    class AmpViewerElement extends HTMLElement {

      constructor() {
        super();

        if (!window.AMP_SHADOW) {
          window.AMP_SHADOW = true;
          this._installScript(
            'https://cdn.ampproject.org/shadow-v0.js');
        }

        this._amp = null;
        this._src = '';
        this._host = null;
      }

      static get observedAttributes() {
        return ['src'];
      }

      set src(src) {
        if (this._src === src) {
          return;
        }

        this._src = src;
        this._clear();
        if (!src) {
          this.removeAttribute('src');
        } else {
          this.setAttribute('src', src);
          this._loadDocument(src);
        }
      }

      get src() {
        return this._src;
      }

      attributeChangedCallback(name, old, value) {
        if (old !== value) this.src = value;
      }

      _setVisibilityState(state) {
        if (this._amp) {
          this._amp._setVisibilityState(state);
        }
      }

      _clear() {
        if (this._amp) {
          this._amp.close();
          this._amp = null;
        }
        if (this._host) {
          this.removeChild(this._host);
          this._host = null;
        }
      }

      _loadDocument(src) {
        this._fetchDocument(src, function (doc) {
          (window.AMP = window.AMP || []).push(function (AMP) {
            this._host = window.document.createElement('div');
            this._host.classList.add('amp-doc-host');
            this.appendChild(this._host);
            this._amp = AMP.attachShadowDoc(this._host, doc,
              src);
          }.bind(this));
        }.bind(this));
      }

      _installScript(src) {
        var ownerDoc = this.ownerDocument;
        var el = ownerDoc.createElement('script');
        el.setAttribute('src', src);
        ownerDoc.head.appendChild(el);
      }

      _fetchDocument(src, callback) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', src, true);
        xhr.responseType = 'document';
        xhr.setRequestHeader('Accept', 'text/html');
        xhr.onreadystatechange = function () {
          if (xhr.readyState < /* STATUS_RECEIVED */ 2) {
            return;
          }
          if (xhr.status < 100 || xhr.status > 599) {
            xhr.onreadystatechange = null;
            throw new Error(\`Unknown HTTP status \${xhr.status}\`);
            return;
          }
          if (xhr.readyState == /* COMPLETE */ 4) {
            if (xhr.responseXML) {
              callback(xhr.responseXML);
            } else {
              throw new Error('No xhr.responseXML');
            }
          }
        };
        xhr.onerror = function () {
          throw new Error('Network failure')
        };
        xhr.onabort = function () {
          throw new Error('Request aborted')
        };
        xhr.send();
      }
    });
};
`;

const renderShadowViewer = ({src, baseHref}) => html`<!doctype html>
<html>
  <head>
    <base href="${baseHref}">
    <script>
      ${SCRIPT}
    </script>
  </head>
  <body>
    <amp-viewer src="http://localhost:8000/${src}"></amp-viewer>
  </body>
</html>`;

module.exports = {renderShadowViewer};


text:
<?php

declare(strict_types=1);

namespace AlphaVantage\Api;

use DateTime;

class Fundamentals extends AbstractApi
{
    public const STATE_ACTIVE = 'active';
    public const STATE_DELISTED = 'delisted';

    public const HORIZON_3MONTH = '3month';
    public const HORIZON_6MONTH = '6month';
    public const HORIZON_12MONTH = '12month';

    /**
     * @param string $symbol
     * @param null|string $dataType
     * @return array
     */
    public function companyOverview(
        string  $symbol,
        ?string $dataType = self::DATA_TYPE_JSON
    ) {
        return $this->get(
            'OVERVIEW',
            $symbol,
            [
                'datatype' => $dataType,
            ]
        );
    }

    /**
     * @param string $symbol
     * @param null|string $dataType
     * @return array
     */
    public function earnings(
        string  $symbol,
        ?string $dataType = self::DATA_TYPE_JSON
    ) {
        return $this->get(
            'EARNINGS',
            $symbol,
            [
                'datatype' => $dataType,
            ]
        );
    }

    /**
     * @param string $symbol
     * @param null|string $dataType
     * @return array
     */
    public function incomeStatement(
        string  $symbol,
        ?string $dataType = self::DATA_TYPE_JSON
    ) {
        return $this->get(
            'INCOME_STATEMENT',
            $symbol,
            [
                'datatype' => $dataType,
            ]
        );
    }

    /**
     * @param string $symbol
     * @param null|string $dataType
     * @return array
     */
    public function balanceSheet(
        string  $symbol,
        ?string $dataType = self::DATA_TYPE_JSON
    ) {
        return $this->get(
            'BALANCE_SHEET',
            $symbol,
            [
                'datatype' => $dataType,
            ]
        );
    }

    /**
     * @param string $symbol
     * @param null|string $dataType
     * @return array
     */
    public function cashFlow(
        string  $symbol,
        ?string $dataType = self::DATA_TYPE_JSON
    ) {
        return $this->get(
            'CASH_FLOW',
            $symbol,
            [
                'datatype' => $dataType,
            ]
        );
    }

    /**
     * @param string $status
     * @param null|DateTime $date
     * @param null|string $dataType
     * @return array
     */
    public function listingStatus(
        string    $status = self::STATE_ACTIVE,
        ?DateTime $date = null,
        ?string   $dataType = self::DATA_TYPE_JSON
    ) {
        return $this->get(
            'LISTING_STATUS',
            null,
            [
                'status' => $status,
                'datatype' => $dataType,
                'date' => $date ? $date->format('Y-m-d') : null,
            ]
        );
    }

    /**
     * @param string $horizon
     * @param null|string $symbol
     * @param null|string $dataType
     * @return array
     */
    public function earningsCalendar(
        string $horizon = self::HORIZON_3MONTH,
        ?string $symbol = null,
        ?string $dataType = self::DATA_TYPE_JSON
    ) {
        return $this->get(
            'EARNINGS_CALENDAR',
            $symbol,
            [
                'horizon' => $horizon,
                'datatype' => $dataType,
            ]
        );
    }

    /**
     * @param null|string $dataType
     * @return array
     */
    public function ipoCalendar(
        ?string $dataType = self::DATA_TYPE_JSON
    ) {
        return $this->get(
            'IPO_CALENDAR',
            null,
            [
                'datatype' => $dataType,
            ]
        );
    }
}


text:
"""
A much simpler testing framework than PyUnit

tests a module by running all functions in it whose name starts with 'test'

a test fails if it raises an exception, otherwise it passes

functions are try_all and try_single
"""

# Written by Bram Cohen
# see LICENSE.txt for license information

from traceback import print_exc
from sys import modules

def try_all(excludes = [], excluded_paths=[]):
    """
    tests all imported modules

    takes an optional list of module names and/or module objects to skip over.
    modules from files under under any of excluded_paths are also skipped.
    """
    failed = []
    for modulename, module in modules.items():
        # skip builtins
        if not hasattr(module, '__file__'):
            continue
        # skip modules under any of excluded_paths
        if [p for p in excluded_paths if module.__file__.startswith(p)]:
            continue
        if modulename not in excludes and module not in excludes:
            try_module(module, modulename, failed)
    print_failed(failed)

def try_single(m):
    """
    tests a single module

    accepts either a module object or a module name in string form
    """
    if type(m) is str:
        modulename = m
        module = __import__(m)
    else:
        modulename = str(m)
        module = m
    failed = []
    try_module(module, modulename, failed)
    print_failed(failed)

def try_module(module, modulename, failed):
    if not hasattr(module, '__dict__'):
        return
    for n, func in module.__dict__.items():
        if not callable(func) or n[:4] != 'test':
            continue
        name = modulename + '.' + n
        try:
            print 'trying ' + name
            func()
            print 'passed ' + name
        except:
            print_exc()
            failed.append(name)
            print 'failed ' + name

def print_failed(failed):
    print
    if len(failed) == 0:
        print 'everything passed'
    else:
        print 'the following tests failed:'
        for i in failed:
            print i


text:
using System;
using System.Collections.Generic;
using System.Windows;
using Microsoft.Shell;

namespace BarbaTunnel.Monitor
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : ISingleInstanceApp
    {
        private const string Unique = @"Local\BarbaMonitor_SingleInstance";

        [STAThread]
        public static void Main()
        {
            if (SingleInstance<App>.InitializeAsFirstInstance(Unique))
            {
                var application = new App();

                application.InitializeComponent();
                application.Run();

                // Allow single instance code to perform cleanup operations
                SingleInstance<App>.Cleanup();
            }
        }

        #region ISingleInstanceApp Members

        public bool SignalExternalCommandLineArgs(IList<string> args)
        {
            // handle command line arguments of second instance
            // ...
            if (MainWindow.WindowState == System.Windows.WindowState.Minimized)
                MainWindow.WindowState = System.Windows.WindowState.Normal;
            MainWindow.Visibility = Visibility.Visible;
            MainWindow.Activate();
            return true;
        }

        #endregion
    }
}


text:
package ru.geekbrains.android2.lesson26;

import android.app.Activity;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

/**
 * The configuration screen for the {@link SmsWidget SmsWidget} AppWidget.
 */
public class SmsWidgetConfigureActivity extends Activity {

    private static final String TAG = "SmsWidgetConfigure";

    static final String PREFS_NAME = "ru.geekbrains.android2.lesson26.SmsWidget";
    static final String PREF_PREFIX_KEY = "appwidget_";
    static final String PREF_COUNT_SUFFIX_KEY = "_sms_count";
    int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
    EditText mAppWidgetText;
    EditText mAppWidgetSmsCount;
    View.OnClickListener mOnClickListener = new View.OnClickListener() {
        public void onClick(View v) {
            final Context context = SmsWidgetConfigureActivity.this;

            // When the button is clicked, store the string locally
            String widgetText = mAppWidgetText.getText().toString();
            int smsCount;
            try {
                smsCount = Integer.parseInt(mAppWidgetSmsCount.getText().toString());
            }
            catch (NumberFormatException e) {
                smsCount = 20;
            }
            if ((smsCount < 1) || (smsCount > 20)) {
                smsCount = 20;
            }
            saveTitlePref(context, mAppWidgetId, widgetText, smsCount);
            Log.d(TAG, "smsCount в Sharedpreferences: " + String.valueOf(loadSmsCountPref(context, mAppWidgetId)));

            // It is the responsibility of the configuration activity to update the app widget
            AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
            SmsWidget.updateAppWidget(context, appWidgetManager, mAppWidgetId);

            // Make sure we pass back the original appWidgetId
            Intent resultValue = new Intent();
            resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
            setResult(RESULT_OK, resultValue);
            finish();
        }
    };

    public SmsWidgetConfigureActivity() {
        super();
    }

    // Write the prefix to the SharedPreferences object for this widget
    static void saveTitlePref(Context context, int appWidgetId, String text, int smsCount) {
        SharedPreferences.Editor prefs = context.getSharedPreferences(PREFS_NAME, 0).edit();
        prefs.putString(PREF_PREFIX_KEY + appWidgetId, text);
        prefs.putInt(PREF_PREFIX_KEY + appWidgetId + PREF_COUNT_SUFFIX_KEY, smsCount);
        prefs.apply();
    }

    // Read the prefix from the SharedPreferences object for this widget.
    // If there is no preference saved, get the default from a resource
    static String loadTitlePref(Context context, int appWidgetId) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, 0);
        String titleValue = prefs.getString(PREF_PREFIX_KEY + appWidgetId, null);
        if (titleValue != null) {
            return titleValue;
        } else {
            return context.getString(R.string.appwidget_text);
        }
    }

    static int loadSmsCountPref(Context context, int appWidgetId) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, 0);
        return prefs.getInt(PREF_PREFIX_KEY + appWidgetId + PREF_COUNT_SUFFIX_KEY, 20);
    }

    static void deleteTitlePref(Context context, int appWidgetId) {
        SharedPreferences.Editor prefs = context.getSharedPreferences(PREFS_NAME, 0).edit();
        prefs.remove(PREF_PREFIX_KEY + appWidgetId);
        prefs.apply();
    }

    static void deleteSmsCountPref(Context context, int appWidgetId) {
        SharedPreferences.Editor prefs = context.getSharedPreferences(PREFS_NAME, 0).edit();
        prefs.remove(PREF_PREFIX_KEY + appWidgetId + PREF_COUNT_SUFFIX_KEY);
        prefs.apply();
    }

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        Log.d(TAG, "onCreate");

        // Set the result to CANCELED.  This will cause the widget host to cancel
        // out of the widget placement if the user presses the back button.
        setResult(RESULT_CANCELED);

        setContentView(R.layout.sms_widget_configure);
        mAppWidgetText = (EditText) findViewById(R.id.appwidget_text);
        mAppWidgetSmsCount = (EditText) findViewById(R.id.appwidget_items_count);
        findViewById(R.id.add_button).setOnClickListener(mOnClickListener);

        // Find the widget id from the intent.
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null) {
            mAppWidgetId = extras.getInt(
                    AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
        }

        // If this activity was started with an intent without an app widget ID, finish with an error.
        if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
            finish();
            return;
        }

        mAppWidgetText.setText(loadTitlePref(SmsWidgetConfigureActivity.this, mAppWidgetId));
        mAppWidgetSmsCount.setText(String.valueOf(loadSmsCountPref(SmsWidgetConfigureActivity.this, mAppWidgetId)));
    }

}


text:
package pl.javastart.exception.unsupportedoperationexception;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class UnsupportedExample1 {
    public static void main(String[] args) {
//        List<Integer> numbers= Arrays.asList(5, 10, 15, 20, 25, 30);
        List<Integer> numbers = new ArrayList<>(Arrays.asList(5, 10, 15, 20, 25, 30));

        numbers.add(11);
        numbers.add(22);
        numbers.add(33);

        System.out.println(numbers);
    }
}