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

import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;

import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.Uninterruptibles;
import com.google.devtools.build.lib.testutil.TestUtils;
import com.google.devtools.build.lib.vfs.inmemoryfs.InMemoryFileSystem;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CancellationException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * Tests {@link UnixGlob}
 */
@RunWith(JUnit4.class)
public class GlobTest {

  private Path tmpPath;
  private FileSystem fs;
  private Path throwOnReaddir = null;

  @Before
  public final void initializeFileSystem() throws Exception  {
    fs = new InMemoryFileSystem() {
      @Override
      public Collection<Dirent> readdir(Path path, boolean followSymlinks) throws IOException {
        if (path.equals(throwOnReaddir)) {
          throw new FileNotFoundException(path.getPathString());
        }
        return super.readdir(path, followSymlinks);
      }
    };
    tmpPath = fs.getPath("/globtmp");
    for (String dir : ImmutableList.of("foo/bar/wiz",
                         "foo/barnacle/wiz",
                         "food/barnacle/wiz",
                         "fool/barnacle/wiz")) {
      FileSystemUtils.createDirectoryAndParents(tmpPath.getRelative(dir));
    }
    FileSystemUtils.createEmptyFile(tmpPath.getRelative("foo/bar/wiz/file"));
  }

  @Test
  public void testQuestionMarkMatch() throws Exception {
    assertGlobMatches("foo?", /* => */"food", "fool");
  }

  @Test
  public void testQuestionMarkNoMatch() throws Exception {
    assertGlobMatches("food/bar?" /* => nothing */);
  }

  @Test
  public void testStartsWithStar() throws Exception {
    assertGlobMatches("*oo", /* => */"foo");
  }

  @Test
  public void testStartsWithStarWithMiddleStar() throws Exception {
    assertGlobMatches("*f*o", /* => */"foo");
  }

  @Test
  public void testEndsWithStar() throws Exception {
    assertGlobMatches("foo*", /* => */"foo", "food", "fool");
  }

  @Test
  public void testEndsWithStarWithMiddleStar() throws Exception {
    assertGlobMatches("f*oo*", /* => */"foo", "food", "fool");
  }

  @Test
  public void testMiddleStar() throws Exception {
    assertGlobMatches("f*o", /* => */"foo");
  }

  @Test
  public void testTwoMiddleStars() throws Exception {
    assertGlobMatches("f*o*o", /* => */"foo");
  }

  @Test
  public void testSingleStarPatternWithNamedChild() throws Exception {
    assertGlobMatches("*/bar", /* => */"foo/bar");
  }

  @Test
  public void testSingleStarPatternWithChildGlob() throws Exception {
    assertGlobMatches("*/bar*", /* => */
        "foo/bar", "foo/barnacle", "food/barnacle", "fool/barnacle");
  }

  @Test
  public void testSingleStarAsChildGlob() throws Exception {
    assertGlobMatches("foo/*/wiz", /* => */"foo/bar/wiz", "foo/barnacle/wiz");
  }

  @Test
  public void testNoAsteriskAndFilesDontExist() throws Exception {
    // Note un-UNIX like semantics:
    assertGlobMatches("ceci/n'est/pas/une/globbe" /* => nothing */);
  }

  @Test
  public void testSingleAsteriskUnderNonexistentDirectory() throws Exception {
    // Note un-UNIX like semantics:
    assertGlobMatches("not-there/*" /* => nothing */);
  }

  @Test
  public void testGlobWithNonExistentBase() throws Exception {
    Collection<Path> globResult = UnixGlob.forPath(fs.getPath("/does/not/exist"))
        .addPattern("*.txt")
        .globInterruptible();
    assertThat(globResult).isEmpty();
  }

  @Test
  public void testGlobUnderFile() throws Exception {
    assertGlobMatches("foo/bar/wiz/file/*" /* => nothing */);
  }

  private void assertGlobMatches(String pattern, String... expecteds)
      throws Exception {
    assertGlobMatches(Collections.singleton(pattern), expecteds);
  }

  private void assertGlobMatches(Collection<String> pattern,
                                 String... expecteds)
      throws Exception {
    assertThat(
        new UnixGlob.Builder(tmpPath)
            .addPatterns(pattern)
            .globInterruptible())
    .containsExactlyElementsIn(resolvePaths(expecteds));
  }

  private Set<Path> resolvePaths(String... relativePaths) {
    Set<Path> expectedFiles = new HashSet<>();
    for (String expected : relativePaths) {
      Path file = expected.equals(".")
          ? tmpPath
          : tmpPath.getRelative(expected);
      expectedFiles.add(file);
    }
    return expectedFiles;
  }

  @Test
  public void testIOFailureOnStat() throws Exception {
    UnixGlob.FilesystemCalls syscalls = new UnixGlob.FilesystemCalls() {
      @Override
      public FileStatus statIfFound(Path path, Symlinks symlinks) throws IOException {
        throw new IOException("EIO");
      }

      @Override
      public Collection<Dirent> readdir(Path path, Symlinks symlinks) {
        throw new IllegalStateException();
      }
    };

    try {
      new UnixGlob.Builder(tmpPath)
          .addPattern("foo/bar/wiz/file")
          .setFilesystemCalls(new AtomicReference<>(syscalls))
          .glob();
      fail("Expected failure");
    } catch (IOException e) {
      assertThat(e).hasMessageThat().isEqualTo("EIO");
    }
  }

  @Test
  public void testGlobWithoutWildcardsDoesNotCallReaddir() throws Exception {
    UnixGlob.FilesystemCalls syscalls = new UnixGlob.FilesystemCalls() {
      @Override
      public FileStatus statIfFound(Path path, Symlinks symlinks) throws IOException {
        return UnixGlob.DEFAULT_SYSCALLS.statIfFound(path, symlinks);
      }

      @Override
      public Collection<Dirent> readdir(Path path, Symlinks symlinks) {
        throw new IllegalStateException();
      }
    };

    assertThat(
            new UnixGlob.Builder(tmpPath)
                .addPattern("foo/bar/wiz/file")
                .setFilesystemCalls(new AtomicReference<>(syscalls))
                .glob())
        .containsExactly(tmpPath.getRelative("foo/bar/wiz/file"));
  }

  @Test
  public void testIllegalPatterns() throws Exception {
    assertIllegalPattern("foo**bar");
    assertIllegalPattern("");
    assertIllegalPattern(".");
    assertIllegalPattern("/foo");
    assertIllegalPattern("./foo");
    assertIllegalPattern("foo/");
    assertIllegalPattern("foo/./bar");
    assertIllegalPattern("../foo/bar");
    assertIllegalPattern("foo//bar");
  }

  /**
   * Tests that globs can contain Java regular expression special characters
   */
  @Test
  public void testSpecialRegexCharacter() throws Exception {
    Path tmpPath2 = fs.getPath("/globtmp2");
    FileSystemUtils.createDirectoryAndParents(tmpPath2);
    Path aDotB = tmpPath2.getChild("a.b");
    FileSystemUtils.createEmptyFile(aDotB);
    FileSystemUtils.createEmptyFile(tmpPath2.getChild("aab"));
    // Note: this contains two asterisks because otherwise a RE is not built,
    // as an optimization.
    assertThat(UnixGlob.forPath(tmpPath2).addPattern("*a.b*").globInterruptible()).containsExactly(
        aDotB);
  }

  @Test
  public void testMatchesCallWithNoCache() {
    assertThat(UnixGlob.matches("*a*b", "CaCb", null)).isTrue();
  }

  @Test
  public void testMultiplePatterns() throws Exception {
    assertGlobMatches(Lists.newArrayList("foo", "fool"), "foo", "fool");
  }

  @Test
  public void testMatcherMethodRecursiveBelowDir() throws Exception {
    FileSystemUtils.createEmptyFile(tmpPath.getRelative("foo/file"));
    String pattern = "foo/**/*";
    assertThat(UnixGlob.matches(pattern, "foo/bar")).isTrue();
    assertThat(UnixGlob.matches(pattern, "foo/bar/baz")).isTrue();
    assertThat(UnixGlob.matches(pattern, "foo")).isFalse();
    assertThat(UnixGlob.matches(pattern, "foob")).isFalse();
    assertThat(UnixGlob.matches("**/foo", "foo")).isTrue();
  }

  @Test
  public void testMultiplePatternsWithOverlap() throws Exception {
    assertGlobMatchesAnyOrder(Lists.newArrayList("food", "foo?"),
                              "food", "fool");
    assertGlobMatchesAnyOrder(Lists.newArrayList("food", "?ood", "f??d"),
                              "food");
    assertThat(resolvePaths("food", "fool", "foo")).containsExactlyElementsIn(
        new UnixGlob.Builder(tmpPath).addPatterns("food", "xxx", "*").glob());

  }

  private void assertGlobMatchesAnyOrder(ArrayList<String> patterns,
                                         String... paths) throws Exception {
    assertThat(resolvePaths(paths)).containsExactlyElementsIn(
        new UnixGlob.Builder(tmpPath).addPatterns(patterns).globInterruptible());
  }

  private void assertIllegalPattern(String pattern) throws Exception {
    try {
      new UnixGlob.Builder(tmpPath)
          .addPattern(pattern)
          .globInterruptible();
      fail();
    } catch (IllegalArgumentException e) {
      assertThat(e).hasMessageThat().containsMatch("in glob pattern");
    }
  }

  @Test
  public void testHiddenFiles() throws Exception {
    for (String dir : ImmutableList.of(".hidden", "..also.hidden", "not.hidden")) {
      FileSystemUtils.createDirectoryAndParents(tmpPath.getRelative(dir));
    }
    // Note that these are not in the result: ".", ".."
    assertGlobMatches("*", "not.hidden", "foo", "fool", "food", ".hidden", "..also.hidden");
    assertGlobMatches("*.hidden", "not.hidden");
  }

  @Test
  public void testIOException() throws Exception {
    throwOnReaddir = fs.getPath("/throw_on_readdir");
    throwOnReaddir.createDirectory();
    try {
      new UnixGlob.Builder(throwOnReaddir).addPattern("**").glob();
      fail();
    } catch (IOException e) {
      // Expected.
    }
  }

  @Test
  public void testCheckCanBeInterrupted() throws Exception {
    final Thread mainThread = Thread.currentThread();
    final ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);

    Predicate<Path> interrupterPredicate =
        new Predicate<Path>() {
          @Override
          public boolean apply(Path input) {
            mainThread.interrupt();
            return true;
          }
        };

    Future<?> globResult = null;
    try {
      globResult =
          new UnixGlob.Builder(tmpPath)
              .addPattern("**")
              .setDirectoryFilter(interrupterPredicate)
              .setThreadPool(executor)
              .globAsync(true);
      globResult.get();
      fail(); // Should have received InterruptedException
    } catch (InterruptedException e) {
      // good
    }

    globResult.cancel(true);
    try {
      Uninterruptibles.getUninterruptibly(globResult);
      fail();
    } catch (CancellationException e) {
      // Expected.
    }

    Thread.interrupted();
    assertThat(executor.isShutdown()).isFalse();
    executor.shutdown();
    assertThat(executor.awaitTermination(TestUtils.WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS))
        .isTrue();
  }

  @Test
  public void testCheckCannotBeInterrupted() throws Exception {
    final Thread mainThread = Thread.currentThread();
    final ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
    final AtomicBoolean sentInterrupt = new AtomicBoolean(false);

    Predicate<Path> interrupterPredicate = new Predicate<Path>() {
      @Override
      public boolean apply(Path input) {
        if (!sentInterrupt.getAndSet(true)) {
          mainThread.interrupt();
        }
        return true;
      }
    };

    List<Path> result = new UnixGlob.Builder(tmpPath)
        .addPatterns("**", "*")
        .setDirectoryFilter(interrupterPredicate).setThreadPool(executor).glob();

    // In the non-interruptible case, the interrupt bit should be set, but the
    // glob should return the correct set of full results.
    assertThat(Thread.interrupted()).isTrue();
    assertThat(result)
        .containsExactlyElementsIn(
            resolvePaths(
                ".",
                "foo",
                "foo/bar",
                "foo/bar/wiz",
                "foo/bar/wiz/file",
                "foo/barnacle",
                "foo/barnacle/wiz",
                "food",
                "food/barnacle",
                "food/barnacle/wiz",
                "fool",
                "fool/barnacle",
                "fool/barnacle/wiz"));

    assertThat(executor.isShutdown()).isFalse();
    executor.shutdown();
    assertThat(executor.awaitTermination(TestUtils.WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS))
        .isTrue();
  }
}


text:
<?php
namespace LanguageFirst\RespuestasPreguntasBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * LanguageFirst\RespuestasPreguntasBundle\Entity\RespuestasPreguntas
 */

/**
 * @ORM\Entity
 * @ORM\Table(name="RESPUESTAS_PREGUNTAS")
 */
class RespuestasPreguntas
{
    /** @ORM\Column(type="integer", unique="TRUE")
     *  @ORM\GeneratedValue(strategy="AUTO")
     * */
    protected $clave_respuesta;

    /** @ORM\Column(type="text") */
    protected $titulo_respuesta;

    /** @ORM\Column(type="string", length=5) */
    protected $numero_respuesta;

    /** @ORM\Column(type="string", length=2) */
    protected $ver_num_respuesta;

    /** @ORM\Column(type="string", length=300) */
    protected $instrucciones_respuesta;

    /** @ORM\Column(type="string", length=2) */
    protected $tipo_campo;

    /** @ORM\Column(type="integer") */
    protected $largo_campo;

    /** @ORM\Column(type="integer") */
    protected $alto_campo;

     /** @ORM\Column(type="string", length=2) */
    protected $forzoso;

    /**
    * @ORM\ManyToOne(targetEntity="LanguageFirst\PreguntasSeccionBundle\Entity\PreguntasSeccion")
    * @ORM\JoinColumn(name="clave_pregunta", referencedColumnName="clave_pregunta")
    */
    protected $clave_pregunta;

    /**
     * @ORM\ManyToOne(targetEntity="LanguageFirst\FaseTestBundle\Entity\FaseTest")
     * @ORM\JoinColumn(name="clave_fase", referencedColumnName="clave_fase")
     */
    protected $clave_fase;

    /** @ORM\Column(type="string", length=255) */
    protected $categoria_respuesta;

    /**
     * Set clave_respuesta
     *
     * @param integer $claveRespuesta
     */
    public function setClaveRespuesta($claveRespuesta)
    {
        $this->clave_respuesta = $claveRespuesta;
    }

    /**
     * Get clave_respuesta
     *
     * @return integer
     */
    public function getClaveRespuesta()
    {
        return $this->clave_respuesta;
    }

    /**
     * Set titulo_respuesta
     *
     * @param text $tituloRespuesta
     */
    public function setTituloRespuesta($tituloRespuesta)
    {
        $this->titulo_respuesta = $tituloRespuesta;
    }

    /**
     * Get titulo_respuesta
     *
     * @return text
     */
    public function getTituloRespuesta()
    {
        return $this->titulo_respuesta;
    }

    /**
     * Set numero_respuesta
     *
     * @param string $numeroRespuesta
     */
    public function setNumeroRespuesta($numeroRespuesta)
    {
        $this->numero_respuesta = $numeroRespuesta;
    }

    /**
     * Get numero_respuesta
     *
     * @return string
     */
    public function getNumeroRespuesta()
    {
        return $this->numero_respuesta;
    }

    /**
     * Set ver_num_respuesta
     *
     * @param string $verNumRespuesta
     */
    public function setVerNumRespuesta($verNumRespuesta)
    {
        $this->ver_num_respuesta = $verNumRespuesta;
    }

    /**
     * Get ver_num_respuesta
     *
     * @return string
     */
    public function getVerNumRespuesta()
    {
        return $this->ver_num_respuesta;
    }

    /**
     * Set instrucciones_respuesta
     *
     * @param string $instruccionesRespuesta
     */
    public function setInstruccionesRespuesta($instruccionesRespuesta)
    {
        $this->instrucciones_respuesta = $instruccionesRespuesta;
    }

    /**
     * Get instrucciones_respuesta
     *
     * @return string
     */
    public function getInstruccionesRespuesta()
    {
        return $this->instrucciones_respuesta;
    }

    /**
     * Set tipo_campo
     *
     * @param string $tipoCampo
     */
    public function setTipoCampo($tipoCampo)
    {
        $this->tipo_campo = $tipoCampo;
    }

    /**
     * Get tipo_campo
     *
     * @return string
     */
    public function getTipoCampo()
    {
        return $this->tipo_campo;
    }

    /**
     * Set largo_campo
     *
     * @param integer $largoCampo
     */
    public function setLargoCampo($largoCampo)
    {
        $this->largo_campo = $largoCampo;
    }

    /**
     * Get largo_campo
     *
     * @return integer
     */
    public function getLargoCampo()
    {
        return $this->largo_campo;
    }

    /**
     * Set alto_campo
     *
     * @param integer $altoCampo
     */
    public function setAltoCampo($altoCampo)
    {
        $this->alto_campo = $altoCampo;
    }

    /**
     * Get alto_campo
     *
     * @return integer
     */
    public function getAltoCampo()
    {
        return $this->alto_campo;
    }

    /**
     * Set forzoso
     *
     * @param string $forzoso
     */
    public function setForzoso($forzoso)
    {
        $this->forzoso = $forzoso;
    }

    /**
     * Get forzoso
     *
     * @return string
     */
    public function getForzoso()
    {
        return $this->forzoso;
    }

    /**
     * Set categoria_respuesta
     *
     * @param string $categoriaRespuesta
     */
    public function setCategoriaRespuesta($categoriaRespuesta)
    {
        $this->categoria_respuesta = $categoriaRespuesta;
    }

    /**
     * Get categoria_respuesta
     *
     * @return string
     */
    public function getCategoriaRespuesta()
    {
        return $this->categoria_respuesta;
    }

    /**
     * Set clave_pregunta
     *
     * @param LanguageFirst\PreguntasSeccionBundle\Entity\PreguntasSeccion $clavePregunta
     */
    public function setClavePregunta(\LanguageFirst\PreguntasSeccionBundle\Entity\PreguntasSeccion $clavePregunta)
    {
        $this->clave_pregunta = $clavePregunta;
    }

    /**
     * Get clave_pregunta
     *
     * @return LanguageFirst\PreguntasSeccionBundle\Entity\PreguntasSeccion
     */
    public function getClavePregunta()
    {
        return $this->clave_pregunta;
    }

    /**
     * Set clave_fase
     *
     * @param LanguageFirst\FaseTestBundle\Entity\FaseTest $claveFase
     */
    public function setClaveFase(\LanguageFirst\FaseTestBundle\Entity\FaseTest $claveFase)
    {
        $this->clave_fase = $claveFase;
    }

    /**
     * Get clave_fase
     *
     * @return LanguageFirst\FaseTestBundle\Entity\FaseTest
     */
    public function getClaveFase()
    {
        return $this->clave_fase;
    }
}

redpajama_set_name: RedPajamaGithub


text:
import { Page } from 'puppeteer';
import { waitForPropertyExists, waitForText, waitWhileLoading } from 'utils/waits-utils';
import RadioButton from 'app/element/radiobutton';
import { Language, LinkText } from 'app/text-labels';
import Button from 'app/element/button';
import Textbox from 'app/element/textbox';
import { waitUntilChanged } from 'utils/element-utils';
import Textarea from 'app/element/textarea';
import Modal from './modal';

const modalTitle = 'New Notebook';

export default class NewNotebookModal extends Modal {
  constructor(page: Page, opts?: { xpath?: string; modalIndex?: number }) {
    super(page, opts);
  }

  async isLoaded(): Promise<boolean> {
    await waitForText(this.page, modalTitle, { container: this });
    await this.name().exists(30000);
    return true;
  }

  /**
   * Fill out New Notebook modal:
   * - Type notebook name.
   * - Select notebook language.
   * - Click Create Notebook button.
   * @param {string} notebookName Notebook name.
   * @param {Language} language Notebook language.
   */
  async fillInModal(notebookName: string, language: Language): Promise<void> {
    await this.name().type(notebookName);
    const radio = language === Language.Python ? this.getPythonRadioButton() : this.getRRadioButton();
    await radio.select();
    return this.clickButton(LinkText.CreateNotebook, {
      waitForClose: true,
      waitForLoadingSpinner: false
    });
  }

  name(): Textbox {
    return Textbox.findByName(this.page, { name: 'Name:' }, this);
  }

  getPythonRadioButton(): RadioButton {
    const selector = '//*[@role="dialog"]//label[contains(normalize-space(),"Python 3")]//input[@type="radio"]';
    return new RadioButton(this.page, selector);
  }

  getRRadioButton(): RadioButton {
    const selector = '//*[@role="dialog"]//label[contains(normalize-space(),"R")]//input[@type="radio"]';
    return new RadioButton(this.page, selector);
  }

  createNotebookButton(): Button {
    return Button.findByName(this.page, { name: LinkText.CreateNotebook }, this);
  }

  /**
   * Click 'See Code Preview' button. Returns code contents.
   */
  async previewCode(): Promise<string> {
    const previewButton = Button.findByName(this.page, { name: LinkText.SeeCodePreview }, this);
    const element = await previewButton.asElementHandle();
    await previewButton.click();
    await waitUntilChanged(this.page, element);
    await waitWhileLoading(this.page);

    // Find Preview Code
    const selector = `${this.getXpath()}//textarea[@data-test-id="code-text-box"]`;
    const previewTextArea = new Textarea(this.page, selector);
    // Has 'disabled' property
    await waitForPropertyExists(this.page, selector, 'disabled');
    return previewTextArea.getTextContent();
  }
}


text:
package org.apache.jackrabbit.vault.sync.impl;

/**
 * {@code SyncConstants}...
 */
public class SyncConstants {

    public static final String SYNCLOG_FILE_NAME = ".vlt-sync.log";

    public static final String FILTER_FILE_NAME = ".vlt-sync-filter.xml";

    public static final String CONFIG_FILE_NAME = ".vlt-sync-config.properties";

}


text:
<?php

namespace app\controllers\classes;

use yii\base\Component;
use yii\helpers\ArrayHelper;

/**
 * @property array $possibleValues
 * @property string|array $selectedValues Read only.
 * @property mixed $selectedValue Read only.
 * @property string $name
 */

class Filter extends Component
{
    private $_possibleValues;
    private $_selectedValues;

    /**
     * @param string|array $selectedValues
     */
    public function __construct($selectedValues)
    {
        $this->_selectedValues = $selectedValues;
    }

    /**
     * @return array|mixed
     */
    public function getSelectedValues()
    {
        return $this->_selectedValues;
    }

    /**
     * @param array|ObjectCollection $values
     * @return Filter $this
     */
    public function setPossibleValues($values)
    {
        if (is_object($values))
            $values = $values->toArray();

        $this->_possibleValues = $values;
        return $this;
    }

    public function getPossibleValues()
    {
        return $this->_possibleValues;
    }

    /**
     * @return bool
     */
    public function isSelected()
    {
        return (bool) $this->selectedValues;
    }

    public function getSelectedValue()
    {
        if (!$this->isSelected())
            return null;

        if (is_array($this->selectedValues))
            return $this->selectedValues[0];
        else
            return $this->selectedValues;
    }

    public function setSelectedValues($values)
    {
        if (is_object($values))
            $values = $values->toArray();

        $this->_selectedValues = $values;
        return $this;
    }
}


text:
module Phcscriptcdn
  module Script::VersionsHelper
  end
end


text:
module Ridley
  class EnvironmentObject < Ridley::ChefObject
    set_chef_id "name"
    set_chef_type "environment"
    set_chef_json_class "Chef::Environment"

    attribute :name,
      required: true

    attribute :description,
      default: String.new

    attribute :default_attributes,
      default: Hashie::Mash.new

    attribute :override_attributes,
      default: Hashie::Mash.new

    attribute :cookbook_versions,
      default: Hashie::Mash.new

    # Set an environment level default attribute given the dotted path representation of
    # the Chef attribute and value
    #
    # @example setting and saving an environment level default attribute
    #
    #   obj = environment.find("production")
    #   obj.set_default_attribute("my_app.billing.enabled", false)
    #   obj.save
    #
    # @param [String] key
    # @param [Object] value
    #
    # @return [Hashie::Mash]
    def set_default_attribute(key, value)
      attr_hash = Hashie::Mash.from_dotted_path(key, value)
      self.default_attributes = self.default_attributes.deep_merge(attr_hash)
    end

    # Set an environment level override attribute given the dotted path representation of
    # the Chef attribute and value
    #
    # @example setting and saving an environment level override attribute
    #
    #   obj = environment.find("production")
    #   obj.set_override_attribute("my_app.billing.enabled", false)
    #   obj.save
    #
    # @param [String] key
    # @param [Object] value
    #
    # @return [Hashie::Mash]
    def set_override_attribute(key, value)
      attr_hash = Hashie::Mash.from_dotted_path(key, value)
      self.override_attributes = self.override_attributes.deep_merge(attr_hash)
    end
  end
end


text:
import React, {useCallback} from "react"
import {Edge, EdgeKind, EdgeType} from "../../../../types"
import BaseModalContent from "../BaseModalContent"
import EditableEditor from "../editors/EditableEditor"
import {useDiffMark} from "../PathsToMark"

interface Props {
  edge: Edge,
  readOnly?: boolean,
  changeEdgeTypeValue: (type: EdgeType["type"]) => void,
  changeEdgeTypeCondition: (condition: EdgeType["condition"]["expression"]) => void,
  showValidation?: boolean,
  showSwitch?: boolean,
  variableTypes,
  edgeErrors?,
}

export default function EdgeDetailsContent(props: Props): JSX.Element | null {
  const {
    edge,
    edgeErrors,
    readOnly,
    changeEdgeTypeCondition,
    showValidation,
    showSwitch,
    changeEdgeTypeValue,
    variableTypes,
  } = props

  const [isMarked] = useDiffMark()
  const renderFieldLabel = useCallback((label) =>
{label}
, [])

  switch (edge.edgeType?.type) {
    case EdgeKind.switchDefault: {
      return (
        <BaseModalContent
          edge={edge}
          edgeErrors={edgeErrors}
          readOnly={readOnly}
          isMarked={isMarked}
          changeEdgeTypeValue={changeEdgeTypeValue}
        />
      )
    }
    case EdgeKind.switchNext: {
      const expressionObj = {
        expression: edge.edgeType.condition.expression,
        language: edge.edgeType.condition.language,
      }
      return (
        <BaseModalContent
          edge={edge}
          edgeErrors={edgeErrors}
          readOnly={readOnly}
          isMarked={isMarked}
          changeEdgeTypeValue={changeEdgeTypeValue}
        >
          <EditableEditor
            variableTypes={variableTypes}
            fieldLabel={"Expression"}
            renderFieldLabel={renderFieldLabel}
            expressionObj={expressionObj}
            readOnly={readOnly}
            isMarked={isMarked("edgeType.condition.expression")}
            showValidation={showValidation}
            showSwitch={showSwitch}
            onValueChange={changeEdgeTypeCondition}
          />
        </BaseModalContent>
      )
    }
    default:
      return null
  }
}


text:
package com.lohasle.baseframe.s4m3.pojo;

/**
 * 拖动配置条目pojo
 * @author ganmin
 * @value dragId 拖动条目ID
 * @value configId 配置ID
 * @value type 操作类型 (add-添加;del-删除)
 * @value staffId 操作工号
 */
public class DragConfig {
	private String dragId;
	private String configId;
	private String type;
	private String staffId;

	/** default constructor */
	public DragConfig() {
	}

	/** full constructor */
	public DragConfig(String dragId, String configId, String type,
			String staffId) {
		super();
		this.dragId = dragId;
		this.configId = configId;
		this.type = type;
		this.staffId = staffId;
	}

	public String getDragId() {
		return dragId;
	}

	public void setDragId(String dragId) {
		this.dragId = dragId;
	}

	public String getConfigId() {
		return configId;
	}

	public void setConfigId(String configId) {
		this.configId = configId;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getStaffId() {
		return staffId;
	}

	public void setStaffId(String staffId) {
		this.staffId = staffId;
	}
}


text:
from django.apps import AppConfig
from django.contrib.auth import get_user_model
from django.contrib import admin

from models import UserSettingDescriptor
from admin import UserAdmin

class UserSettingsConfig(AppConfig):
    name = "django_dynamic_usersettings"
    setting_attribute_name = "settings"
    insert_inline_editing = True

    def ready(self):
        setattr(
            get_user_model(),
            UserSettingsConfig.setting_attribute_name,
            UserSettingDescriptor(),
        )

        if UserSettingsConfig.insert_inline_editing:
            admin.site.unregister(get_user_model())
            admin.site.register(get_user_model(), UserAdmin)


text:
<?php
    $custom_css = array('forum.scss', 'highlight.css', 'confirm.css');
    $custom_js = array('forum.js', 'highlight.js', 'jquery.confirm.js');
    if (!defined("_SIDEBAR")) define("_SIDEBAR", false);
    if (!defined("PAGE_PUBLIC")) define('PAGE_PUBLIC', true);

    define('TWIG', true);

    require_once('init.php');

    if (isset($_GET['page']) && is_numeric($_GET['page']))
        $page = $_GET['page'];
    else
        $page = 1;

    $forum = $app->forum;

    $breadcrumb = '';
    if (isset($_GET['slug'])) {
        // Get id from slug
        preg_match('/\/([0-9]+)[a-z0-9\s-]+$/s', $_GET['slug'], $matches);
        if ($matches) {
            $id = $matches[1];

            // Section or thread?
            $thread = $forum->isThread($id);
            if ($thread) {
                if (isset($_GET['edit']))
                    include('edit.php');
                else
                    include('view.php');
                die();
            }
        }

        $section = $forum->getSection($_GET['slug']);
        if (!$section) {
            header('Location: /forum');
            die();
        }

        if (!$section->incomplete && isset($_GET['submit'])) {
            if (isset($_POST['title']) && isset($_POST['body'])) {
                $newThreadResult = $forum->newThread($section, $_POST['title'], $_POST['body']);

                if (strpos($newThreadResult, '/') === 0) {
                    header('Location: '. $newThreadResult);
                }
            }
        }

        $app->page->title = 'Forum - ' . $section->title;
    } else {
        $section = null;
        $app->page->title = 'Forum';
    }

    $breadcrumb = $forum->getBreadcrumb($section);

    if (isset($_GET['watching'])) {
        $breadcrumb .= 'Watched threads';
        if (isset($_GET['popular']) || isset($_GET['no-replies'])) {
            $breadcrumb .= ' & ';
        }
    }
    if (isset($_GET['popular'])) {
        $breadcrumb .= 'Most popular threads';
        if (isset($_GET['no-replies'])) {
            $breadcrumb .= ' & ';
        }
    }
    if (isset($_GET['no-replies'])) {
        $breadcrumb .= 'Threads with no replies';
    }
    if (!isset($_GET['no-replies']) && !isset($_GET['popular']) && !isset($_GET['watching'])) {
        $breadcrumb .= 'Latest threads';
    }

    $threads = $forum->getThreads($section, $page, isset($_GET['no-replies']), isset($_GET['popular']), isset($_GET['watching']));

    $threads_count = $threads->count;
    $threads = $threads->threads;

    require_once('header.php');
?>

<?php
        include('elements/sidebar_forum.php');
?>

<?php
    if ($app->user->loggedIn && $app->user->forum_priv > 0 && $section && !$section->incomplete):
        if (isset($newThreadResult)):
?>
     Thread list
<?php
        else:
?>
     New thread
<?php
        endif;
    elseif ($section && $section->incomplete):
?>
     New thread
<?php
    else:
?>
     New thread
<?php
    endif;
?>

Forum

                            <?=$breadcrumb;?>

<?php
    if ($app->user->loggedIn && $app->user->forum_priv < 1) {
        $app->utils->message('You have been banned from posting content in the forum', 'error');
    }
?>
                            <div class='forum-container clearfix <?=isset($newThreadResult)?'new-thread':'';?>'>

<?php
    if (count($threads) && (!$section || !$section->incomplete)):
?>

Thread

Replies

Voices

Latest

<?php
        foreach($threads AS $thread):
?>
                                                <li class='row <?=($app->user->loggedIn)?(!$thread->viewed)?($thread->watching)?'highlight':'new':'':'';?> <?=($thread->closed)?'closed':'';?> <?=($thread->sticky)?'sticky':'';?>'>

                                                        <a class='strong' href="/forum/<?=$thread->slug;?>"><?=$thread->title;?>
<?php
            if (ceil($thread->count/10) > 1) {
                $pagination = new stdClass();
                $pagination->count = ceil($thread->count/10);
                $pagination->root = '/forum/' . $thread->slug . '?page=';
                include('elements/lite_pagination.php');
            }

            $threadBreadcrumb = $forum->getThreadBreadcrumb($section, $thread);
            if ($threadBreadcrumb):
?>

<?=$threadBreadcrumb;?>

<?php
            else:
?>

                                                            <?=$thread->blurb;?>

<?php
            endif;
?>

<?=$thread->count;?>

<?=$thread->voices;?>

                                                        <time itemprop='datePublished' pubdate datetime="<?=date('c', strtotime($thread->latest));?>"><?=$app->utils->timeSince($thread->latest);?></time>

                                                        <a class='strong' href="/user/<?=$thread->latest_author;?>"><?=$thread->latest_author;?>

<?php
        endforeach;
?>

<?php
    elseif ($section->incomplete):
        $app->utils->message('You must complete the relevant level before accessing this section', 'warning');
    else:
        $app->utils->message('No threads found, consider starting your own', 'info');
    endif;

    if ($threads_count > 10) {
        $pagination = new stdClass();
        $pagination->current = $page;
        $pagination->count = ceil($threads_count/10);

        // Build root
        $root = '';
        if (isset($_GET['watching'])) $root = 'watching&';
        if (isset($_GET['popular'])) $root = 'popular&';
        if (isset($_GET['no-replies'])) $root = 'no-replies&';

        $pagination->root = '?'.$root.'page=';
        include('elements/pagination.php');
    }
?>

New post

New post in watched thread

Thread closed

Sticky thread

<?php
    if (isset($newThreadResult)) {
        $app->utils->message($newThreadResult);
    }
?>
                                    <form method="POST" action="?submit">
                                        Title:

                                        <input type="text" id='title' name='title' class='short'/>
    <?php include('elements/wysiwyg.php'); ?>
                                        <input type='submit' class='button' value='Submit'/>
                                    </form>

<?php
   require_once('footer.php');
?>


text:
<?php
/**
 * Edit tag form for inclusion in administration panels.
 *
 * @package WordPress
 * @subpackage Administration
 */

// don't load directly
if ( !defined('ABSPATH') )
	die('-1');

if ( empty($tag_ID) ) { ?>

<?php _e( 'You did not select an item for editing.' ); ?>

<?php
	return;
}

// Back compat hooks
if ( 'category' == $taxonomy ) {
	do_action( 'edit_category_form_pre', $tag );
} elseif ( 'link_category' == $taxonomy ) {
	do_action( 'edit_link_category_form_pre', $tag );
} else {
	do_action( 'edit_tag_form_pre', $tag );
}
do_action( "{$taxonomy}_pre_edit_form", $tag, $taxonomy ); ?>

<?php echo $tax->labels->edit_item; ?>

<form name="edittag" id="edittag" method="post" action="edit-tags.php" class="validate"<?php do_action( $taxonomy . '_term_edit_form_tag' ); ?>>
<input type="hidden" name="action" value="editedtag" />
<input type="hidden" name="tag_ID" value="<?php echo esc_attr($tag->term_id) ?>" />
<input type="hidden" name="taxonomy" value="<?php echo esc_attr($taxonomy) ?>" />
<?php wp_original_referer_field(true, 'previous'); wp_nonce_field('update-tag_' . $tag_ID); ?>

			<?php _ex('Name', 'Taxonomy Name'); ?>
			<input name="name" id="name" type="text" value="<?php if ( isset( $tag->name ) ) echo esc_attr($tag->name); ?>" size="40" aria-required="true" />

<?php _e('The name is how it appears on your site.'); ?>

<?php if ( !global_terms_enabled() ) { ?>

			<?php _ex('Slug', 'Taxonomy Slug'); ?>
			<input name="slug" id="slug" type="text" value="<?php if ( isset( $tag->slug ) ) echo esc_attr(apply_filters('editable_slug', $tag->slug)); ?>" size="40" />

<?php _e('The “slug” is the URL-friendly version of the name. It is usually all lowercase and contains only letters, numbers, and hyphens.'); ?>

<?php } ?>
<?php if ( is_taxonomy_hierarchical($taxonomy) ) : ?>

			<?php _ex('Parent', 'Taxonomy Parent'); ?>

				<?php wp_dropdown_categories(array('hide_empty' => 0, 'hide_if_empty' => false, 'name' => 'parent', 'orderby' => 'name', 'taxonomy' => $taxonomy, 'selected' => $tag->parent, 'exclude_tree' => $tag->term_id, 'hierarchical' => true, 'show_option_none' => __('None'))); ?>
				<?php if ( 'category' == $taxonomy ) : ?>

<?php _e('Categories, unlike tags, can have a hierarchy. You might have a Jazz category, and under that have children categories for Bebop and Big Band. Totally optional.'); ?>

				<?php endif; ?>

<?php endif; // is_taxonomy_hierarchical() ?>

			<?php _ex('Description', 'Taxonomy Description'); ?>
			<textarea name="description" id="description" rows="5" cols="50" class="large-text"><?php echo $tag->description; // textarea_escaped ?></textarea>

			<?php _e('The description is not prominent by default; however, some themes may show it.'); ?>

		<?php
		// Back compat hooks
		if ( 'category' == $taxonomy )
			do_action('edit_category_form_fields', $tag);
		elseif ( 'link_category' == $taxonomy )
			do_action('edit_link_category_form_fields', $tag);
		else
			do_action('edit_tag_form_fields', $tag);

		do_action($taxonomy . '_edit_form_fields', $tag, $taxonomy);
		?>

<?php
// Back compat hooks
if ( 'category' == $taxonomy )
	do_action('edit_category_form', $tag);
elseif ( 'link_category' == $taxonomy )
	do_action('edit_link_category_form', $tag);
else
	do_action('edit_tag_form', $tag);

do_action($taxonomy . '_edit_form', $tag, $taxonomy);

submit_button( __('Update') );
?>
</form>


text:
#region License

#endregion License

using Microsoft.Xna.Framework;
using System;

namespace Microsoft.Xna.Framework.Graphics.PackedVector
{
    public struct Rgba32 : IPackedVector<uint>, IPackedVector, IEquatable<Rgba32>
    {
        public Rgba32(Vector4 vector){ throw new NotImplementedException(); }

        public Rgba32(float x, float y, float z, float w){ throw new NotImplementedException(); }

        public static bool operator !=(Rgba32 a, Rgba32 b){ throw new NotImplementedException(); }

        public static bool operator ==(Rgba32 a, Rgba32 b){ throw new NotImplementedException(); }

        [CLSCompliant(false)]
        public uint PackedValue { get{ throw new NotImplementedException(); } set{ throw new NotImplementedException(); } }

        public override bool Equals(object obj){ throw new NotImplementedException(); }

        public bool Equals(Rgba32 other){ throw new NotImplementedException(); }

        public override int GetHashCode(){ throw new NotImplementedException(); }

        public override string ToString(){ throw new NotImplementedException(); }

        public Vector4 ToVector4(){ throw new NotImplementedException(); }

        void IPackedVector.PackFromVector4(Vector4 vector)
        {
            throw new Exception("The method or operation is not implemented.");
        }
    }
}


text:
@import XCTest;
@import BlocksKit;

@interface NSMutableSetBlocksKitTest : XCTestCase

@end

@implementation NSMutableSetBlocksKitTest {
	NSMutableSet *_subject;
	NSInteger _total;
}

- (void)setUp {
	_subject = [NSMutableSet setWithArray:@[ @"1", @"22", @"333"]];;
	_total = 0;
}

- (void)testSelect {
	BOOL(^validationBlock)(id) = ^(NSString *obj) {
		_total += [obj length];
		BOOL match = ([obj intValue] < 300) ? YES : NO;
		return match;
	};
	[_subject bk_performSelect:validationBlock];
	XCTAssertEqual(_total,(NSInteger)6,@"total length of \"122333\" is %ld", (long)_total);
	NSMutableSet *target = [NSMutableSet setWithArray:@[ @"1", @"22" ]];
	XCTAssertEqualObjects(_subject,target,@"selected items are %@",_subject);
}

- (void)testSelectedNone {
	BOOL(^validationBlock)(id) = ^(NSString *obj) {
		_total += [obj length];
		BOOL match = ([obj intValue] > 400) ? YES : NO;
		return match;
	};
	[_subject bk_performSelect:validationBlock];
	XCTAssertEqual(_total,(NSInteger)6,@"total length of \"122333\" is %ld", (long)_total);
	XCTAssertEqual(_subject.count,(NSUInteger)0,@"no item is selected");
}

- (void)testReject {
	BOOL(^validationBlock)(id) = ^(NSString *obj) {
		_total += [obj length];
		BOOL match = ([obj intValue] > 300) ? YES : NO;
		return match;
	};
	[_subject bk_performReject:validationBlock];
	XCTAssertEqual(_total,(NSInteger)6,@"total length of \"122333\" is %ld", (long)_total);
	NSMutableSet *target = [NSMutableSet setWithArray:@[ @"1", @"22" ]];
	XCTAssertEqualObjects(_subject,target,@"not rejected items are %@",_subject);
}

- (void)testRejectedAll {
	BOOL(^validationBlock)(id) = ^(NSString *obj) {
		_total += [obj length];
		BOOL match = ([obj intValue] < 400) ? YES : NO;
		return match;
	};
	[_subject bk_performReject:validationBlock];
	XCTAssertEqual(_total,(NSInteger)6,@"total length of \"122333\" is %ld", (long)_total);
	XCTAssertEqual(_subject.count,(NSUInteger)0,@"all items are rejected");
}

- (void)testMap {
	id(^transformBlock)(id) = ^(NSString *obj) {
		_total += [obj length];
		return [obj substringToIndex:1];
	};
	[_subject bk_performMap:transformBlock];
	XCTAssertEqual(_total,(NSInteger)6,@"total length of \"122333\" is %ld", (long)_total);
	NSMutableSet *target = [NSMutableSet setWithArray:@[ @"1", @"2", @"3" ]];
	XCTAssertEqualObjects(_subject,target,@"transformed items are %@",_subject);
}

@end


text:
namespace {

typedef testing::Test HttpVaryDataTest;

struct TestTransaction {
  net::HttpRequestInfo request;
  scoped_refptr<net::HttpResponseHeaders> response;

  void Init(const std::string& request_headers,
            const std::string& response_headers) {
    std::string temp(response_headers);
    std::replace(temp.begin(), temp.end(), '\n', '\0');
    response = new net::HttpResponseHeaders(temp);

    request.extra_headers.Clear();
    request.extra_headers.AddHeadersFromString(request_headers);
  }
};

}  // namespace

TEST(HttpVaryDataTest, IsInvalid) {
  // All of these responses should result in an invalid vary data object.
  const char* kTestResponses[] = {
    "HTTP/1.1 200 OK\n\n",
    "HTTP/1.1 200 OK\nVary: *\n\n",
    "HTTP/1.1 200 OK\nVary: cookie, *, bar\n\n",
    "HTTP/1.1 200 OK\nVary: cookie\nFoo: 1\nVary: *\n\n",
  };

  for (size_t i = 0; i < arraysize(kTestResponses); ++i) {
    TestTransaction t;
    t.Init(std::string(), kTestResponses[i]);

    net::HttpVaryData v;
    EXPECT_FALSE(v.is_valid());
    EXPECT_FALSE(v.Init(t.request, *t.response));
    EXPECT_FALSE(v.is_valid());
  }
}

TEST(HttpVaryDataTest, MultipleInit) {
  net::HttpVaryData v;

  // Init to something valid.
  TestTransaction t1;
  t1.Init("Foo: 1\r\nbar: 23", "HTTP/1.1 200 OK\nVary: foo, bar\n\n");
  EXPECT_TRUE(v.Init(t1.request, *t1.response));
  EXPECT_TRUE(v.is_valid());

  // Now overwrite by initializing to something invalid.
  TestTransaction t2;
  t2.Init("Foo: 1\r\nbar: 23", "HTTP/1.1 200 OK\nVary: *\n\n");
  EXPECT_FALSE(v.Init(t2.request, *t2.response));
  EXPECT_FALSE(v.is_valid());
}

TEST(HttpVaryDataTest, DoesVary) {
  TestTransaction a;
  a.Init("Foo: 1", "HTTP/1.1 200 OK\nVary: foo\n\n");

  TestTransaction b;
  b.Init("Foo: 2", "HTTP/1.1 200 OK\nVary: foo\n\n");

  net::HttpVaryData v;
  EXPECT_TRUE(v.Init(a.request, *a.response));

  EXPECT_FALSE(v.MatchesRequest(b.request, *b.response));
}

TEST(HttpVaryDataTest, DoesVary2) {
  TestTransaction a;
  a.Init("Foo: 1\r\nbar: 23", "HTTP/1.1 200 OK\nVary: foo, bar\n\n");

  TestTransaction b;
  b.Init("Foo: 12\r\nbar: 3", "HTTP/1.1 200 OK\nVary: foo, bar\n\n");

  net::HttpVaryData v;
  EXPECT_TRUE(v.Init(a.request, *a.response));

  EXPECT_FALSE(v.MatchesRequest(b.request, *b.response));
}

TEST(HttpVaryDataTest, DoesntVary) {
  TestTransaction a;
  a.Init("Foo: 1", "HTTP/1.1 200 OK\nVary: foo\n\n");

  TestTransaction b;
  b.Init("Foo: 1", "HTTP/1.1 200 OK\nVary: foo\n\n");

  net::HttpVaryData v;
  EXPECT_TRUE(v.Init(a.request, *a.response));

  EXPECT_TRUE(v.MatchesRequest(b.request, *b.response));
}

TEST(HttpVaryDataTest, DoesntVary2) {
  TestTransaction a;
  a.Init("Foo: 1\r\nbAr: 2", "HTTP/1.1 200 OK\nVary: foo, bar\n\n");

  TestTransaction b;
  b.Init("Foo: 1\r\nbaR: 2", "HTTP/1.1 200 OK\nVary: foo\nVary: bar\n\n");

  net::HttpVaryData v;
  EXPECT_TRUE(v.Init(a.request, *a.response));

  EXPECT_TRUE(v.MatchesRequest(b.request, *b.response));
}

TEST(HttpVaryDataTest, ImplicitCookieForRedirect) {
  TestTransaction a;
  a.Init("Cookie: 1", "HTTP/1.1 301 Moved\nLocation: x\n\n");

  TestTransaction b;
  b.Init("Cookie: 2", "HTTP/1.1 301 Moved\nLocation: x\n\n");

  net::HttpVaryData v;
  EXPECT_TRUE(v.Init(a.request, *a.response));

  EXPECT_FALSE(v.MatchesRequest(b.request, *b.response));
}

TEST(HttpVaryDataTest, ImplicitCookieForRedirect2) {
  // This should be no different than the test above

  TestTransaction a;
  a.Init("Cookie: 1", "HTTP/1.1 301 Moved\nLocation: x\nVary: coOkie\n\n");

  TestTransaction b;
  b.Init("Cookie: 2", "HTTP/1.1 301 Moved\nLocation: x\nVary: cooKie\n\n");

  net::HttpVaryData v;
  EXPECT_TRUE(v.Init(a.request, *a.response));

  EXPECT_FALSE(v.MatchesRequest(b.request, *b.response));
}


text:
random
======

Random test stuff


text:
/**
 * @file calibration_routines.h
 * Calibration routines definitions.
 *
 * @author Lorenz Meier <lm@inf.ethz.ch>
 */

/**
 * Least-squares fit of a sphere to a set of points.
 *
 * Fits a sphere to a set of points on the sphere surface.
 *
 * @param x point coordinates on the X axis
 * @param y point coordinates on the Y axis
 * @param z point coordinates on the Z axis
 * @param size number of points
 * @param max_iterations abort if maximum number of iterations have been reached. If unsure, set to 100.
 * @param delta abort if error is below delta. If unsure, set to 0 to run max_iterations times.
 * @param sphere_x coordinate of the sphere center on the X axis
 * @param sphere_y coordinate of the sphere center on the Y axis
 * @param sphere_z coordinate of the sphere center on the Z axis
 * @param sphere_radius sphere radius
 *
 * @return 0 on success, 1 on failure
 */
int sphere_fit_least_squares(const float x[], const float y[], const float z[],
			     unsigned int size, unsigned int max_iterations, float delta, float *sphere_x, float *sphere_y, float *sphere_z,
			     float *sphere_radius);


text:
#ifndef GPG_IOS_PLATFORM_CONFIGURATION_H_
#define GPG_IOS_PLATFORM_CONFIGURATION_H_

#ifndef __cplusplus
#error Header file supports C++ only
#endif  // __cplusplus

#include <memory>

#include "gpg/common.h"

#ifdef __OBJC__
#import <UIKit/UIKit.h>
#endif

namespace gpg {

class IosPlatformConfigurationImpl;

/**
 * The platform configuration used when creating an instance of the GameServices
 * class on iOS.
 */
class GPG_EXPORT IosPlatformConfiguration {
 public:
  IosPlatformConfiguration();
  ~IosPlatformConfiguration();

  /**
   * Sets the Client ID, using a value obtained beforehand from the Google Play
   * Developer Console. More information is available at
   * https://developers.google.com/games/services/console/enabling#client_id.
   */
  IosPlatformConfiguration &SetClientID(std::string const &client_id);

#ifdef __OBJC__
  IosPlatformConfiguration &SetOptionalViewControllerForPopups(
      UIViewController *ui_view_controller);
#endif  // __OBJC__

  /**
   * Returns true if all required values were provided to the
   * IosPlatformConfiguration. In this case, the only required value is the
   * Client ID.
   */
  bool Valid() const;

 private:
  IosPlatformConfiguration(IosPlatformConfiguration const &) = delete;
  IosPlatformConfiguration &operator=(
      IosPlatformConfiguration const &) = delete;

  friend class GameServicesImpl;
  std::unique_ptr<IosPlatformConfigurationImpl> impl_;
};

}  // namespace gpg

#endif  // GPG_IOS_PLATFORM_CONFIGURATION_H_


text:
Amata mea Argeia - gratiam magnam tibi ago!
Patientia tua in studiis meis computatoriis auxilium meum maximum!

## JavaScript & Node.js

https://nodejs.org/api/child_process.html

https://google.github.io/styleguide/jsguide.html

https://stackoverflow.com/questions/13230370/nodejs-child-process-write-to-stdin-from-an-already-initialised-process
https://stackoverflow.com/questions/14989081/node-js-to-get-determine-os-version
https://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string
https://stackoverflow.com/questions/15515549/node-js-writing-a-function-to-return-spawn-stdout-as-a-string
https://stackoverflow.com/questions/9781214/parse-output-of-spawned-node-js-child-process-line-by-line
https://stackoverflow.com/questions/3133243/how-do-i-get-the-path-to-the-current-script-with-node-js

http://www.tutorialspoint.com/jquery/ajax-serialize.htm

https://gist.github.com/leommoore/4484379 (Node - Processes)
https://www.hacksparrow.com/how-to-write-node-js-modules.html
http://justbuildsomething.com/node-js-best-practices/

## PHP

http://php.net/manual/en/function.phpversion.php


text:
#include <aws/sagemaker-runtime/model/InvokeEndpointResult.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

#include <utility>

using namespace Aws::SageMakerRuntime::Model;
using namespace Aws::Utils::Stream;
using namespace Aws::Utils;
using namespace Aws;

InvokeEndpointResult::InvokeEndpointResult()
{
}

InvokeEndpointResult::InvokeEndpointResult(InvokeEndpointResult&& toMove) :
    m_body(std::move(toMove.m_body)),
    m_contentType(std::move(toMove.m_contentType)),
    m_invokedProductionVariant(std::move(toMove.m_invokedProductionVariant)),
    m_customAttributes(std::move(toMove.m_customAttributes))
{
}

InvokeEndpointResult& InvokeEndpointResult::operator=(InvokeEndpointResult&& toMove)
{
   if(this == &toMove)
   {
      return *this;
   }

   m_body = std::move(toMove.m_body);
   m_contentType = std::move(toMove.m_contentType);
   m_invokedProductionVariant = std::move(toMove.m_invokedProductionVariant);
   m_customAttributes = std::move(toMove.m_customAttributes);

   return *this;
}

InvokeEndpointResult::InvokeEndpointResult(Aws::AmazonWebServiceResult<ResponseStream>&& result)
{
  *this = std::move(result);
}

InvokeEndpointResult& InvokeEndpointResult::operator =(Aws::AmazonWebServiceResult<ResponseStream>&& result)
{
  m_body = result.TakeOwnershipOfPayload();

  const auto& headers = result.GetHeaderValueCollection();
  const auto& contentTypeIter = headers.find("content-type");
  if(contentTypeIter != headers.end())
  {
    m_contentType = contentTypeIter->second;
  }

  const auto& invokedProductionVariantIter = headers.find("x-amzn-invoked-production-variant");
  if(invokedProductionVariantIter != headers.end())
  {
    m_invokedProductionVariant = invokedProductionVariantIter->second;
  }

  const auto& customAttributesIter = headers.find("x-amzn-sagemaker-custom-attributes");
  if(customAttributesIter != headers.end())
  {
    m_customAttributes = customAttributesIter->second;
  }

   return *this;
}


text:
/*
 * For a detailed explanation regarding each configuration property, visit:
 * https://jestjs.io/docs/configuration
 */

module.exports = {
  clearMocks: true,
  coverageProvider: 'v8',
  setupFiles: [
    './testlib/jest.setup.js',
    './testlib/jest.setup.external.js',
    './testlib/jest.setup.fetch.js',
    './testlib/jest.setup.digdag-ui.js'
  ],
  testEnvironment: 'jsdom'
}


text:
'use strict';

const Homey = require('homey');
const MeshDevice = require('../MeshDevice.js');

// TODO battery node online event

/**
 * @extends MeshDevice
 */
class ZigBeeDevice extends MeshDevice {

	/*
	 *	Homey methods
	 */

	/**
	 * @private
	 */
	onInit() {
		super.onInit('zigbee');

		this._capabilities = {};
		this._settings = {};
		this._reportListeners = {};
		this._attrReportListeners = {};
		this._pollIntervals = {};
		this._pollIntervalsKeys = {};
		this._bindRequests = [];
		this._configureReportRequests = [];

		this.once('__meshInit', () => {
			this.log('ZigBeeDevice has been inited');
			this.onMeshInit && this.onMeshInit();
			this._initReportListener();
		});
	}

	/*
	 * Private methods
	 */

	/**
	 * @private
	 */
	_initReportListener() {

		// Start listening for incoming reports
		this.node.on('report', report => {
			if (report && report.event === 'report') {
				const clusterEndpointId = `${Number(report.endpoint) - 1}_${report.cluster}`;
				if ((this._attrReportListeners[clusterEndpointId] && this._attrReportListeners[clusterEndpointId][report.attr])) {
					this._attrReportListeners[clusterEndpointId][report.attr](report.value);
				}
			}
		});
	}

	/**
	 * @private
	 */
	_registerCapabilityGet(capabilityId, clusterId) {

		const capabilityGetObj = this._getCapabilityObj('get', capabilityId, clusterId);
		if (capabilityGetObj instanceof Error) return capabilityGetObj;

		// get initial value on start if null, unless it's an offline battery device and the getOnOnline flag is also set
		if (capabilityGetObj.opts.getOnStart
			&& this.getCapabilityValue(capabilityId) === null
			&& !(this.node.battery && this.node.online === false && capabilityGetObj.opts.getOnOnline === true)) {
			this._getCapabilityValue(capabilityId, clusterId);
		}

		if (capabilityGetObj.opts.getOnOnline) {
			this.node.on('online', () => {
				this._debug(`Node online, getting clusterId '${clusterId}' for capabilityId '${capabilityId}'`);
				this._getCapabilityValue(capabilityId, clusterId);
			});
		}

		if (capabilityGetObj.opts.pollInterval) {

			let pollInterval;

			if (typeof capabilityGetObj.opts.pollInterval === 'number') {
				pollInterval = capabilityGetObj.opts.pollInterval;
			}

			if (typeof capabilityGetObj.opts.pollInterval === 'string') {
				pollInterval = this.getSetting(capabilityGetObj.opts.pollInterval);
				this._pollIntervalsKeys[capabilityGetObj.opts.pollInterval] = {
					capabilityId,
					clusterId,
				};
			}

			this._setPollInterval(capabilityId, clusterId, pollInterval);
		}
	}

	/**
	 * @private
	 */
	_setPollInterval(capabilityId, clusterId, pollInterval) {

		this._pollIntervals[capabilityId] = this._pollIntervals[capabilityId] || {};

		if (this._pollIntervals[capabilityId][clusterId]) {
			clearInterval(this._pollIntervals[capabilityId][clusterId]);
		}

		if (pollInterval < 1) return;

		this._pollIntervals[capabilityId][clusterId] = setInterval(() => {
			this._debug(`Polling clusterId '${clusterId}' for capabilityId '${capabilityId}'`);
			this._getCapabilityValue(capabilityId, clusterId);
		}, pollInterval);

	}

	/**
	 * @private
	 */
	async _getCapabilityValue(capabilityId, clusterId) {

		const capabilityGetObj = this._getCapabilityObj('get', capabilityId, clusterId);
		if (capabilityGetObj instanceof Error) return capabilityGetObj;

		let parsedPayload = {};

		if (typeof capabilityGetObj.parser === 'function') {
			parsedPayload = await capabilityGetObj.parser.call(this);
			if (parsedPayload instanceof Error) return this.error(parsedPayload);
		}

		try {
			const cluster = capabilityGetObj.node.endpoints[capabilityGetObj.endpoint].clusters[capabilityGetObj.clusterId];
			return cluster.read(capabilityGetObj.commandId)
				.then(res => this._onReport(capabilityId, capabilityGetObj.clusterId, res))
				.catch(err => this.error(err));
		} catch (err) {
			return this.error(err);
		}
	}

	/**
	 * @private
	 */
	_registerCapabilitySet(capabilityId, clusterId) {

		const capabilitySetObj = this._getCapabilityObj('set', capabilityId, clusterId);
		if (capabilitySetObj instanceof Error) return capabilitySetObj;

		this.registerCapabilityListener(capabilityId, async (value, opts) => {
			return await this._registerCapabilityListenerHandler(capabilitySetObj, capabilityId, value, opts);
		});
	}

	/**
	 * @param capabilitiesOpts
	 * @private
	 */
	_registerCapabilitiesSet(capabilitiesOpts, fn) {

		// Register multiple capabilities with a debouncer
		this.registerMultipleCapabilityListener(capabilitiesOpts.map(x => x.capability), async (valueObj, optsObj) => {

			// Let the app try to handle the debounced capabilities updates
			const result = await fn(valueObj, optsObj);

			// If it did not handle it for some reason, return to the defaults
			if (!result || result instanceof Error) {

				// Loop all changed capabilities
				for (const capabilityId of Object.keys(valueObj)) {
					const capabilityObj = capabilitiesOpts.find(x => x.capability = capabilityId);
					const clusterId = capabilityObj.cluster;
					const value = valueObj[capabilityId];
					const opts = optsObj[capabilityId];

					// Try and get capability set object
					const capabilitySetObj = this._getCapabilityObj('set', capabilityId, clusterId);
					if (capabilitySetObj instanceof Error) {
						this.error(`capabilitySetObj ${capabilityId} ${clusterId} is error`, capabilitySetObj);
						break;
					}

					// Try to handle executing the capability change event
					try {
						await this._registerCapabilityListenerHandler(capabilitySetObj, capabilityId, value, opts);
					} catch (err) {
						this.error('_registerCapabilityListenerHandler() -> failed', err);
						break;
					}
				}
			}
		}, 500);
	}

	/**
	 * @param capabilitySetObj
	 * @param capabilityId
	 * @param value
	 * @param opts
	 * @returns {Promise.<*>}
	 * @private
	 */
	async _registerCapabilityListenerHandler(capabilitySetObj, capabilityId, value, opts) {
		this.log(`set ${capabilityId} -> ${value}`);
		if (typeof capabilitySetObj.parser !== 'function') return Promise.reject(new Error('parser_is_not_a_function'));

		let commandId = capabilitySetObj.commandId;
		if (typeof capabilitySetObj.commandId === 'function') commandId = capabilitySetObj.commandId(value, opts);
		let parsedPayload = await capabilitySetObj.parser.call(this, value, opts);
		if (parsedPayload instanceof Error) return Promise.reject(parsedPayload);
		if (parsedPayload === null) return Promise.resolve();

		try {
			const cluster = capabilitySetObj.node.endpoints[capabilitySetObj.endpoint].clusters[capabilitySetObj.clusterId];
			return cluster.do(commandId, parsedPayload)
				.catch(err => {
					this.error(`Error: could not perform ${commandId} on ${capabilitySetObj.clusterId}`, err);
					throw err;
				});
		} catch (err) {
			return Promise.reject(err);
		}
	}

	/**
	 * @param capabilityId
	 * @param clusterId
	 * @param userOpts
	 * @private
	 */
	_mergeSystemAndUserOpts(capabilityId, clusterId, userOpts) {

		// Merge systemOpts & userOpts
		let systemOpts = {};
		try {
			systemOpts = Homey.util.recursiveDeepCopy(require(`./system/capabilities/${capabilityId}/${clusterId}.js`));

			// Bind correct scope
			for (let i in systemOpts) {
				if (systemOpts.hasOwnProperty(i) && typeof systemOpts[i] === 'function') {
					systemOpts[i] = systemOpts[i].bind(this);
				}
			}
		} catch (err) {
			if (err.code !== 'MODULE_NOT_FOUND' || err.message.indexOf(`/system/capabilities/${capabilityId}/${clusterId}.js`) < 0) {
				process.nextTick(() => {
					throw err;
				});
			}
		}

		// Insert default endpoint zero
		if (userOpts && !userOpts.hasOwnProperty('endpoint')) userOpts.endpoint = this.getClusterEndpoint(clusterId);
		else if (typeof userOpts === 'undefined') userOpts = { endpoint: this.getClusterEndpoint(clusterId) };

		this._capabilities[capabilityId][clusterId] = Object.assign(
			systemOpts || {},
			userOpts || {}
		);
	}

	/**
	 * @private
	 */
	async _onReport(capabilityId, clusterId, payload) {

		const capabilityReportObj = this._getCapabilityObj('report', capabilityId, clusterId);
		if (capabilityReportObj instanceof Error) return capabilityReportObj;

		if (typeof capabilityReportObj.parser !== 'function') return;

		const parsedPayload = await capabilityReportObj.parser.call(this, payload);
		if (parsedPayload instanceof Error) return;
		if (parsedPayload === null) return;

		this.setCapabilityValue(capabilityId, parsedPayload);

		return parsedPayload;
	}

	/**
	 * @private
	 */
	_getCapabilityObj(commandType, capabilityId, clusterId) {

		const capability = this._capabilities[capabilityId];
		let cluster;

		if (typeof clusterId !== 'undefined') {
			cluster = capability[clusterId];
		} else {
			return new Error('missing_zigbee_cluster_id');
		}

		if (typeof cluster === 'undefined') return new Error('missing_zigbee_capability');
		const commandId = cluster[commandType];
		const parser = cluster[`${commandType}Parser`] || null;
		const opts = cluster[`${commandType}Opts`] || {};
		const node = this.node;

		if (typeof commandId === 'string' || typeof commandId === 'function') {
			return {
				clusterId,
				commandId,
				endpoint: cluster.endpoint,
				parser,
				opts,
				node,
			};
		}

		return new Error(`capability_${commandType}_is_not_a_function_or_string`);
	}

	/*
	 * Public methods
	 */

	/**
	 * Register a Homey Capability with a Cluster.
	 * @param {string} capabilityId - The Homey capability id (e.g. `onoff`)
	 * @param {string} clusterId - The Cluster id (e.g. `genBasic`)
	 * @param {Object} [userOpts] - The object with options for this capability/cluster combination. These will extend system options, if available (`/lib/zigbee/system/`)
	 * @param {string} [userOpts.get] - The command to get a value (e.g. `onOff`)
	 * @param {string} [userOpts.getParser] - The function that is called when a GET request is made. Should return an Object.
	 * @param {Object} [userOpts.getOpts
	 * @param {Boolean} [userOpts.getOpts.getOnStart] - Get the value on App start
	 * @param {Boolean} [userOpts.getOpts.getOnOnline] - Get the value when the device is marked as online
	 * @param {Number|string} [userOpts.getOpts.pollInterval] - Interval (in ms) to poll with a GET request. When provided a string, the device's setting with the string as ID will be used (e.g. `poll_interval`)
	 * @param {string} [userOpts.set] - The command to set a value (e.g. `on`)
	 * @param {Function} [userOpts.setParser] - The function that is called when a SET request is made. Should return an Object.
	 * @param {*} [userOpts.setParser.value] - The value of the Homey capability
	 * @param {Object} [userOpts.setParser.opts] - Options for the capability command
	 * @param {string} [userOpts.report] - The command to report a value (e.g. `onOff`)
	 * @param {Function} [userOpts.reportParser] - The function that is called when a REPORT request is made. Should return an Object.
	 * @param {Object} [userOpts.reportParser.report] - The report object
	 * @param {number} [userOpts.endpoint=0] - An index to identify the endpoint to use for this capability
	 */
	registerCapability(capabilityId, clusterId, userOpts) {

		// Register the ZigBee capability listener
		this._capabilities[capabilityId] = this._capabilities[capabilityId] || {};
		this._capabilities[capabilityId][clusterId] = this._capabilities[capabilityId][clusterId] || {};

		// Merge systemOpts & userOpts
		this._mergeSystemAndUserOpts(capabilityId, clusterId, userOpts);

		// Register get/set
		this._registerCapabilitySet(capabilityId, clusterId);
		this._registerCapabilityGet(capabilityId, clusterId);
	}

	/**
	 * Register multiple Homey Capabilities with a Cluster. When a capability is changed, the event will be debounced
	 * with the other capabilities in the capabilitiesOpts array.
	 * @param {Object[]} capabilitiesOpts
	 * @param {string} capabilitiesOpts.capability
	 * @param {string} capabilitiesOpts.cluster
	 * @param {Object} [capabilitiesOpts.opts] - The object with options for this capability/cluster combination. These will extend system options, if available (`/lib/zigbee/system/`)
	 * @param {string} [capabilitiesOpts.opts.get] - The command to get a value (e.g. `onOff`)
	 * @param {string} [capabilitiesOpts.opts.getParser] - The function that is called when a GET request is made. Should return an Object.
	 * @param {Object} [capabilitiesOpts.opts.getOpts]
	 * @param {Boolean} [capabilitiesOpts.opts.getOpts.getOnStart] - Get the value on App start
	 * @param {Boolean} [capabilitiesOpts.opts.getOpts.getOnOnline] - Get the value when the device is marked as online
	 * @param {Number|string} [capabilitiesOpts.opts.getOpts.pollInterval] - Interval to poll with a GET request. When provided a string, the device's setting with the string as ID will be used (e.g. `poll_interval`)
	 * @param {string} [capabilitiesOpts.opts.set] - The command to set a value (e.g. `on`)
	 * @param {Function} [capabilitiesOpts.opts.setParser] - The function that is called when a SET request is made. Should return an Object.
	 * @param {*} [capabilitiesOpts.opts.setParser.value] - The value of the Homey capability
	 * @param {Object} [capabilitiesOpts.opts.setParser.opts] - Options for the capability command
	 * @param {string} [capabilitiesOpts.opts.report] - The command to report a value (e.g. `onOff`)
	 * @param {Function} [capabilitiesOpts.opts.reportParser] - The function that is called when a REPORT request is made. Should return an Object.
	 * @param {Object} [capabilitiesOpts.opts.reportParser.report] - The report object
	 * @param {number} [capabilitiesOpts.opts.endpoint=0] - An index to identify the endpoint to use for this capability
	 * @param {function} fn
	 */
	registerMultipleCapabilities(capabilitiesOpts = [], fn) {

		// Loop all provided capabilities
		capabilitiesOpts.forEach(capabilityObj => {
			const capabilityId = capabilityObj.capability;
			const clusterId = capabilityObj.cluster;
			let userOpts = capabilityObj.opts || {};

			// Register the ZigBee capability listener
			this._capabilities[capabilityId] = this._capabilities[capabilityId] || {};
			this._capabilities[capabilityId][clusterId] = this._capabilities[capabilityId][clusterId] || {};

			// Override default system opts with user opts
			this._mergeSystemAndUserOpts(capabilityId, clusterId, userOpts);

			// Register capability getter
			this._registerCapabilityGet(capabilityId, clusterId);

			// Register debounced capabilities set
			this._registerCapabilitiesSet(capabilitiesOpts, fn);
		});
	}

	/**
	 * Method that searches for the first occurrence of a clusterName in a device's endpoints and returns the endpoint id.
	 * @param {string} clusterName
	 */
	getClusterEndpoint(clusterName) {
		if (typeof clusterName !== 'string') return new Error('invalid_cluster_name');
		if (!this.node || !this.node.hasOwnProperty('endpoints')) return new Error('node_not_initialized');

		// Loop all endpoints for first occurence of clusterName
		for (const endpoint of this.node.endpoints) {
			if (endpoint.clusters.hasOwnProperty(clusterName)) {
				return this.node.endpoints.indexOf(endpoint);
			}
		}

		// Not found, probably something wrong, return default
		return 0;
	}

	/**
	 * Register a endpoint command listener, which is called when a command has been received from the provided endpoint
	 * cluster combination.
	 * @param {string} clusterId - The ID of the cluster (e.g. `genBasic`)
	 * @param {string} commandId - The ID of the Command (e.g. `onOff`)
	 * @param {Function} triggerFn
	 * @param {Object} triggerFn.rawReport - The raw report
	 * @param {Object} triggerFn.parsedReport - The parsed report (parsed by the first available `reportParser` method)
	 * @param {number} [endpointId=0] - The endpoint index (e.g. 0)
	 */
	registerReportListener(clusterId, commandId, triggerFn, endpointId = 0) {
		const reportId = `${endpointId}_${clusterId}_${commandId}`;
		const clusterEndpointId = `${endpointId}_${clusterId}`;

		const alreadyBound = this.getStoreValue(reportId);
		const alreadyRegistered = Object.keys(this._reportListeners[clusterEndpointId] || {}).length > 0;

		this._reportListeners[clusterEndpointId] = this._reportListeners[clusterEndpointId] || {};
		this._reportListeners[clusterEndpointId][commandId] = triggerFn;

		// Make sure to only bind each cluster once
		if (alreadyBound || alreadyRegistered) {
			this.log('registerReportListener() -> already bound cluster', clusterId, commandId, endpointId);

			// Lister on this cluster for specific commands
			this.node.on('command', command => {
				const endpointId = command.endpoint;
				if (!endpointId) this.error('command missing endpoint id', command);
				const commandClusterEndpointId = `${endpointId}_${clusterId}`;
				if (this._reportListeners[commandClusterEndpointId]
					&& this._reportListeners[commandClusterEndpointId][command.attr]
					&& commandId === command.attr) {
					this._reportListeners[commandClusterEndpointId][command.attr](command.value);
				}
			});
		} else {

			this.log('registerReportListener() -> bind cluster', clusterId, commandId, endpointId);

			// Add to queue
			this._bindRequests.push({ endpointId, clusterId, commandId, reportId });

			// If not already binding start the binding process
			if (!this.bindingInProcess) this._bindCluster();
		}
	}

	/**
	 * Start binding process, if there are more than one bindings required perform them one after another.
	 * @returns {Promise}
	 * @private
	 */
	async _bindCluster() {

		// Mark binding true
		this.bindingInProcess = true;

		// Get next bind obj in queue
		const bindObj = this._bindRequests.shift();
		try {
			await this.node.endpoints[bindObj.endpointId].clusters[bindObj.clusterId].bind();
		} catch (err) {
			this.error(`registerReportListener() -> error could not bind ${bindObj.clusterId} cluster on endpoint ${bindObj.endpointId}`, err);
			if (this._bindRequests.length > 0) return this._bindCluster();
			else this.bindingInProcess = false;
			return;
		}

		this.log(`registerReportListener() -> bind ${bindObj.clusterId} on endpoint ${bindObj.endpointId} successful`);

		// Mark this cluster as bound for this device to prevent rebinding
		this.setStoreValue(bindObj.reportId, true);

		// Bind listener for incoming commands
		this.node.on('command', command => {
			const endpointId = command.endpoint;
			if (!endpointId) this.error('command missing endpoint id', command);
			const commandClusterEndpointId = `${endpointId}_${bindObj.clusterId}`;
			if (this._reportListeners[commandClusterEndpointId]
				&& this._reportListeners[commandClusterEndpointId][command.attr]
				&& bindObj.commandId === command.attr) {
				this._reportListeners[commandClusterEndpointId][command.attr](command.value);
			}
		});

		// If queue not empty continue, else mark as done
		if (this._bindRequests.length > 0) return this._bindCluster();
		else this.bindingInProcess = false;
	}

	/**
	 * Register an attribute report listener, which is called when a report has been received for the provided endpoint
	 * cluster and attribute combination.
	 * @param {string} clusterId - The ID of the cluster (e.g. `genBasic`)
	 * @param {string} attrId - The ID of the attribute (e.g. `onOff`)
	 * @param {number} minInt - The minimal reporting interval in seconds (e.g. 10 (seconds))
	 * @param {number} maxInt - The maximal reporting interval in seconds (e.g. 300 (seconds))
	 * @param {number} repChange - Reportable change; the attribute should report its value when the value is changed more than this setting, for attributes of analog data type this argument is mandatory.
	 * @param {Function} triggerFn - Function that will be called when attribute report data is received
	 * @param {number} [endpointId=0] - The endpoint index (e.g. 0)
	 * @returns {Promise} Resolves if configuration succeeded
	 */
	async registerAttrReportListener(clusterId, attrId, minInt, maxInt, repChange = null, triggerFn, endpointId = 0) {
		const reportId = `attrReport_${endpointId}_${clusterId}_${attrId}`;
		const clusterEndpointId = `${endpointId}_${clusterId}`;

		// minInt must be greater than or equal to 1
		if (minInt < 1) throw new Error('invalid_min_int_report_value');

		// maxInt must be larger than 60 and larger than minInt or 0
		if (maxInt !== 0 && (maxInt < 60 || maxInt < minInt)) {
			throw new Error('invalid_max_int_report_value');
		}

		// Check if endpoint cluster combi exists
		if (!this.node.endpoints[endpointId] || !this.node.endpoints[endpointId].clusters[clusterId]) {
			throw new Error('invalid_endpoint_cluster_combination');
		}

		// Check if already configured
		const alreadyConfigured = this.getStoreValue(reportId);
		this._attrReportListeners[clusterEndpointId] = this._attrReportListeners[clusterEndpointId] || {};

		// Store callback
		this._attrReportListeners[clusterEndpointId][attrId] = triggerFn;

		// Make sure to configure just once
		if (alreadyConfigured &&
			alreadyConfigured.minInt === minInt &&
			alreadyConfigured.maxInt === maxInt &&
			alreadyConfigured.repChange === repChange) {
			this.log(`registerAttrReportListener() -> already configured attr reporting ${reportId}`);
			return true;
		} else {

			// If was registered before unregister it first
			this.unsetStoreValue(reportId);

			return new Promise((resolve, reject) => {
				// Add to queue
				this._configureReportRequests.push({
					reportId,
					endpointId,
					clusterId,
					attrId,
					minInt,
					maxInt,
					repChange,
					promise: { resolve, reject }
				});

				// If not already binding start the binding process
				if (!this.configureReportInProcess) this._configureReport();
			})
		}
	}

	/**
	 * Start report configuring process, if there are more than one configurations required perform them one after another.
	 * @returns {Promise}
	 * @private
	 */
	async _configureReport() {

		// Mark configuring true
		this.configureReportInProcess = true;

		// Get next configure obj in queue
		const configureReportObj = this._configureReportRequests.shift();

		try {
			await this.node.endpoints[configureReportObj.endpointId].clusters[configureReportObj.clusterId]
				.report(configureReportObj.attrId, configureReportObj.minInt, configureReportObj.maxInt, configureReportObj.repChange);

			this.log(`registerAttrReportListener() -> configured attr reporting ${configureReportObj.reportId}`);

			// Store configuration succeeded
			this.setStoreValue(configureReportObj.reportId, {
				minInt: configureReportObj.minInt,
				maxInt: configureReportObj.maxInt,
				repChange: configureReportObj.repChange,
			});

			if (configureReportObj.promise) configureReportObj.promise.resolve();
		} catch (err) {
			this.error(`registerAttrReportListener() -> error could not configure ${configureReportObj.reportId}`, err);
			if (configureReportObj.promise) configureReportObj.promise.reject(err);
		}

		// If queue not empty continue, else mark as done
		if (this._configureReportRequests.length > 0) return this._configureReport();
		else this.configureReportInProcess = false;
	}

	/**
	 * Print the current Node information with Endpoints and Clusters
	 */
	printNode() {
		this.log('------------------------------------------');

		// log the entire Node
		this.log('Node:', this.getData().token);
		this.log('- Battery:', this.node.battery);

		Object.keys(this.node.endpoints).forEach(endpointsId => {
			this.log('- Endpoints:', endpointsId);
			this.log('-- Clusters:');
			Object.keys(this.node.endpoints[endpointsId].clusters).forEach(key => {
				this.log('---', key);
				if (typeof this.node.endpoints[endpointsId].clusters[key].attrs !== 'undefined') {
					Object.keys(this.node.endpoints[endpointsId].clusters[key].attrs).forEach(attrKey => {
						this.log('----', attrKey, ':', this.node.endpoints[endpointsId].clusters[key].attrs[attrKey]);
					});
				}
			});
		});

		this.log('------------------------------------------');
	}
}

module.exports = ZigBeeDevice;


text:
var debug = require('debug');
var getModuleDebugId = require('./functions').getModuleDebugId;
var filter;

var cache = {};

var api = module.exports = {
  configure: function(opts) {
    if ( !opts ) opts = {};
    if ( opts.filter && typeof opts.filter === 'function' ) {
      filter = opts.filter;
      cache = {};
    }
  },
  get: function( filename, submoduleName ) {
    return debug(api.getModuleDebugName(filename, submoduleName));
  },
  getModuleDebugName: function ( filename, submoduleName ) {
    var name = cache[filename];
    if ( !name ) {
      name = getModuleDebugId(filename, {platform: process.platform, filter:filter});
      cache[filename] = name;
    }
    if ( submoduleName ) {
      return name + ':' + submoduleName;
    } else {
      return name;
    }
  }
};


text:
from sqlalchemy import Column, String, Integer, ForeignKey, Unicode
from sqlalchemy.orm import relationship, backref
from sqlalchemy.ext.declarative import declarative_base
from hashlib import sha1
import os

Base = declarative_base()

class FileHashes(Base):
    __tablename__ = 'file_hashes'

    id = Column(Integer, autoincrement=True, primary_key=True)
    hash_id = Column(Unicode(40))
    files = relationship("CheckedFile", backref="hash")

    def __init__(self, hash_id):
        self.hash_id = hash_id

    def __repr__(self):
        return '<FileHash: {}>'.format(self.hash_id)

class CheckedFile(Base):
    __tablename__ = 'checked_file'

    id = Column(Integer, autoincrement=True, primary_key=True)
    # Access the the file_hashes using 'hash'
    hash_id = Column(Integer, ForeignKey('file_hashes.id'))
    path = Column(Unicode(255))

    def __init__(self, filepath):
        # Double check we're receiving a valid file path
        if os.path.exists(filepath):
            self.path = filepath

    def __repr__(self):
        return '<File: {}>'.format(self.path)

    def calculate_hash(self, filepath):
        # From Ben's comments on StackOverflow (http://stackoverflow.com/a/19711609/2809087)
        sha = sha1()
        try:
            with open(filepath, 'rb') as f:
                while True:
                    block = f.read(2**10)
                    if not block:
                        break
                    sha.update(block)
            return sha.hexdigest()
        except IOError:
            # unable to read file
            return False

    def get_hash(self):
        return self.calculate_hash(self.path)


text:
jquery.smartmessage.js is a JQuery-Plugin in order to display Smart Messages (message overlays) dependent on display triggers like for example Exit-Intent. A message may be designed and positioned as wished via different options. The message box has a close button which can be deactivated by the options.

=======

## Integration

The following files have to be integrated. (jquery.etracker-smartmessage.js only has to be integrated if the etracker Targeting API and the etracker counting are needed for the Smart Message)

```html
...
<script src="jquery.min.js"></script>
<script src="jquery.smartmessage.min.js"></script>
</head>
```

## API reference

### Options
The options are transferred during initialisation via object.

* id : string (default smartMessage)
  * Defines the DOM Id of the Smart Message. If the container does not exist in the DOM, it will be created and added to the body.
* name : string (default Smart Message)
  * Defines the message name and is used for the tracking.
* debugMode : boolean (default false)
  * If the debugMode is activated, the output of the JS console contains some log information regarding the processing/initialisation of the message. The recurrence time of the message is ignored and the message will always be delivered as soon as the targeting and/or the trigger apply.
* recurrenceTime : integer (default 14)
  * Indicates how many days a message will not be displayed for a second time once it has been triggered.
* dataEventBinding : object
  * The event binding allows to link events to HTML elements in the message.
 The following code is added to an existing HTML tag for the binding.
 data-smartmessage="test" Via an entry in the object an interaction like "click" can be attached to a function behind "test".
 Default Binding
* tracking : function (default: function(eventType, configuration){})
  * When a View, Click or Close event is executed the defined tracking function that tracks the message interactions is also called. If the jquery.etracker-smartmessage.js is used it is not necessary to define this function.

```js
var options = {
    'id': 'example', // DOM ID
    'name' : "test message",
    'debugMode' : true,
    'recurrenceTime' : 5,
    'tracking' : function(event, config) {
      // google event tracking
      _gaq.push(['_trackEvent', 'Smart Messaging', config.name, eventName]);
    },
    'dataEventBinding' : {
      'click' : {
        'test' : function() {
          alert('test click');
        }
      }
    },
    'message' : {
      'content' : '<a href="#" data-smartmessage="test">Test Klick</a>'
    }
}
var smartMessage = $.smartMessage(options);
```

#### Trigger

* type : string (default exitIntent)
  * exitIntent The message is displayed as soon as the visitor leaves the visible page area with the mouse.
  * attentionGrabber The message is displayed when the visitor does not interact with the page and runs into the timeout (default: 10 s).
  * greeter The message is displayed after expiration of a timeout (default: 10 s).
  * none The message is displayed directly. (Interesting for Targeting-Only)
* timeout : integer (default 10)
  * Indicates how many seconds it lasts until Greeter and Attention Grabber are triggered.

```js
var testMessage = $.smartMessage({
  'message' : {
    'content' : 'Welcome to my page.'
  },
  'trigger' : {
    'type' : 'greeter',
    'options' : {
      'timeout' : 10,
    }
  }
});
```

#### Targeting

* config : object (default {})
  * Key/Value object to be used in the Targeting Collector. (jquery.etracker-smartmessage.js needs this option)
* collector : function (default function(callback){ callback({}); })
  * The defined function calls a callback function and transfers the data (got from APIs for example) that shall be available to be used in the condition.
* condition : function (default null)
  * When this function is defined targeting for the message is active. The function parameters come from the data of the collector function.

```js
var testMessage = $.smartMessage({
  'message' : {
    'content' : 'It is not raining at your place.'
  },
  'targeting' : {
    'condition' : function(targetingData) {
        return targetingData.weather != 'Rain';
    },
    'collector' : function(callback) {
      $.getJSON("http://www.telize.com/geoip", function(ipdata) {
        $.getJSON("http://api.openweathermap.org/data/2.5/weather?q="+ipdata.city+','+ipdata.country_code,
        function(weatherData) {
          callback({'weather' : weatherData.weather[0].main});
        });
      });
    }
  }
});
```
#### Message

* content : string (default '')
 * Serves to define the HTML content alternatively unless a div object has already been created in the DOM with the ID from the options.
* styles : object
  * Key/Value object with css style properties for the message.
  Default:
  ```css
  'z-index'           : '90001',
  'display'           : 'none',
  'width'             : '500px',
  'background-color'  : '#fff',
  'padding'         : '10px',
  'border'        : '2px solid #ff710d',
  'border-radius'     : '8px',
  'position'        : 'absolute'
  ```
* autoPosition : boolean (default true)
  * Positions the message container via an internal subsidiary function always in the middle of the page. Even during scrolling/resizing the message remains in the centre.
* animation : function (default function(obj){$(obj).show();})
  * With the help of the called function you can determine how the message will slide in. The function is called for the overlay and the message container.
* closeButton : boolean (default true)
  * Positions a Close button (pure css) in the upper right corner of the message. When the Close button is clicked the message is closed and the tracking for "close" is called. Via the css class .jquerySmartMessage .closeButton the button can be edited/exchanged.
* overlay : boolean (default true)
  * Shows an overlay when the message is displayed. (Page is blacked out)
* overlayOpacity : string (default 0.5)
  * Opacity of the overlays.
* iframe : object
  * If the src option is defined within the object of iframe an iframe with the indicated page is loaded in the message. The iframe size can be edited via the options width and height.
  ```js
  'iframe' : {
    'src' : 'http://github.com',
    'width' : '500px',
    'height' : '400px'
  }
  ```

```js
var testMessage = $.smartMessage({
  'debugMode' : true,
  'message' : {
    'content' : 'Sliding in Yeahhhh.',
    'overlay' : false,
    'autoPosition' : false,
    'styles' : {
      'top' : '10px',
      'left' : '0px',
      'display' : 'block',
      'border-radius' : '0px 5px 5px 0px',
      'border-left' : 'none',
      'margin-left' : '-550px'
    },
    'closeButton' : false,
    'animation': function(obj) {
      $(obj).animate({"margin-left": '+=550'}, 1000);
    }
  }
});
```

### Methods on the object

* object.getConfiguration()
  * Returns the current configuration.
* object.closeMessage()
  * Closes the message.
* object.showMessage()
  * Shows the message regardless of the trigger/targeting.
* object.trackClick()
  * Counts a click via the defined tracking method.
* object.onShowMessage(callback)
  * The defined callback function is called when the message is shown.
* object.onCloseMessage(callback)
  * The defined callback function is called when the message is closed.
* object.onTargetingData(callback(data))
  * When the targeting data are successfully loaded from the collector the callback function is called with the data as parameters.
* object.onClickMessage(callback)
  * The callback function is called when clicking on an element that is defined with data-smartmessage="trackClick".

## Use with etracker
As soon as jquery.etracker-smartmessage.js is integrated the targeting and tracking for etracker is set up.
```html
...
<script src="jquery.min.js"></script>
<script src="jquery.smartmessage.js"></script>
<script src="jquery.etracker-smartmessage.js"></script>
</head>
```

### Configure the targeting

In order to be able to use the targeting API data from etracker in the Smart Message the config object under targeting needs the correct secure code (account key 2).

```js
// example
...
'targeting' : {
    'config' : {
        'secureCode' : 'FvZgay2SaHf8iVpHdFEyFCUB3NDirFUJnpHCGPWKI0='
    },
    'condition' : function(targetingData) {
        return targetingData.visits > 3;
    }
}
...
```

#### Combine the etracker Targeting API with other APIs

If you want to request data from the Targeting API and other APIs at the same time this can easily be done by a small encapsulation. In the following example the message is shown with at least two visits depending on the weather on the location of the user.

```js
// example
...
'targeting' : {
    'config' : {
        'secureCode' : 'FvZgay2SaHf8iVpHdFEyFCUB3NDirFUJnpHCGPWKI0='
    },
    'condition' : function(targetingData) {
        return targetingData.visits >= 2 && targetingData.weather.main != 'Rain';
    },
    'collector' : function(callback) {
    smartMessage.etrackerCollector(function(data){
      $.getJSON("http://www.telize.com/geoip", function(ipdata) {
        $.getJSON("http://api.openweathermap.org/data/2.5/weather?q="+ipdata.city+','+ipdata.country_code,
        function(weatherData) {
          callback($.extend(data, {'locationCity' : ipdata.city, 'weather' : weatherData.weather[0]}));
        });
      });
    });
    }
}
...
```

### etracker tracking

Tracking of the messages is done automatically. The counting flows into the corresponding etracker reports where it can be evaluated. The option name allows to define the name of the Smart Message so that it can be easily found in the reports.


text:
package com.ctrip.www.android;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class MainActivity extends AppCompatActivity {
    private EditText edit;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edit = (EditText) findViewById(R.id.edit);
        String inputText = load();
        if (!TextUtils.isEmpty(inputText)){
            edit.setText(inputText);
            edit.setSelection(inputText.length());
            Toast.makeText(this, "Restoring successed",Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        String inputText = edit.getText().toString();
        save(inputText);
    }
    public  void save(String inputText){
        FileOutputStream out = null;
        BufferedWriter writer = null;
        try{
            out = openFileOutput("data", Context.MODE_PRIVATE);
            writer = new BufferedWriter(new OutputStreamWriter(out));
            writer.write(inputText);
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try{
                if (writer != null){
                    writer.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
    public  String load(){
        FileInputStream in = null;
        BufferedReader reader = null;
        StringBuffer content = new StringBuffer();
        try {
            in = openFileInput("data");
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null){
                content.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null){
                    reader.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return  content.toString();
    }
}


text:
<?php

namespace Drupal\form_test\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Builds a simple form to test the #group property on #type 'container'.
 */
class FormTestGroupContainerForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'form_test_group_container';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['container'] = [
      '#type' => 'container',
    ];
    $form['meta'] = [
      '#type' => 'details',
      '#title' => 'Group element',
      '#open' => TRUE,
      '#group' => 'container',
    ];
    $form['meta']['element'] = [
      '#type' => 'textfield',
      '#title' => 'Nest in details element',
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
  }

}


text:
import { IFunctionCallMode } from './IFunctionCallMode';
export declare class InvokeFunctionCallMode implements IFunctionCallMode {
}