text:
"""Label map utility functions."""

import logging

import tensorflow as tf
from google.protobuf import text_format
from object_detection.protos import string_int_label_map_pb2

def create_category_index(categories):
  """Creates dictionary of COCO compatible categories keyed by category id.

  Args:
    categories: a list of dicts, each of which has the following keys:
      'id': (required) an integer id uniquely identifying this category.
      'name': (required) string representing category name
        e.g., 'cat', 'dog', 'pizza'.

  Returns:
    category_index: a dict containing the same entries as categories, but keyed
      by the 'id' field of each category.
  """
  category_index = {}
  for cat in categories:
    category_index[cat['id']] = cat
  return category_index

def convert_label_map_to_categories(label_map,
                                    max_num_classes,
                                    use_display_name=True):
  """Loads label map proto and returns categories list compatible with eval.

  This function loads a label map and returns a list of dicts, each of which
  has the following keys:
    'id': (required) an integer id uniquely identifying this category.
    'name': (required) string representing category name
      e.g., 'cat', 'dog', 'pizza'.
  We only allow class into the list if its id-label_id_offset is
  between 0 (inclusive) and max_num_classes (exclusive).
  If there are several items mapping to the same id in the label map,
  we will only keep the first one in the categories list.

  Args:
    label_map: a StringIntLabelMapProto or None.  If None, a default categories
      list is created with max_num_classes categories.
    max_num_classes: maximum number of (consecutive) label indices to include.
    use_display_name: (boolean) choose whether to load 'display_name' field
      as category name.  If False of if the display_name field does not exist,
      uses 'name' field as category names instead.
  Returns:
    categories: a list of dictionaries representing all possible categories.
  """
  categories = []
  list_of_ids_already_added = []
  if not label_map:
    label_id_offset = 1
    for class_id in range(max_num_classes):
      categories.append({
          'id': class_id + label_id_offset,
          'name': 'category_{}'.format(class_id + label_id_offset)
      })
    return categories
  for item in label_map.item:
    if not 0 < item.id <= max_num_classes:
      logging.info('Ignore item %d since it falls outside of requested '
                   'label range.', item.id)
      continue
    if use_display_name and item.HasField('display_name'):
      name = item.display_name
    else:
      name = item.name
    if item.id not in list_of_ids_already_added:
      list_of_ids_already_added.append(item.id)
      categories.append({'id': item.id, 'name': name})
  return categories

# TODO: double check documentaion.
def load_labelmap(path):
  """Loads label map proto.

  Args:
    path: path to StringIntLabelMap proto text file.
  Returns:
    a StringIntLabelMapProto
  """
  with tf.gfile.GFile(path, 'r') as fid:
    label_map_string = fid.read()
    label_map = string_int_label_map_pb2.StringIntLabelMap()
    try:
      text_format.Merge(label_map_string, label_map)
    except text_format.ParseError:
      label_map.ParseFromString(label_map_string)
  return label_map

def get_label_map_dict(label_map_path):
  """Reads a label map and returns a dictionary of label names to id.

  Args:
    label_map_path: path to label_map.

  Returns:
    A dictionary mapping label names to id.
  """
  label_map = load_labelmap(label_map_path)
  label_map_dict = {}
  for item in label_map.item:
    label_map_dict[item.name] = item.id
  return label_map_dict


text:
#pragma once
#include <aws/email/SES_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSStreamFwd.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Xml
{
  class XmlNode;
} // namespace Xml
} // namespace Utils
namespace SES
{
namespace Model
{

  /**
   *
Indicates that email sending is disabled for the configuration set.

   *
You can enable or disable email sending for a configuration set using
   * UpdateConfigurationSetSendingEnabled.

See Also:
   AWS
   * API Reference

   */
  class AWS_SES_API ConfigurationSetSendingPausedException
  {
  public:
    ConfigurationSetSendingPausedException();
    ConfigurationSetSendingPausedException(const Aws::Utils::Xml::XmlNode& xmlNode);
    ConfigurationSetSendingPausedException& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);

    void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const;
    void OutputToStream(Aws::OStream& oStream, const char* location) const;

    /**
     *
The name of the configuration set for which email sending is disabled.

     */
    inline const Aws::String& GetConfigurationSetName() const{ return m_configurationSetName; }

    /**
     *
The name of the configuration set for which email sending is disabled.

     */
    inline bool ConfigurationSetNameHasBeenSet() const { return m_configurationSetNameHasBeenSet; }

    /**
     *
The name of the configuration set for which email sending is disabled.

     */
    inline void SetConfigurationSetName(const Aws::String& value) { m_configurationSetNameHasBeenSet = true; m_configurationSetName = value; }

    /**
     *
The name of the configuration set for which email sending is disabled.

     */
    inline void SetConfigurationSetName(Aws::String&& value) { m_configurationSetNameHasBeenSet = true; m_configurationSetName = std::move(value); }

    /**
     *
The name of the configuration set for which email sending is disabled.

     */
    inline void SetConfigurationSetName(const char* value) { m_configurationSetNameHasBeenSet = true; m_configurationSetName.assign(value); }

    /**
     *
The name of the configuration set for which email sending is disabled.

     */
    inline ConfigurationSetSendingPausedException& WithConfigurationSetName(const Aws::String& value) { SetConfigurationSetName(value); return *this;}

    /**
     *
The name of the configuration set for which email sending is disabled.

     */
    inline ConfigurationSetSendingPausedException& WithConfigurationSetName(Aws::String&& value) { SetConfigurationSetName(std::move(value)); return *this;}

    /**
     *
The name of the configuration set for which email sending is disabled.

     */
    inline ConfigurationSetSendingPausedException& WithConfigurationSetName(const char* value) { SetConfigurationSetName(value); return *this;}

  private:

    Aws::String m_configurationSetName;
    bool m_configurationSetNameHasBeenSet = false;
  };

} // namespace Model
} // namespace SES
} // namespace Aws

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * @package limba.models
 * @author  Ludovic Reenaers
 * @since 23 sept. 2010
 * @link http://code.google.com/p/limba
 */

class ModelDocument extends Model{
	function show(){
		$factory  = new DocumentFactory($this->params,$this->factory);
		return $factory;
	}
	function admin(){
		$factory  = new DocumentFactory($this->params,$this->factory);
		return $factory;
	}
	function edit(){
		FormManager::setUrls($_SERVER['SCRIPT_NAME']."?/document/admin/".$this->params["currentid"]."/".$this->params["title"]."/",$_SERVER['SCRIPT_NAME']."?/document/admin/".$this->params["currentid"]."/".$this->params["title"]."/");
		$factory  = new DocumentFactory($this->params,$this->factory);
		return $factory;
	}
	function add(){
		FormManager::setUrls($_SERVER['SCRIPT_NAME']."?/category/admin/".$this->params["targetcatid"]."/",$_SERVER['SCRIPT_NAME']."?/category/admin/".$this->params["targetcatid"]."/");
		$factory  = new DocumentFactory($this->params,$this->factory);
		return $factory;

	}

	function insert(){
		$DAO = $this->factory->getDocumentDAO();
		$typeDocDAO = $this->factory->getTypeDocumentDAO();
		$propDAO = $this->factory->getPropertyDAO();
		$catDAO =  $this->factory->getCategoryDAO();
		$langDAO = $this->factory->getLangueDAO();
		$docInfoDAO = $this->factory->getDocumentInfoDAO();
		$valDAO = $this->factory->getPropertyValueDAO();
		$Cat = $catDAO->getById((int)$_POST['targetcatid']);
		$Document = new Document(0);
		$Document->setOwnerId((int)$_SESSION['USER_BEAN']->getId());
		$Document->setGroupId($Cat->getGroupId());
		$Document->setPermission($Cat->getPermission());
		$Document->setParentCategoryId((int)$_POST['targetcatid']);
		$typeDoc = $typeDocDAO->getById((int)$_POST['typedocid']);
		$Document->setTypeDocument($typeDoc);
		$infos = array();
		$values = array();
		foreach($_POST as $key=>$val){
			$tab = explode("_",$key);
			if (isset($tab[2])){
				$Langue = $langDAO->getByIso($tab[2]);
				if($tab[0] == "{meta}"){

					$Info = $Document->getInfo($Langue);
					if(is_null($Info)){
						$Info = new DocumentInfo(0);
						$Info->setDocumentId($Document->getId());
						$Info->setLangue($Langue);
					}
					$meth = "set".ucfirst($tab[1]);
					$Info->$meth($val);
					$Document->secureAddInfo($Info);
				}else{
					$Val = $Document->convertPostToPropertyValue($tab,$Langue,$val);
					if(!is_null($Val)){
						FormManager::validateProperty((int)$tab[1],$val);
						array_push($values,$Val);
					}
				}
			}
		}
		$Document->setValues($values);
		$Document = $DAO->add($Document);
		return "";
	}

	function update(){
		$docid = $_POST["currentid"];
		$DAO = $this->factory->getDocumentDAO();
		$langDAO = $this->factory->getLangueDAO();
		$Document = $DAO->getById((int)$docid);
		foreach($_POST as $key=>$val){
			$tab = explode("_",$key);
			if(count($tab)>1){
				if($tab[0] == "{meta}"){
					$Document->setMeta($tab[1],$tab[2],$val);
				}else{
					if($tab[1]=='{ins}'){
						$tmptab = array();
						$cp=0;
						$Langue = $langDAO->getByIso($tab[3]);
						foreach($tab as $k=>$v){
							if($k<>1){
								$tmptab[$cp] = $v;
								$cp++;
							}
						}
						$Val = $Document->convertPostToPropertyValue($tmptab,$Langue,$val);
						if(!is_null($Val)){
							FormManager::validateProperty((int)$tab[2],$val);
							$Document->addValue($Val);
						}
					}else{
						$valueid = (int)$tab[1];
						if ($tab[0] == "{str}"){
							$value = $val;
						}elseif ($tab[0] == "{dfr}"){
							$value = array();
							array_push($value, $val, $_POST["{dto}_".$valueid]);
						}elseif ($tab[0] == "{xpe}"){
							$value = isset($_POST["{chk}_".$valueid]);
						}
						FormManager::validateProperty($valueid,$val);
						$Document->setValue($valueid,$value);
					}
				}
			}
		}
		$DAO->update($Document);

		return "";
	}
}
?>


text:
package kotlin.coroutines;

// This is a stub for the Kotlin Continuation interface.
public interface Continuation<T> { }


text:
package com.facebook.buck.io.file;

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;

import com.facebook.buck.core.filesystems.BuckFileSystem;
import com.facebook.buck.testutil.BuckFSProviderDeleteError;
import com.facebook.buck.testutil.TemporaryPaths;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableList;
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import org.hamcrest.Matchers;
import org.junit.Rule;
import org.junit.Test;

public class MostFilesTest {

  @Rule public TemporaryPaths tmp = new TemporaryPaths();

  @Test
  public void testDeleteRecursively() throws IOException {
    tmp.newFile(".dotfile");
    tmp.newFile("somefile");
    tmp.newFolder("foo");
    tmp.newFile("foo/bar");
    tmp.newFolder("foo/baz");
    tmp.newFile("foo/baz/biz");
    assertEquals("There should be files to delete.", 3, tmp.getRoot().toFile().listFiles().length);
    MostFiles.deleteRecursively(tmp.getRoot());
    assertNull(tmp.getRoot().toFile().listFiles());
  }

  @Test
  public void deleteRecursivelyIfExistsShouldNotFailOnNonExistentDir() throws IOException {
    FileSystem vfs = Jimfs.newFileSystem(Configuration.unix());
    Path fakeTmpDir = vfs.getPath("/tmp/fake-tmp-dir");
    MostFiles.deleteRecursivelyIfExists(fakeTmpDir.resolve("nonexistent"));
  }

  @Test
  public void deleteRecursivelyNonExistentDeleteContentsIgnoreNoSuchFile() throws IOException {
    FileSystem vfs = Jimfs.newFileSystem(Configuration.unix());
    Path fakeTmpDir = vfs.getPath("/tmp/fake-tmp-dir");
    MostFiles.deleteRecursivelyWithOptions(
        fakeTmpDir.resolve("nonexistent"),
        EnumSet.of(
            MostFiles.DeleteRecursivelyOptions.DELETE_CONTENTS_ONLY,
            MostFiles.DeleteRecursivelyOptions.IGNORE_NO_SUCH_FILE_EXCEPTION));
  }

  @Test(expected = IOException.class)
  public void deleteRecursivelyIfExistsShouldFailOnFileIfDeletingOnlyContents() throws IOException {
    FileSystem vfs = Jimfs.newFileSystem(Configuration.unix());
    Path fakeTmpDir = vfs.getPath("/tmp/fake-tmp-dir");
    Path fileToDelete = fakeTmpDir.resolve("delete-me");
    Files.createDirectories(fakeTmpDir);
    MostFiles.writeLinesToFile(ImmutableList.of(""), fileToDelete);

    MostFiles.deleteRecursivelyWithOptions(
        fileToDelete, EnumSet.of(MostFiles.DeleteRecursivelyOptions.DELETE_CONTENTS_ONLY));
  }

  @Test
  public void deleteRecursivelyIfExistsShouldNotFailOnFile() throws IOException {
    FileSystem vfs = Jimfs.newFileSystem(Configuration.unix());
    Path fakeTmpDir = vfs.getPath("/tmp/fake-tmp-dir");
    Path fileToDelete = fakeTmpDir.resolve("delete-me");
    Files.createDirectories(fakeTmpDir);
    MostFiles.writeLinesToFile(ImmutableList.of(""), fileToDelete);

    MostFiles.deleteRecursivelyWithOptions(
        fileToDelete, EnumSet.noneOf(MostFiles.DeleteRecursivelyOptions.class));
    assertThat(Files.exists(fileToDelete), is(false));
  }

  @Test
  public void deleteRecursivelyIfExistsDeletesDirectory() throws IOException {
    FileSystem vfs = Jimfs.newFileSystem(Configuration.unix());
    Path fakeTmpDir = vfs.getPath("/tmp/fake-tmp-dir");
    Path dirToDelete = fakeTmpDir.resolve("delete-me");
    Path childDir = dirToDelete.resolve("child-dir");
    Files.createDirectories(childDir);
    MostFiles.deleteRecursivelyIfExists(dirToDelete);
    assertThat(Files.exists(dirToDelete), is(false));
  }

  @Test
  public void deleteRecursivelyIfExistsWithUndeletableFile() throws IOException {
    FileSystem vfs = Jimfs.newFileSystem(Configuration.unix());
    BuckFSProviderDeleteError bfsProvider = new BuckFSProviderDeleteError(vfs);
    BuckFileSystem bfs = new BuckFileSystem(bfsProvider, "/");
    Path fakeTmpDir = bfs.getPath("/tmp/fake-tmp-dir");
    Path dirToDelete = fakeTmpDir.resolve("delete-me");
    Path childDir = dirToDelete.resolve("child-dir");
    Files.createDirectories(childDir);
    Path readOnlyFile = dirToDelete.resolve("roFile");
    Files.createFile(readOnlyFile);
    Path deletableFile = childDir.resolve("deletableFile");
    Files.createFile(deletableFile);
    bfsProvider.setFileToErrorOnDeletion(readOnlyFile);

    MostFiles.deleteRecursivelyIfExists(dirToDelete);
    assertThat(Files.exists(childDir), is(false));
    assertThat(Files.exists(dirToDelete), is(true));
    assertThat(Files.exists(readOnlyFile), is(true));
  }

  @Test
  public void deleteRecursivelyIfExistsWithUndeletableDirectory() throws IOException {
    FileSystem vfs = Jimfs.newFileSystem(Configuration.unix());
    BuckFSProviderDeleteError bfsProvider = new BuckFSProviderDeleteError(vfs);
    BuckFileSystem bfs = new BuckFileSystem(bfsProvider, "/");
    Path fakeTmpDir = bfs.getPath("/tmp/fake-tmp-dir");
    Path dirToDelete = fakeTmpDir.resolve("delete-me");
    Path childDir = dirToDelete.resolve("child-dir");
    Files.createDirectories(childDir);
    Path readOnlyDir = dirToDelete.resolve("roDir");
    Files.createDirectories(readOnlyDir);
    bfsProvider.setFileToErrorOnDeletion(readOnlyDir);
    Path fileInReadOnlyDir = readOnlyDir.resolve("deletableFile");
    Files.createFile(fileInReadOnlyDir);

    MostFiles.deleteRecursivelyIfExists(dirToDelete);
    assertThat(Files.exists(childDir), is(false));
    assertThat(Files.exists(fileInReadOnlyDir), is(false));
    assertThat(Files.exists(dirToDelete), is(true));
    assertThat(Files.exists(readOnlyDir), is(true));
  }

  @Test
  public void deleteRecursivelyContentsOnlyLeavesParentDirectory() throws IOException {
    FileSystem vfs = Jimfs.newFileSystem(Configuration.unix());
    Path fakeTmpDir = vfs.getPath("/tmp/fake-tmp-dir");
    Path dirToDelete = fakeTmpDir.resolve("delete-me");
    Path childDir = dirToDelete.resolve("child-dir");
    Files.createDirectories(childDir);
    MostFiles.deleteRecursivelyWithOptions(
        dirToDelete, EnumSet.of(MostFiles.DeleteRecursivelyOptions.DELETE_CONTENTS_ONLY));
    assertThat(Files.exists(dirToDelete), is(true));
    assertThat(Files.exists(childDir), is(false));
  }

  @Test
  public void testWriteLinesToFile() throws IOException {
    Path outputFile = tmp.newFile("output.txt");
    ImmutableList<String> lines =
        ImmutableList.of("The", "quick brown fox", "jumps over", "the lazy dog.");
    MostFiles.writeLinesToFile(lines, outputFile);

    List<String> observedLines = Files.readAllLines(outputFile, Charsets.UTF_8);
    assertEquals(lines, observedLines);
  }

  @Test
  public void testSortFilesByAccessTime() throws IOException {
    Path dir = tmp.newFolder();
    Path fileW = dir.resolve("w");
    Path fileX = dir.resolve("x");
    Path fileY = dir.resolve("y");
    Path fileZ = dir.resolve("z");

    Files.write(fileW, "w".getBytes(UTF_8));
    Files.write(fileX, "x".getBytes(UTF_8));
    Files.write(fileY, "y".getBytes(UTF_8));
    Files.write(fileZ, "z".getBytes(UTF_8));

    Files.setAttribute(fileW, "lastAccessTime", FileTime.fromMillis(9000));
    Files.setAttribute(fileX, "lastAccessTime", FileTime.fromMillis(0));
    Files.setAttribute(fileY, "lastAccessTime", FileTime.fromMillis(1000));
    Files.setAttribute(fileZ, "lastAccessTime", FileTime.fromMillis(2000));

    File[] files = dir.toFile().listFiles();
    MostFiles.sortFilesByAccessTime(files);
    assertEquals(
        "Files short be sorted from most recently accessed to least recently accessed.",
        ImmutableList.of(fileW.toFile(), fileZ.toFile(), fileY.toFile(), fileX.toFile()),
        Arrays.asList(files));
  }

  @Test
  public void testMakeExecutable() throws IOException {
    Path file = tmp.newFile();

    // If the file system does not support the executable permission, skip the test
    assumeTrue(file.toFile().setExecutable(false));
    assertFalse("File should not be executable", file.toFile().canExecute());
    MostFiles.makeExecutable(file);
    assertTrue("File should be executable", file.toFile().canExecute());

    assumeTrue(file.toFile().setExecutable(true));
    assertTrue("File should be executable", Files.isExecutable(file));
    MostFiles.makeExecutable(file);
    assertTrue("File should be executable", Files.isExecutable(file));
  }

  @Test
  public void testMakeExecutableOnPosix() throws IOException {
    assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix"));

    Path file = tmp.newFile();

    Files.setPosixFilePermissions(file, PosixFilePermissions.fromString("r--------"));
    MostFiles.makeExecutable(file);
    assertEquals(
        "Owner's execute permission should have been set",
        "r-x------",
        PosixFilePermissions.toString(Files.getPosixFilePermissions(file)));

    Files.setPosixFilePermissions(file, PosixFilePermissions.fromString("---r-----"));
    MostFiles.makeExecutable(file);
    assertEquals(
        "Group's execute permission should have been set",
        "---r-x---",
        PosixFilePermissions.toString(Files.getPosixFilePermissions(file)));

    Files.setPosixFilePermissions(file, PosixFilePermissions.fromString("------r--"));
    MostFiles.makeExecutable(file);
    assertEquals(
        "Others' execute permission should have been set",
        "------r-x",
        PosixFilePermissions.toString(Files.getPosixFilePermissions(file)));

    Files.setPosixFilePermissions(file, PosixFilePermissions.fromString("r--r--r--"));
    MostFiles.makeExecutable(file);
    assertEquals(
        "All execute permissions should have been set",
        "r-xr-xr-x",
        PosixFilePermissions.toString(Files.getPosixFilePermissions(file)));

    Files.setPosixFilePermissions(file, PosixFilePermissions.fromString("r-xrw-rwx"));
    MostFiles.makeExecutable(file);
    assertEquals(
        "Only group's execute permission should have been set",
        "r-xrwxrwx",
        PosixFilePermissions.toString(Files.getPosixFilePermissions(file)));

    Files.setPosixFilePermissions(file, PosixFilePermissions.fromString("-w---x-wx"));
    MostFiles.makeExecutable(file);
    assertEquals(
        "No permissions should have been changed",
        "-w---x-wx",
        PosixFilePermissions.toString(Files.getPosixFilePermissions(file)));

    Files.setPosixFilePermissions(file, PosixFilePermissions.fromString("---------"));
    MostFiles.makeExecutable(file);
    assertEquals(
        "No permissions should have been changed",
        "---------",
        PosixFilePermissions.toString(Files.getPosixFilePermissions(file)));

    Files.setPosixFilePermissions(file, PosixFilePermissions.fromString("rwxrwxrwx"));
    MostFiles.makeExecutable(file);
    assertEquals(
        "No permissions should have been changed",
        "rwxrwxrwx",
        PosixFilePermissions.toString(Files.getPosixFilePermissions(file)));
  }

  @Test
  public void concatenatingNoFilesReturnsFalse() throws IOException {
    FileSystem vfs = Jimfs.newFileSystem(Configuration.unix());
    Path outputPath = vfs.getPath("logs.txt");
    boolean collected = MostFiles.concatenateFiles(outputPath, ImmutableList.of());
    assertThat(collected, is(false));
    assertThat(Files.exists(outputPath), is(false));
  }

  @Test
  public void concatenatingTwoEmptyFilesReturnsFalse() throws Exception {
    FileSystem vfs = Jimfs.newFileSystem(Configuration.unix());

    Path fooPath = vfs.getPath("foo.txt");
    Files.write(fooPath, new byte[0]);

    Path barPath = vfs.getPath("bar.txt");
    Files.write(barPath, new byte[0]);

    Path outputPath = vfs.getPath("logs.txt");

    boolean concatenated =
        MostFiles.concatenateFiles(outputPath, ImmutableList.of(fooPath, barPath));
    assertThat(concatenated, is(false));

    assertThat(Files.exists(outputPath), is(false));
  }

  @Test
  public void concatenatingTwoNonEmptyFilesReturnsTrueAndWritesConcatenatedFile() throws Exception {
    FileSystem vfs = Jimfs.newFileSystem(Configuration.unix());

    Path fooPath = vfs.getPath("foo.txt");
    Files.write(fooPath, "hello world\n".getBytes(UTF_8));

    Path barPath = vfs.getPath("bar.txt");
    Files.write(barPath, "goodbye world\n".getBytes(UTF_8));

    Path outputPath = vfs.getPath("logs.txt");

    boolean concatenated =
        MostFiles.concatenateFiles(outputPath, ImmutableList.of(fooPath, barPath));
    assertThat(concatenated, is(true));

    assertThat(
        Files.readAllLines(outputPath, UTF_8),
        Matchers.equalTo(ImmutableList.of("hello world", "goodbye world")));
  }
}


text:
from impact.v1.views.base_list_view import BaseListView
from impact.v1.views.post_mixin import PostMixin
from impact.v1.helpers import CriterionHelper

class CriterionListView(BaseListView,
                        PostMixin):
    view_name = "criterion"
    helper_class = CriterionHelper
    actions = ['GET', 'POST']  # Should get this from PostMixin

    def get(self, request):
        self.validate_id(request, 'judging_round_id')

        return super().get(request)

    def filter(self, qs):
        return self._filter_by_judging_round_id(super().filter(qs))

    def _filter_by_judging_round_id(self, qs):
        return self.filter_by_field("judging_round", qs)


text:
const jsyaml = require("js-yaml");

var express = require('express');
var app = express();
app.post('/store/:id', function(req, res) {
  let data;
  data = jsyaml.load(req.params.data); // NOT OK
  data = jsyaml.loadAll(req.params.data); // NOT OK
  data = jsyaml.safeLoad(req.params.data); // OK
  data = jsyaml.safeLoadAll(req.params.data); // OK
  let unsafeConfig = { schema: jsyaml.DEFAULT_FULL_SCHEMA };
  data = jsyaml.safeLoad(req.params.data, unsafeConfig); // NOT OK
  data = jsyaml.safeLoadAll(req.params.data, unsafeConfig); // NOT OK
});


text:
require "rails_helper"
require "portus/background/security_scanning"

describe ::Portus::Background::SecurityScanning do
  let!(:admin) { create(:admin) }
  let!(:token) { create(:application_token, user: admin) }
  let!(:registry)   { create(:registry, hostname: "my.registry:5000", use_ssl: true) }
  let!(:repository) { create(:repository, name: "repo", namespace: registry.global_namespace) }

  before do
    APP_CONFIG["security"] = {
      "clair"  => {
        "server"  => "http://my.clair:6060",
        "timeout" => 900
      },
      "zypper" => { "server" => "" },
      "dummy"  => { "server" => "" }
    }
  end

  describe "#sleep_value" do
    it "returns always 10" do
      expect(subject.sleep_value).to eq 10
    end
  end

  describe "#work?" do
    it "returns false if security scanning is not enabled" do
      APP_CONFIG["security"]["clair"]["server"] = ""
      expect(subject).not_to be_work
    end

    it "returns true if there are tags to be scanned" do
      create(:tag, name: "tag", repository: repository, digest: "1", author: admin)
      expect(subject).to be_work
    end

    it "returns false if no tags are to be scanned" do
      create(:tag, name: "tag", repository: repository, digest: "1",
             author: admin, scanned: Tag.statuses[:scan_done])
      expect(subject).not_to be_work
    end
  end

  describe "#execute!" do
    let!(:repository2) { create(:repository, name: "node", namespace: registry.global_namespace) }
    let(:proper) do
      {
        clair: [
          {
            "Name"          => "CVE-2016-8859",
            "NamespaceName" => "alpine:v3.4",
            "Link"          => "https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2016-8859",
            "Severity"      => "High",
            "FixedBy"       => "1.1.14-r13"
          },
          {
            "Name"          => "CVE-2016-6301",
            "NamespaceName" => "alpine:v3.4",
            "Link"          => "https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2016-6301",
            "Severity"      => "High",
            "FixedBy"       => "1.24.2-r12"
          }
        ]
      }.freeze
    end

    it "saves all data" do
      # Data from the real image `node:8`
      create(
        :tag,
        name:       "8",
        user_id:    admin.id,
        repository: repository2,
        digest:     "sha256:021c1dba94d141972a13f62194fea0f8ef2a081cd9c03fd3f70a529886a8af11",
        image_id:   "b87c2ad8344dd1c1fdfd09060a99ff5dbac4a1fe1a079ad871dfa228fc628e1c"
      )

      VCR.turn_on!
      VCR.use_cassette("background/node", record: :none) do
        subject.execute!
      end

      vul = Vulnerability.all.order(:id).first
      expect(vul.name).to eq "CVE-2004-0230"
      expect(vul.scanner).to eq "clair"
      expect(vul.severity).to eq "Negligible"
      expect(vul.link).not_to be_empty
      expect(vul.metadata).not_to be_empty
      expect(vul.description).not_to be_empty

      # There's at least one vulnerability with the "FixedBy" attribute.
      expect(Vulnerability.all.any? { |v| v.fixed_by.present? }).to be_truthy
    end

    it "properly saves the vulnerabilities" do
      VCR.turn_on!

      tag = create(:tag, name: "tag", repository: repository, author: admin)

      VCR.use_cassette("background/clair", record: :none) do
        subject.execute!
      end

      tag.reload
      expect(tag.scanned).to eq Tag.statuses[:scan_done]
      expect(tag.vulnerabilities.size).to eq 11
      expect(tag.vulnerabilities.order(:id).first.name).to eq "CVE-2016-6301"
    end

    it "ignores it when a push has happened while fetching vulnerabilities" do
      tag = create(:tag, name: "tag", repository: repository, digest: "1", author: admin)

      allow_any_instance_of(::Portus::Security).to receive(:vulnerabilities) do
        tag.reload
        expect(tag.scanned).to eq Tag.statuses[:scan_working]

        # Faking a push
        Tag.update_all(scanned: Tag.statuses[:scan_none])
        []
      end

      subject.execute!

      tag.reload
      expect(tag.scanned).to eq Tag.statuses[:scan_none]
    end

    it "ignores it when a delete has happened while fetching vulnerabilities" do
      tag = create(:tag, name: "tag", repository: repository, digest: "1", author: admin)

      allow_any_instance_of(::Portus::Security).to receive(:vulnerabilities) do |_, *_args|
        tag.reload
        expect(tag.scanned).to eq Tag.statuses[:scan_working]

        # Faking a delete
        Tag.delete_all
        []
      end

      subject.execute!
      expect { tag.reload }.to raise_error(ActiveRecord::RecordNotFound)
    end

    it "updates all tags with the same digest" do
      tag   = create(:tag, name: "tag", repository: repository, digest: "1", author: admin)
      tag1  = create(:tag, name: "tag1", repository: repository, digest: "1", author: admin)
      count = 0

      allow_any_instance_of(::Portus::Security).to receive(:vulnerabilities) do
        count += 1

        tag.reload
        tag1.reload
        expect(tag.scanned).to eq Tag.statuses[:scan_working]
        expect(tag1.scanned).to eq Tag.statuses[:scan_working]
        proper
      end

      subject.execute!

      expect(count).to eq 1
      expect(Tag.all).to(be_all { |t| t.scanned == Tag.statuses[:scan_done] })
      expect(Tag.all).to(be_all { |t| t.vulnerabilities.size == 2 })
    end

    it "marks tags as not scanned if it does not fetch vulnerabilities properly" do
      create(:tag, name: "tag", repository: repository, digest: "1", author: admin)
      allow_any_instance_of(::Portus::Security).to receive(:vulnerabilities) {}
      allow_any_instance_of(Tag).to receive(:update_vulnerabilities) {}

      subject.execute!

      t = Tag.find_by(name: "tag")
      expect(t.scanned).to eq(Tag.statuses[:scan_none])
    end
  end

  describe "#enabled?" do
    it "returns true when enabled" do
      expect(subject.enabled?).to be_truthy
    end

    it "returns false when not enabled" do
      APP_CONFIG["security"] = {
        "clair"  => { "server" => "" },
        "zypper" => { "server" => "" },
        "dummy"  => { "server" => "" }
      }
      expect(subject.enabled?).to be_falsey
    end
  end

  describe "#disable?" do
    it "always returns false" do
      expect(subject.disable?).to be_falsey
    end
  end

  describe "#to_s" do
    it "works" do
      expect(subject.to_s).to eq "Security scanning"
    end
  end
end


text:
package org.apache.ignite.internal.processors.cache.persistence.diagnostic.pagelocktracker;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import org.apache.ignite.internal.processors.cache.persistence.DataStructure;
import org.apache.ignite.internal.processors.cache.persistence.tree.util.PageLockListener;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.testframework.ListeningTestLogger;
import org.junit.Assert;
import org.junit.Test;

import static org.apache.ignite.internal.processors.cache.persistence.diagnostic.pagelocktracker.LockTrackerFactory.HEAP_LOG;
import static org.apache.ignite.internal.processors.cache.persistence.diagnostic.pagelocktracker.LockTrackerFactory.HEAP_STACK;
import static org.apache.ignite.internal.processors.cache.persistence.diagnostic.pagelocktracker.LockTrackerFactory.OFF_HEAP_LOG;
import static org.apache.ignite.internal.processors.cache.persistence.diagnostic.pagelocktracker.LockTrackerFactory.OFF_HEAP_STACK;

/**
 *
 */
public class PageLockTrackerManagerTest {
    /**
     *
     */
    @Test
    public void testDisableTracking() {
        System.setProperty("IGNITE_PAGE_LOCK_TRACKER_TYPE", String.valueOf(-1));

        try {
            PageLockTrackerManager mgr = new PageLockTrackerManager(new ListeningTestLogger());

            PageLockListener pll = mgr.createPageLockTracker("test");

            Assert.assertNotNull(pll);
            Assert.assertSame(pll, DataStructure.NOOP_LSNR);

        } finally {
            System.clearProperty("IGNITE_PAGE_LOCK_TRACKER_TYPE");
        }

        System.setProperty("IGNITE_PAGE_LOCK_TRACKER_TYPE", String.valueOf(HEAP_LOG));

        try {
            PageLockTrackerManager mgr = new PageLockTrackerManager(new ListeningTestLogger());

            PageLockListener pll = mgr.createPageLockTracker("test");

            Assert.assertNotNull(pll);
            Assert.assertNotSame(pll, DataStructure.NOOP_LSNR);

        } finally {
            System.clearProperty("IGNITE_PAGE_LOCK_TRACKER_TYPE");
        }
    }

    /**
     *
     */
    @Test
    public void testMemoryCalculation() throws Exception {
        int[] trackerTypes = new int[] {HEAP_STACK, HEAP_LOG, OFF_HEAP_STACK, OFF_HEAP_LOG};

        for (int type : trackerTypes)
            testMemoryCalculation0(type);
    }

    /**
     * @param type Tracker type.
     */
    public void testMemoryCalculation0(int type) throws Exception {
        System.out.println(">>> Calculation mempory tracker type:" + type);

        int timeOutWorkerInterval = 10_000;

        System.setProperty("IGNITE_PAGE_LOCK_TRACKER_TYPE", String.valueOf(type));
        System.setProperty("IGNITE_PAGE_LOCK_TRACKER_CHECK_INTERVAL", String.valueOf(timeOutWorkerInterval));

        try {
            PageLockTrackerManager mgr = new PageLockTrackerManager(new ListeningTestLogger());

            mgr.start();

            printOverhead(mgr);

            long heapOverhead0 = mgr.getHeapOverhead();
            long offHeapOverhead0 = mgr.getOffHeapOverhead();
            long totalOverhead0 = mgr.getTotalOverhead();

            Assert.assertTrue(heapOverhead0 > 0);
            Assert.assertTrue(offHeapOverhead0 >= 0);
            Assert.assertEquals(heapOverhead0 + offHeapOverhead0, totalOverhead0);

            PageLockListener pls = mgr.createPageLockTracker("test");

            printOverhead(mgr);

            long heapOverhead1 = mgr.getHeapOverhead();
            long offHeapOverhead1 = mgr.getOffHeapOverhead();
            long totalOverhead1 = mgr.getTotalOverhead();

            Assert.assertTrue(heapOverhead1 > 0);
            Assert.assertTrue(offHeapOverhead1 >= 0);
            Assert.assertTrue(heapOverhead1 > heapOverhead0);
            Assert.assertTrue(offHeapOverhead1 >= offHeapOverhead0);
            Assert.assertEquals(heapOverhead1 + offHeapOverhead1, totalOverhead1);

            int threads = 2_000;

            int cacheId = 1;
            long pageId = 2;
            long page = 3;
            long pageAdder = 4;

            List<Thread> threadsList = new ArrayList<>(threads);

            String threadNamePreffix = "my-thread-";

            CountDownLatch startThreadsLatch = new CountDownLatch(threads);
            CountDownLatch finishThreadsLatch = new CountDownLatch(1);

            for (int i = 0; i < threads; i++) {
                Thread th = new Thread(() -> {
                    startThreadsLatch.countDown();

                    pls.onBeforeReadLock(cacheId, pageId, page);

                    pls.onReadLock(cacheId, pageId, page, pageAdder);

                    pls.onReadUnlock(cacheId, pageId, page, pageAdder);

                    try {
                        finishThreadsLatch.await();
                    }
                    catch (InterruptedException ignored) {
                        // No-op.
                    }
                });

                th.setName(threadNamePreffix + i);

                threadsList.add(th);

                th.start();

                System.out.println(">>> start thread:" + th.getName());
            }

            startThreadsLatch.await();

            printOverhead(mgr);

            long heapOverhead2 = mgr.getHeapOverhead();
            long offHeapOverhead2 = mgr.getOffHeapOverhead();
            long totalOverhead2 = mgr.getTotalOverhead();

            Assert.assertTrue(heapOverhead2 > heapOverhead1);
            Assert.assertTrue(offHeapOverhead2 >= offHeapOverhead1);
            Assert.assertEquals(heapOverhead2 + offHeapOverhead2, totalOverhead2);

            finishThreadsLatch.countDown();

            threadsList.forEach(th -> {
                try {
                    System.out.println(">>> await thread:" + th.getName());

                    th.join();
                }
                catch (InterruptedException ignored) {
                    // No-op.
                }
            });

            // Await cleanup worker interval.
            U.sleep(2 * timeOutWorkerInterval);

            printOverhead(mgr);

            long heapOverhead3 = mgr.getHeapOverhead();
            long offHeapOverhead3 = mgr.getOffHeapOverhead();
            long totalOverhead3 = mgr.getTotalOverhead();

            Assert.assertTrue(heapOverhead3 > 0);
            Assert.assertTrue(offHeapOverhead3 >= 0);
            Assert.assertTrue(heapOverhead3 < heapOverhead2);
            Assert.assertTrue(offHeapOverhead3 <= offHeapOverhead2);
            Assert.assertEquals(heapOverhead3 + offHeapOverhead3, totalOverhead3);

            mgr.stop();
        }
        finally {
            System.clearProperty("IGNITE_PAGE_LOCK_TRACKER_TYPE");
            System.clearProperty("IGNITE_PAGE_LOCK_TRACKER_CHECK_INTERVAL");
        }
    }

    private void printOverhead(PageLockTrackerManager mgr) {
        System.out.println(
            "Head:" + mgr.getHeapOverhead()
                + ", OffHeap:" + mgr.getOffHeapOverhead()
                + ", Total:" + mgr.getTotalOverhead());
    }
}


text:
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">

	<title>Rockety</title>

	<link rel="stylesheet" href="/assets/css/vendor.css">
	<link rel="stylesheet" href="/assets/css/style.css">
</head>
<body>
	<!--
		Delete the line below this comment and rockety.html file
		when you are ready to start working
	-->
	<% include rockety.html %>

	<script src="/assets/js/vendor.js"></script>
	<script src="/assets/js/bundle.js"></script>
	<script src="http://localhost:35729/livereload.js?snipver=1"></script>
</body>
</html>


text:
<?php

use yii\db\Migration;

class m160424_215236_insert_rbac_roles extends Migration
{
    public function up()
    {
      $auth_item_columns =[
        'name','type','description','created_at','updated_at'
      ];

      $auth_item_rows = [
        ['theCreator','1','Site Creator Role',Time(),Time()],
        ['Admin','1','Site Administrator',Time(),Time()],
        ['Manager','1','Manager Level Employees',Time(),Time()],
        ['Employee','1','Employees',Time(),Time()],
        ['/admin/*','2','admin route',Time(),Time()],
        ['/debug/*','2','admin route',Time(),Time()],
      ];
      $this->batchInsert('auth_item',$auth_item_columns, $auth_item_rows);
    }

    public function down()
    {
        $this->execute('DELETE From auth_item WHERE name <> "";');//
    }

    /*
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
    }

    public function safeDown()
    {
    }
    */
}


text:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.Collections;

public class MainMenuHUD : MonoBehaviour
{
    // The title text object of the main menu background
    public Text mainMenuTitle;

    // Loading text object
    public Text loadingText;

    // Fade out image object
    public Image fadeOutImage;

    /*--HUD group titles--*/
    [Header("HUD Group Titles")]
    public string welcomeGroupTitle;
    public string levelSelectGroupTitle;
    public string helpGroupTitle;

    /*--HUD Groups--*/
    [Header("HUD Groups")]
    public GameObject welcomeHUDGroup;
    public GameObject levelSelectHUDGroup;
    public GameObject helpHUDGroup;

    /*--HUD Animation Controllers--*/
    [Header("HUD Animation Controllers")]
    public Animator mainMenuBackgroundAnimationController;
    public Animator fadeOutImageAnimationController;

    /*--HUD Animation Properties--*/
    [Header("HUD Animation Properties")]
    public float hudTransitionDelay = 1.0f;
    public float loadingTransitionDelay = 1.0f;

	// Use this for initialization
	void Start ()
    {
        // Enable the mouse cursor
        Cursor.visible = true;

        // Enable the fade out image
        fadeOutImage.gameObject.SetActive(true);

        // Enable the welcome HUD group
        welcomeHUDGroup.SetActive(true);

        // Disable all other HUD groups
        levelSelectHUDGroup.SetActive(false);
        helpHUDGroup.SetActive(false);

        // Disable the loading text object
        loadingText.gameObject.SetActive(false);
    }

	// Update is called once per frame
	void Update ()
    {

	}

    // Set the title of the main menu background
    private void setMainMenuTitle(string title)
    {
        mainMenuTitle.text = title;
    }

    /*--Menu Background Animation Functions--*/

    // Transition to HUD Group
    private IEnumerator transitionToHUDGroup(GameObject groupToDisable, GameObject groupToEnable, string newHUDGroupTitle)
    {
        // Shrink the background
        shrinkMenuBackground();

        // Disable the designated group
        groupToDisable.SetActive(false);

        // Have a delay
        yield return new WaitForSeconds(hudTransitionDelay);

        // Set the title of the main menu background
        setMainMenuTitle(newHUDGroupTitle);

        // Enable the designated group
        groupToEnable.SetActive(true);

        // Expand the background
        expandMenuBackground();
    }

    // Shrink menu background
    private void shrinkMenuBackground()
    {
        mainMenuBackgroundAnimationController.SetBool("isExpanding", false);
        mainMenuBackgroundAnimationController.SetBool("isShrinking", true);
    }

    // Expand menu background
    private void expandMenuBackground()
    {
        mainMenuBackgroundAnimationController.SetBool("isExpanding", true);
        mainMenuBackgroundAnimationController.SetBool("isShrinking", false);
    }

    /*--Level Select HUD Functions--*/

    // Open the level select screen
    public void openLevelSelectScreen()
    {
        // Transition to HUD Group
        // Disable the welcome HUD Group
        // Enable the level select HUD Group
        // Set the title of the main menu to be the level select title
        StartCoroutine(transitionToHUDGroup(welcomeHUDGroup, levelSelectHUDGroup, levelSelectGroupTitle));
    }

    // Close the level select screen
    public void closeLevelSelectScreen()
    {
        // Transition to HUD Group
        // Disable the level select HUD Group
        // Enable the welcome HUD Group
        // Set the title of the main menu to be the welcome title
        StartCoroutine(transitionToHUDGroup(levelSelectHUDGroup, welcomeHUDGroup, welcomeGroupTitle));
    }

    /*--Help Group HUD Functions--*/

    // Open the help screen
    public void openHelpScreen()
    {
        StartCoroutine(transitionToHUDGroup(welcomeHUDGroup, helpHUDGroup, helpGroupTitle));
    }

    // Close the help screen
    public void closeHelpScreen()
    {
        StartCoroutine(transitionToHUDGroup(helpHUDGroup, welcomeHUDGroup, welcomeGroupTitle));
    }

    // Load a level
    public void loadLevel(string levelName)
    {
        // Transition to the selected level
        StartCoroutine(transitionToSelectedLevel(levelName));
    }

    // Transition to the selected level
    private IEnumerator transitionToSelectedLevel(string name)
    {
        // Shrink the menu background
        shrinkMenuBackground();

        // Show loading text object
        loadingText.gameObject.SetActive(true);

        yield return new WaitForSeconds(loadingTransitionDelay);

        // Open the level
        SceneManager.LoadSceneAsync(name);
    }

}


text:
from setuptools import setup, find_packages

setup(name='worm-dao',
      version='0.1.4',
      description='Worst or wonderful DAO library',
      classifiers=[
        "Development Status :: 2 - Pre-Alpha",
        "License :: OSI Approved :: BSD License",
        "Operating System :: OS Independent",
        "Programming Language :: Python",
        "Programming Language :: Python :: 2.7",
        "Topic :: Database :: Front-Ends",
        "Topic :: Software Development :: Libraries :: Python Modules",
        "Intended Audience :: Developers",
        ],
      author='Marcin Nowak',
      author_email='marcin.j.nowak@gmail.com',
      url='https://github.com/marcinn/worm',
      keywords='dao orm database',
      packages=find_packages('.'),
      include_package_data=True,
      zip_safe=True,
      )


text:
<?xml version="1.0"?>
<!DOCTYPE project>

<project name="bootstrap3-theme" basedir="." default="deploy">
	<import file="D:\Works\liferay-plugins-sdk-6.2\themes/build-common-theme.xml" />

	<property name="theme.parent" value="_unstyled" />
</project>


text:
static int set_input_clock(struct echoaudio *chip, u16 clock);
static int set_professional_spdif(struct echoaudio *chip, char prof);
static int update_flags(struct echoaudio *chip);
static int set_vmixer_gain(struct echoaudio *chip, u16 output, u16 pipe,
			   int gain);
static int update_vmixer_level(struct echoaudio *chip);

static int init_hw(struct echoaudio *chip, u16 device_id, u16 subdevice_id)
{
	int err;

	DE_INIT(("init_hw() - Mia\n"));
	if (snd_BUG_ON((subdevice_id & 0xfff0) != MIA))
		return -ENODEV;

	if ((err = init_dsp_comm_page(chip))) {
		DE_INIT(("init_hw - could not initialize DSP comm page\n"));
		return err;
	}

	chip->device_id = device_id;
	chip->subdevice_id = subdevice_id;
	chip->bad_board = TRUE;
	chip->dsp_code_to_load = &card_fw[FW_MIA_DSP];
	/* Since this card has no ASIC, mark it as loaded so everything
	   works OK */
	chip->asic_loaded = TRUE;
	if ((subdevice_id & 0x0000f) == MIA_MIDI_REV)
		chip->has_midi = TRUE;
	chip->input_clock_types = ECHO_CLOCK_BIT_INTERNAL |
		ECHO_CLOCK_BIT_SPDIF;

	if ((err = load_firmware(chip)) < 0)
		return err;
	chip->bad_board = FALSE;

	if ((err = init_line_levels(chip)))
		return err;

	DE_INIT(("init_hw done\n"));
	return err;
}

static u32 detect_input_clocks(const struct echoaudio *chip)
{
	u32 clocks_from_dsp, clock_bits;

	/* Map the DSP clock detect bits to the generic driver clock
	   detect bits */
	clocks_from_dsp = le32_to_cpu(chip->comm_page->status_clocks);

	clock_bits = ECHO_CLOCK_BIT_INTERNAL;

	if (clocks_from_dsp & GLDM_CLOCK_DETECT_BIT_SPDIF)
		clock_bits |= ECHO_CLOCK_BIT_SPDIF;

	return clock_bits;
}

/* The Mia has no ASIC. Just do nothing */
static int load_asic(struct echoaudio *chip)
{
	return 0;
}

static int set_sample_rate(struct echoaudio *chip, u32 rate)
{
	u32 control_reg;

	switch (rate) {
	case 96000:
		control_reg = MIA_96000;
		break;
	case 88200:
		control_reg = MIA_88200;
		break;
	case 48000:
		control_reg = MIA_48000;
		break;
	case 44100:
		control_reg = MIA_44100;
		break;
	case 32000:
		control_reg = MIA_32000;
		break;
	default:
		DE_ACT(("set_sample_rate: %d invalid!\n", rate));
		return -EINVAL;
	}

	/* Override the clock setting if this Mia is set to S/PDIF clock */
	if (chip->input_clock == ECHO_CLOCK_SPDIF)
		control_reg |= MIA_SPDIF;

	/* Set the control register if it has changed */
	if (control_reg != le32_to_cpu(chip->comm_page->control_register)) {
		if (wait_handshake(chip))
			return -EIO;

		chip->comm_page->sample_rate = cpu_to_le32(rate);	/* ignored by the DSP */
		chip->comm_page->control_register = cpu_to_le32(control_reg);
		chip->sample_rate = rate;

		clear_handshake(chip);
		return send_vector(chip, DSP_VC_UPDATE_CLOCKS);
	}
	return 0;
}

static int set_input_clock(struct echoaudio *chip, u16 clock)
{
	DE_ACT(("set_input_clock(%d)\n", clock));
	if (snd_BUG_ON(clock != ECHO_CLOCK_INTERNAL &&
		       clock != ECHO_CLOCK_SPDIF))
		return -EINVAL;

	chip->input_clock = clock;
	return set_sample_rate(chip, chip->sample_rate);
}

/* This function routes the sound from a virtual channel to a real output */
static int set_vmixer_gain(struct echoaudio *chip, u16 output, u16 pipe,
			   int gain)
{
	int index;

	if (snd_BUG_ON(pipe >= num_pipes_out(chip) ||
		       output >= num_busses_out(chip)))
		return -EINVAL;

	if (wait_handshake(chip))
		return -EIO;

	chip->vmixer_gain[output][pipe] = gain;
	index = output * num_pipes_out(chip) + pipe;
	chip->comm_page->vmixer[index] = gain;

	DE_ACT(("set_vmixer_gain: pipe %d, out %d = %d\n", pipe, output, gain));
	return 0;
}

/* Tell the DSP to read and update virtual mixer levels in comm page. */
static int update_vmixer_level(struct echoaudio *chip)
{
	if (wait_handshake(chip))
		return -EIO;
	clear_handshake(chip);
	return send_vector(chip, DSP_VC_SET_VMIXER_GAIN);
}

/* Tell the DSP to reread the flags from the comm page */
static int update_flags(struct echoaudio *chip)
{
	if (wait_handshake(chip))
		return -EIO;
	clear_handshake(chip);
	return send_vector(chip, DSP_VC_UPDATE_FLAGS);
}

static int set_professional_spdif(struct echoaudio *chip, char prof)
{
	DE_ACT(("set_professional_spdif %d\n", prof));
	if (prof)
		chip->comm_page->flags |=
			cpu_to_le32(DSP_FLAG_PROFESSIONAL_SPDIF);
	else
		chip->comm_page->flags &=
			~cpu_to_le32(DSP_FLAG_PROFESSIONAL_SPDIF);
	chip->professional_spdif = prof;
	return update_flags(chip);
}


text:
module Utils
  def pause_if_needed(seconds = 0.1)
    seconds *= 10 if ENV['CI'] == 'true'
    sleep seconds unless BrokerConfig.current_adapter == :in_memory
  end
end

RSpec.configure do |config|
  config.include Utils
end


text:
package main

import (
	"flag"
	"log"
	"os"
)

// You'll see the name VTOC used a lot.
// The Volume Table Of Contents (extra points for looking this
// up) is an array of structs listing the file names, and
// their info. We'll see how much is needed -- almost
// certainly more than we think.  No attempt is made hee to be
// space efficient. Disks are big, and metadata is much the
// smallest part of it all. I think.
// The VTOC goes after the data, because the VTOC size
// is actually dependent on the values of the offsets in the
// individual structs. We have to write the data, fill in the
// VTOC, and write the encoded VTOC out.
// VTOC is a []file.

var (
	debug = func(string, ...interface{}) {}
	d     = flag.Bool("d", false, "Debug prints")
)

func usage() {
	log.Fatalf("Usage: archive d|e|t [args...]")
}

func main() {
	var err error
	flag.Parse()
	if *d {
		debug = log.Printf
	}

	a := flag.Args()
	debug("Args %v", a)
	if len(a) < 1 {
		usage()
	}
	op := a[0]

	switch op {
	case "e":
		err = encode(os.Stdout, a[1:]...)
	case "t":
		err = toc(a[1:]...)
	case "d":
		err = decode(a[1:]...)
	default:
		usage()
	}
	if err != nil {
		log.Fatalf("%v", err)
	}
}


text:
import Ember from 'ember';
import ExtractedField from './extracted-field';
import ExtractedVariant from './extracted-variant';

export default Ember.Object.extend({
    definition: null,
    extracted: null,
    matchedTemplate: null,

    url: Ember.computed.reads('extracted.url'),

    fields: function() {
        var fields = [],
            item = this.get('extracted');
        Object.keys(item).forEach(function(key) {
            var fieldDefinition = this.get('definition.fields').findBy('name', key);
            if (fieldDefinition) {
                fields.pushObject(ExtractedField.create(
                    { name: key, type: fieldDefinition.get('type'), value: item[key] }));
            }
        }.bind(this));
        return fields;
    }.property('extracted', 'definition'),

    variants: function() {
        var variants = [],
            item = this.get('extracted');
        if (!Ember.isEmpty(item['variants'])) {
            item.variants.forEach(function(variant) {
                var fields = [];
                Object.keys(variant).forEach(function(key) {
                    fields.pushObject(ExtractedField.create(
                        { name: key, type: 'variant', value: variant[key] }));
                }.bind(this));
                variants.pushObject(ExtractedVariant.create({ fields: fields }));
            }.bind(this));
        }
        return variants;
    }.property('extracted', 'definition'),
});


text:
package org.supla.android.listview;

/*
 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; either version 2
 of the License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

 Author: Przemyslaw Zygmunt p.zygmunt@acsoftware.pl [AC SOFTWARE]
 */

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;

import org.supla.android.ChannelDetailRGB;
import org.supla.android.R;
import org.supla.android.db.Channel;

public class ChannelListView extends ListView {

    private float LastXtouch = -1;
    private float LastYtouch = -1;
    private ChannelLayout channelLayout = null;
    private ChannelLayout lastCL = null;
    private boolean buttonSliding = false;
    private Cursor _newCursor;
    private OnChannelButtonTouchListener onChannelButtonTouchListener;
    private OnDetailListener onDetailListener;
    private boolean requestLayout_Locked = false;
    private boolean detailSliding;
    private boolean detailTouchDown;
    private SectionLayout Header;
    private boolean detailAnim;
    private boolean mDetailVisible;
    private DetailLayout mDetailLayout;

    public interface OnChannelButtonTouchListener {

        void onChannelButtonTouch(boolean left, boolean up, int channelId, int channelFunc);
    }

    public interface OnDetailListener {

        void onChannelDetailShow();
        void onChannelDetailHide();
    }

    public ChannelListView(Context context) {
        super(context);
        init(context);
    }

    public ChannelListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    public ChannelListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {

        setHeaderDividersEnabled(false);
        setFooterDividersEnabled(false);

        setDivider(null);

        //setFastScrollEnabled(true);
        setVerticalScrollBarEnabled(false);

        Header = new SectionLayout(context);
        Header.setCaption("ABC");
        detailSliding = false;
        detailTouchDown = false;
        detailAnim = false;
        mDetailLayout = null;
        mDetailVisible = false;

    }

    private DetailLayout getDetailLayout() {

        if ( mDetailLayout == null ) {

            mDetailLayout = new ChannelDetailRGB(getContext(), this);

            if ( getParent() instanceof ViewGroup ) {
                ((ViewGroup)getParent()).addView(mDetailLayout);
            }

            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(getWidth(), getHeight());
            lp.setMargins(getWidth(),0,-getWidth(),0);
            mDetailLayout.setLayoutParams(lp);

            return mDetailLayout;

        }

        return mDetailLayout;
    }

    @Override
    public void setAdapter(ListAdapter adapter) {
        super.setAdapter(adapter);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return super.onInterceptTouchEvent(ev);
    }

    @Override
    public void requestLayout() {

        if (!requestLayout_Locked)
            super.requestLayout();

    }

    public int getMargin() {

        ViewGroup.LayoutParams lp = getLayoutParams();
        if ( lp instanceof  ViewGroup.MarginLayoutParams ) {
            return ((MarginLayoutParams)lp).leftMargin;
        }

        return 0;
    }

    public boolean setMargin(int margin) {

        ViewGroup.LayoutParams lp = getLayoutParams();
        if ( lp instanceof  ViewGroup.MarginLayoutParams ) {
            ((ViewGroup.MarginLayoutParams)lp).setMargins(margin,0,-margin,0);
            setLayoutParams(lp);

            if ( mDetailLayout != null )
                mDetailLayout.setMargin(getWidth()+((MarginLayoutParams) lp).leftMargin);

            return true;
        }

        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {

        int action = ev.getAction();
        float X = ev.getX();
        float Y = ev.getY();

        float deltaY = Math.abs(Y - LastYtouch);
        float deltaX = Math.abs(X - LastXtouch);

        if ( ev.getAction() == MotionEvent.ACTION_DOWN
                || channelLayout != null ) {

            View view = getChildAt(pointToPosition((int) ev.getX(), (int) ev.getY()) - getFirstVisiblePosition());

            if (view instanceof ChannelLayout) {

                if ( action == MotionEvent.ACTION_DOWN ) {

                    LastXtouch = ev.getX();
                    LastYtouch = ev.getY();

                    if ( !isDetailVisible() ) {
                        channelLayout = (ChannelLayout)view;
                    }

                    buttonSliding = false;
                    detailSliding = false;
                    detailTouchDown = false;

                    if ( lastCL != null && lastCL != channelLayout ) {
                        lastCL.AnimateToRestingPosition(true);
                        lastCL = null;
                    }

                    if ( channelLayout != null
                         && channelLayout.getDetailSliderEnabled() ) {

                        Object obj = getItemAtPosition(pointToPosition((int) ev.getX(), (int) ev.getY()));
                        if ( obj instanceof Cursor && getDetailLayout() != null ) {

                            Channel channel = new Channel();
                            channel.AssignCursorData((Cursor)obj);
                            getDetailLayout().setData(channel);

                            detailTouchDown = true;

                        }
                    }

                } else if ( action == MotionEvent.ACTION_MOVE ) {

                    if ( channelLayout.getButtonsEnabled()
                            && !detailSliding ) {

                        if ( channelLayout.Sliding() == false
                                && deltaY >= deltaX ) {
                            return super.onTouchEvent(ev);
                        }

                        if (  X != LastXtouch ) {
                            channelLayout.Slide((int)(X-LastXtouch));
                            buttonSliding = true;
                        }

                        LastXtouch = X;
                        LastYtouch = Y;

                        if ( channelLayout.Sliding() ) {
                            return true;
                        }

                    }
                }

            }

        }

        if ( LastXtouch != -1
                && ( detailTouchDown || isDetailVisible() )
                && action == MotionEvent.ACTION_MOVE) {

                        int delta = (int)(X-LastXtouch);
                        int margin = getMargin();

                        if ( isDetailVisible() ) {
                            if ( margin + (int)delta < -getWidth() )
                                delta = -(margin+getWidth());
                        } else {
                            if ( margin + (int)delta > -1 )
                                delta-=(margin + (int)delta) + 1;
                        }

                        if ( ( ( (!isDetailVisible() && X <= LastXtouch)
                                || (isDetailVisible() && X >= LastXtouch) )
                                && deltaY < deltaX ) || detailSliding ) {

                            setMargin(getMargin()+delta);

                            if ( detailSliding == false ) {

                                int color = getResources().getColor(R.color.detail_gb);

                                if ( channelLayout != null )
                                    channelLayout.setBackgroundColor(color);

                                setVisibility(View.VISIBLE);
                                mDetailLayout.setBackgroundColor(color);
                                mDetailLayout.setVisibility(View.VISIBLE);

                            }

                            detailSliding = true;

                            return true;

                        } else if ( detailSliding ){
                            return true;
                        }

        }

        if  ( action == MotionEvent.ACTION_UP
                || action == MotionEvent.ACTION_CANCEL )  {

            AnimateDetailSliding(false);

            if ( channelLayout != null ) {
                channelLayout.AnimateToRestingPosition(buttonSliding == false);
                lastCL = channelLayout;
                channelLayout = null;
            }

            LastXtouch = -1;
            buttonSliding = false;
            detailSliding = false;
        }

        return super.onTouchEvent(ev);

    }

    public void AnimateDetailSliding(boolean force) {

        final int margin = getMargin();

        if ( detailAnim
                || mDetailLayout == null )
            return;

        if ( ( margin == 0
                || ( isDetailVisible()
                     && margin == -getWidth() ) ) && !force )
            return;

        int offset = 0;
        int m = margin;

        if ( isDetailVisible() )
            m+=getWidth();

        if ( Math.abs(m) > getWidth()/3.5 || force ) {

            if ( isDetailVisible() ) {
                offset = -margin;
            } else {
                offset = -(margin+getWidth());
            }

        } else {

            if ( isDetailVisible() ) {
                offset = -(getWidth()+margin);
            } else {
                offset = -margin;
            }

        }

        ValueAnimator varl = ValueAnimator.ofInt(offset);
        varl.setDuration(200);

        varl.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {

                setMargin(margin+(Integer)animation.getAnimatedValue());
            }

        });

        varl.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                detailAnim = true;
                setVisibility(View.VISIBLE);
                mDetailLayout.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                detailAnim = false;

                if ( getMargin() != 0 ) {
                    mDetailLayout.setVisibility(View.VISIBLE);
                    setVisibility(View.INVISIBLE);
                    mDetailVisible = true;

                    onDetailShow();

                } else {
                    mDetailLayout.setVisibility(View.INVISIBLE);
                    setVisibility(View.VISIBLE);
                    mDetailVisible = false;

                    onDetailHide();
                }

                setChannelBackgroundColor(getResources().getColor(R.color.channel_cell));
                detailAnim = false;
                detailSliding = false;
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                onAnimationEnd(animation);
            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });

        varl.start();

    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);

        canvas.save();

        ListViewCursorAdapter adapter = (ListViewCursorAdapter)getAdapter();
        if ( adapter != null ) {

            int idx = adapter.getSectionIndexAtPosition(pointToPosition(0, 0));

            ListViewCursorAdapter.SectionItem section = adapter.getSectionAtIndex(idx);
            if ( section != null
                    && section.getView() != null ) {

                idx++;
                ListViewCursorAdapter.SectionItem next = adapter.getSectionAtIndex(idx);

                if ( next != null
                        && next.getView() != null
                        && next.getView().getTop() > 0
                        && next.getView().getTop() <= section.getView().getHeight() ) {

                    canvas.translate(0, (next.getView().getHeight() - next.getView().getTop())*-1);
                }

                section.getView().draw(canvas);
            }
        }

        canvas.restore();

    }

    public void onSlideAnimationEnd() {

        if ( _newCursor != null && !Slided() ) {
            Cursor newCursor = _newCursor;
            _newCursor = null;
            Refresh(newCursor, true);
        }

    }

    private void onDetailShow() {
        if ( onDetailListener != null )
            onDetailListener.onChannelDetailShow();
    }

    private void onDetailHide() {
        if ( onDetailListener != null )
            onDetailListener.onChannelDetailHide();
    }

    private void setChannelBackgroundColor(int color) {

        for(int i=0; i<=getCount();i++) {

            View v = getChildAt(i);

            if ( v != null
                    && v instanceof ChannelLayout ) {
                ((ChannelLayout)v).setBackgroundColor(color);
            }

        }

    }

    public boolean isDetailSliding() {
        return detailSliding || detailAnim;
    }

    public boolean Slided() {

        if ( detailSliding )
            return true;

        int start = getFirstVisiblePosition();

        for(int i=start; i<=getLastVisiblePosition();i++) {

            View v = getChildAt(i-start);

            if ( v != null
                    && v instanceof ChannelLayout
                    && ((ChannelLayout)v).Slided() > 0 ) {
                    return true;
            }

        }

        return false;
    }

    public void Refresh(Cursor newCursor, boolean full) {

        if ( _newCursor != null ) {
            _newCursor.close();
            _newCursor = null;
        }

        if ( getAdapter() == null )
            return;

        if ( full
                || ( !isDetailSliding()
                     && !Slided()
                     && getFirstVisiblePosition() == 0 ) ) {
            newCursor.moveToFirst();
            ((ListViewCursorAdapter)getAdapter()).changeCursor(newCursor);
            return;
        };

        if ( newCursor == null || newCursor.isClosed() )
            return;

        _newCursor = newCursor;
        int start = getFirstVisiblePosition();

        for(int i=start;i<=getLastVisiblePosition();i++) {

            View v = getChildAt(i-start);
            Object obj = getItemAtPosition(i);

            if ( v instanceof ChannelLayout
                    && obj instanceof Cursor ) {

                Channel old_channel = new Channel();
                old_channel.AssignCursorData((Cursor) obj);

                if ( _newCursor.moveToFirst() )
                    do {
                        Channel new_channel = new Channel();
                        new_channel.AssignCursorData(_newCursor);

                        if ( new_channel.getId() == old_channel.getId() ) {
                            requestLayout_Locked = true;
                            ((ListViewCursorAdapter) getAdapter()).setData((ChannelLayout) v, new_channel);
                            requestLayout_Locked = false;
                        }

                    } while(_newCursor.moveToNext());
            }

        }

    }

    public void setOnChannelButtonTouchListener(OnChannelButtonTouchListener onChannelButtonTouchListener) {
        this.onChannelButtonTouchListener = onChannelButtonTouchListener;
    }

    public void setOnDetailListener(OnDetailListener onDetailListener) {
        this.onDetailListener = onDetailListener;
    }

    public OnChannelButtonTouchListener getOnChannelButtonTouchListener() {
        return onChannelButtonTouchListener;
    }

    public boolean isDetailVisible() {
        return mDetailVisible && mDetailLayout != null;
    }

    public void hideDetail(boolean animated) {

        if ( isDetailVisible() )

            if ( animated ) {
                AnimateDetailSliding(true);
            } else {

                setMargin(0);

                mDetailLayout.setVisibility(View.INVISIBLE);
                mDetailVisible = false;
                setVisibility(View.VISIBLE);

                onDetailHide();
            }

    }

    public Channel detail_getChannel() {

        if ( isDetailVisible() ) {
            return mDetailLayout.getChannelFromDatabase();
        }

        return null;
    }

    public int detail_getChannelId() {

        if ( isDetailVisible() ) {
            return mDetailLayout.getChannelId();
        }

        return 0;
    }

    public void detail_OnChannelDataChanged() {

        if ( isDetailVisible() )
            mDetailLayout.OnChannelDataChanged();

    }
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PopupBox.cs" company="PropertyTools">
//   Copyright (c) 2014 PropertyTools contributors
// </copyright>
// <summary>
//   Represents a popup control that provides a data template for the popup.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace PropertyTools.Wpf
{
    using System.Windows;
    using System.Windows.Controls;

    /// <summary>
    /// Represents a popup control that provides a data template for the popup.
    /// </summary>
    public class PopupBox : ComboBox
    {
        /// <summary>
        /// Identifies the <see cref="PopupTemplate"/> dependency property.
        /// </summary>
        public static readonly DependencyProperty PopupTemplateProperty = DependencyProperty.Register(
            nameof(PopupTemplate),
            typeof(DataTemplate),
            typeof(PopupBox),
            new UIPropertyMetadata(null));

        /// <summary>
        /// Initializes static members of the <see cref="PopupBox" /> class.
        /// </summary>
        static PopupBox()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(PopupBox), new FrameworkPropertyMetadata(typeof(PopupBox)));
        }

        /// <summary>
        /// Gets or sets the popup template.
        /// </summary>
        /// <value>The popup template.</value>
        public DataTemplate PopupTemplate
        {
            get
            {
                return (DataTemplate)this.GetValue(PopupTemplateProperty);
            }

            set
            {
                this.SetValue(PopupTemplateProperty, value);
            }
        }
    }
}


text:
package org.spongepowered.api.plugin;

import org.spongepowered.plugin.PluginContainer;

import java.util.Collection;
import java.util.Optional;

/**
 * The manager that manages {@link PluginContainer plugins}.
 */
public interface PluginManager {

    String MINECRAFT_PLUGIN_ID = "minecraft";
    String SPONGE_PLUGIN_ID = "sponge";

    /**
     * Gets the plugin container from an instance.
     *
     * @param instance The instance
     * @return The container
     */
    Optional<PluginContainer> fromInstance(Object instance);

    /**
     * Retrieves a {@link PluginContainer} based on its ID.
     *
     * @param id The plugin ID
     * @return The plugin, if available
     */
    Optional<PluginContainer> plugin(String id);

    /**
     * Gets a {@link Collection} of all {@link PluginContainer}s.
     *
     * @return The plugins
     */
    Collection<PluginContainer> plugins();
}


text:
package com.amazonaws.services.route53resolver.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * In an UpdateResolverRule request, information about the changes that you want to make.
 *

 *
 * @see AWS
 *      API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ResolverRuleConfig implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The new name for the resolver rule. The name that you specify appears in the Resolver dashboard in the Route 53
     * console.
     *

     */
    private String name;
    /**
     *

     * For DNS queries that originate in your VPC, the new IP addresses that you want to route outbound DNS queries to.
     *

     */
    private java.util.List<TargetAddress> targetIps;
    /**
     *

     * The ID of the new outbound resolver endpoint that you want to use to route DNS queries to the IP addresses that
     * you specify in TargetIps.
     *

     */
    private String resolverEndpointId;

    /**
     *

     * The new name for the resolver rule. The name that you specify appears in the Resolver dashboard in the Route 53
     * console.
     *

     *
     * @param name
     *        The new name for the resolver rule. The name that you specify appears in the Resolver dashboard in the
     *        Route 53 console.
     */

    public void setName(String name) {
        this.name = name;
    }

    /**
     *

     * The new name for the resolver rule. The name that you specify appears in the Resolver dashboard in the Route 53
     * console.
     *

     *
     * @return The new name for the resolver rule. The name that you specify appears in the Resolver dashboard in the
     *         Route 53 console.
     */

    public String getName() {
        return this.name;
    }

    /**
     *

     * The new name for the resolver rule. The name that you specify appears in the Resolver dashboard in the Route 53
     * console.
     *

     *
     * @param name
     *        The new name for the resolver rule. The name that you specify appears in the Resolver dashboard in the
     *        Route 53 console.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ResolverRuleConfig withName(String name) {
        setName(name);
        return this;
    }

    /**
     *

     * For DNS queries that originate in your VPC, the new IP addresses that you want to route outbound DNS queries to.
     *

     *
     * @return For DNS queries that originate in your VPC, the new IP addresses that you want to route outbound DNS
     *         queries to.
     */

    public java.util.List<TargetAddress> getTargetIps() {
        return targetIps;
    }

    /**
     *

     * For DNS queries that originate in your VPC, the new IP addresses that you want to route outbound DNS queries to.
     *

     *
     * @param targetIps
     *        For DNS queries that originate in your VPC, the new IP addresses that you want to route outbound DNS
     *        queries to.
     */

    public void setTargetIps(java.util.Collection<TargetAddress> targetIps) {
        if (targetIps == null) {
            this.targetIps = null;
            return;
        }

        this.targetIps = new java.util.ArrayList<TargetAddress>(targetIps);
    }

    /**
     *

     * For DNS queries that originate in your VPC, the new IP addresses that you want to route outbound DNS queries to.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setTargetIps(java.util.Collection)} or {@link #withTargetIps(java.util.Collection)} if you want to
     * override the existing values.
     *

     *
     * @param targetIps
     *        For DNS queries that originate in your VPC, the new IP addresses that you want to route outbound DNS
     *        queries to.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ResolverRuleConfig withTargetIps(TargetAddress... targetIps) {
        if (this.targetIps == null) {
            setTargetIps(new java.util.ArrayList<TargetAddress>(targetIps.length));
        }
        for (TargetAddress ele : targetIps) {
            this.targetIps.add(ele);
        }
        return this;
    }

    /**
     *

     * For DNS queries that originate in your VPC, the new IP addresses that you want to route outbound DNS queries to.
     *

     *
     * @param targetIps
     *        For DNS queries that originate in your VPC, the new IP addresses that you want to route outbound DNS
     *        queries to.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ResolverRuleConfig withTargetIps(java.util.Collection<TargetAddress> targetIps) {
        setTargetIps(targetIps);
        return this;
    }

    /**
     *

     * The ID of the new outbound resolver endpoint that you want to use to route DNS queries to the IP addresses that
     * you specify in TargetIps.
     *

     *
     * @param resolverEndpointId
     *        The ID of the new outbound resolver endpoint that you want to use to route DNS queries to the IP addresses
     *        that you specify in TargetIps.
     */

    public void setResolverEndpointId(String resolverEndpointId) {
        this.resolverEndpointId = resolverEndpointId;
    }

    /**
     *

     * The ID of the new outbound resolver endpoint that you want to use to route DNS queries to the IP addresses that
     * you specify in TargetIps.
     *

     *
     * @return The ID of the new outbound resolver endpoint that you want to use to route DNS queries to the IP
     *         addresses that you specify in TargetIps.
     */

    public String getResolverEndpointId() {
        return this.resolverEndpointId;
    }

    /**
     *

     * The ID of the new outbound resolver endpoint that you want to use to route DNS queries to the IP addresses that
     * you specify in TargetIps.
     *

     *
     * @param resolverEndpointId
     *        The ID of the new outbound resolver endpoint that you want to use to route DNS queries to the IP addresses
     *        that you specify in TargetIps.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ResolverRuleConfig withResolverEndpointId(String resolverEndpointId) {
        setResolverEndpointId(resolverEndpointId);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getName() != null)
            sb.append("Name: ").append(getName()).append(",");
        if (getTargetIps() != null)
            sb.append("TargetIps: ").append(getTargetIps()).append(",");
        if (getResolverEndpointId() != null)
            sb.append("ResolverEndpointId: ").append(getResolverEndpointId());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof ResolverRuleConfig == false)
            return false;
        ResolverRuleConfig other = (ResolverRuleConfig) obj;
        if (other.getName() == null ^ this.getName() == null)
            return false;
        if (other.getName() != null && other.getName().equals(this.getName()) == false)
            return false;
        if (other.getTargetIps() == null ^ this.getTargetIps() == null)
            return false;
        if (other.getTargetIps() != null && other.getTargetIps().equals(this.getTargetIps()) == false)
            return false;
        if (other.getResolverEndpointId() == null ^ this.getResolverEndpointId() == null)
            return false;
        if (other.getResolverEndpointId() != null && other.getResolverEndpointId().equals(this.getResolverEndpointId()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
        hashCode = prime * hashCode + ((getTargetIps() == null) ? 0 : getTargetIps().hashCode());
        hashCode = prime * hashCode + ((getResolverEndpointId() == null) ? 0 : getResolverEndpointId().hashCode());
        return hashCode;
    }

    @Override
    public ResolverRuleConfig clone() {
        try {
            return (ResolverRuleConfig) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.route53resolver.model.transform.ResolverRuleConfigMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
**Link To A Click-Editable List** http://git.io/qEUPIg

##Clues To Implement
- [ ] trioLeft(Peca, Linha, Coluna, Tabuleiro)
- [ ] trioRight(Peca, Linha, Coluna, Tabuleiro)
- [ ] cobra(Peca, Linha, Coluna, Tabuleiro)
- [ ] tSimples(Peca, Linha, Coluna, Tabuleiro)
- [ ] tLeft(Peca, Linha, Coluna, Tabuleiro)
- [ ] tRight(Peca, Linha, Coluna, Tabuleiro)
- [ ] tInvertido(Peca, Linha, Coluna, Tabuleiro)
- [ ] cantoTopLeft(Peca, Linha, Coluna, Tabuleiro)
- [ ] cantoTopRight(Peca, Linha, Coluna, Tabuleiro)
- [ ] cantoBottomLeft(Peca, Linha, Coluna, Tabuleiro)
- [ ] cantoBottomRight(Peca, Linha, Coluna, Tabuleiro)
- [ ] diagonalGrave(Peca, Linha, Coluna, Tabuleiro)
- [ ] diagonalAguda(Peca, Linha, Coluna, Tabuleiro)

##Other Implementations##
- [ ] check(Tabuleiro, TabuleroCompleto)


text:
import logging
import urllib

from oslo_config import cfg
from oslo_utils import encodeutils

import requests

from glance_store import capabilities
import glance_store.driver
from glance_store import exceptions
from glance_store.i18n import _, _LI
import glance_store.location

LOG = logging.getLogger(__name__)

MAX_REDIRECTS = 5

_HTTP_OPTS = [
    cfg.StrOpt('https_ca_certificates_file',
               help="""
Path to the CA bundle file.

This configuration option enables the operator to use a custom
Certificate Authority file to verify the remote server certificate. If
this option is set, the ``https_insecure`` option will be ignored and
the CA file specified will be used to authenticate the server
certificate and establish a secure connection to the server.

Possible values:
    * A valid path to a CA file

Related options:
    * https_insecure

"""),
    cfg.BoolOpt('https_insecure',
                default=True,
                help="""
Set verification of the remote server certificate.

This configuration option takes in a boolean value to determine
whether or not to verify the remote server certificate. If set to
True, the remote server certificate is not verified. If the option is
set to False, then the default CA truststore is used for verification.

This option is ignored if ``https_ca_certificates_file`` is set.
The remote server certificate will then be verified using the file
specified using the ``https_ca_certificates_file`` option.

Possible values:
    * True
    * False

Related options:
    * https_ca_certificates_file

"""),
    cfg.DictOpt('http_proxy_information',
                default={},
                help="""
The http/https proxy information to be used to connect to the remote
server.

This configuration option specifies the http/https proxy information
that should be used to connect to the remote server. The proxy
information should be a key value pair of the scheme and proxy, for
example, http:10.0.0.1:3128. You can also specify proxies for multiple
schemes by separating the key value pairs with a comma, for example,
http:10.0.0.1:3128, https:10.0.0.1:1080.

Possible values:
    * A comma separated list of scheme:proxy pairs as described above

Related options:
    * None

""")]

class StoreLocation(glance_store.location.StoreLocation):

    """Class describing an HTTP(S) URI."""

    def process_specs(self):
        self.scheme = self.specs.get('scheme', 'http')
        self.netloc = self.specs['netloc']
        self.user = self.specs.get('user')
        self.password = self.specs.get('password')
        self.path = self.specs.get('path')
        self.query = self.spec.get('query')

    def _get_credstring(self):
        if self.user:
            return '%s:%s@' % (self.user, self.password)
        return ''

    def _get_query_string(self):
        if self.query:
            return "?%s" % self.query
        return ""

    def get_uri(self):
        return "%s://%s%s%s%s" % (
            self.scheme,
            self._get_credstring(),
            self.netloc,
            self.path,
            self._get_query_string()
        )

    def parse_uri(self, uri):
        """
        Parse URLs. This method fixes an issue where credentials specified
        in the URL are interpreted differently in Python 2.6.1+ than prior
        versions of Python.
        """
        pieces = urllib.parse.urlparse(uri)
        self.validate_schemas(uri, valid_schemas=('https://', 'http://'))
        self.scheme = pieces.scheme
        netloc = pieces.netloc
        path = pieces.path
        try:
            if '@' in netloc:
                creds, netloc = netloc.split('@')
            else:
                creds = None
        except ValueError:
            # Python 2.6.1 compat
            # see lp659445 and Python issue7904
            if '@' in path:
                creds, path = path.split('@')
            else:
                creds = None
        if creds:
            try:
                self.user, self.password = creds.split(':')
            except ValueError:
                reason = _("Credentials are not well-formatted.")
                LOG.info(reason)
                raise exceptions.BadStoreUri(message=reason)
        else:
            self.user = None
        if netloc == '':
            LOG.info(_LI("No address specified in HTTP URL"))
            raise exceptions.BadStoreUri(uri=uri)
        else:
            # IPv6 address has the following format [1223:0:0:..]:<some_port>
            # we need to be sure that we are validating port in both IPv4,IPv6
            delimiter = "]:" if netloc.count(":") > 1 else ":"
            host, dlm, port = netloc.partition(delimiter)
            # if port is present in location then validate port format
            if port and not port.isdigit():
                raise exceptions.BadStoreUri(uri=uri)

        self.netloc = netloc
        self.path = path
        self.query = pieces.query

def http_response_iterator(conn, response, size):
    """
    Return an iterator for a file-like object.

    :param conn: HTTP(S) Connection
    :param response: urllib3.HTTPResponse object
    :param size: Chunk size to iterate with
    """
    try:
        chunk = response.read(size)
        while chunk:
            yield chunk
            chunk = response.read(size)
    finally:
        conn.close()

class Store(glance_store.driver.Store):

    """An implementation of the HTTP(S) Backend Adapter"""

    _CAPABILITIES = (capabilities.BitMasks.READ_ACCESS |
                     capabilities.BitMasks.DRIVER_REUSABLE)
    OPTIONS = _HTTP_OPTS

    def __init__(self, *args, **kargs):
        super(Store, self).__init__(*args, **kargs)
        if self.backend_group:
            self._set_url_prefix()

    def _set_url_prefix(self):
        # NOTE(abhishekk): HTTP store url either starts with http
        # or https, so default _url_prefix is set to http.
        self._url_prefix = "http"

    @capabilities.check
    def get(self, location, offset=0, chunk_size=None, context=None):
        """
        Takes a `glance_store.location.Location` object that indicates
        where to find the image file, and returns a tuple of generator
        (for reading the image file) and image_size

        :param location: `glance_store.location.Location` object, supplied
                        from glance_store.location.get_location_from_uri()
        """
        try:
            conn, resp, content_length = self._query(location, 'GET')
        except requests.exceptions.ConnectionError:
            reason = _("Remote server where the image is present "
                       "is unavailable.")
            LOG.exception(reason)
            raise exceptions.RemoteServiceUnavailable(message=reason)

        iterator = http_response_iterator(conn, resp, self.READ_CHUNKSIZE)

        class ResponseIndexable(glance_store.Indexable):
            def another(self):
                try:
                    return next(self.wrapped)
                except StopIteration:
                    return ''

        return (ResponseIndexable(iterator, content_length), content_length)

    def get_schemes(self):
        return ('http', 'https')

    def get_size(self, location, context=None):
        """
        Takes a `glance_store.location.Location` object that indicates
        where to find the image file, and returns the size

        :param location: `glance_store.location.Location` object, supplied
                        from glance_store.location.get_location_from_uri()
        """
        conn = None
        try:
            conn, resp, size = self._query(location, 'HEAD')
        except requests.exceptions.ConnectionError as exc:
            err_msg = encodeutils.exception_to_unicode(exc)
            reason = _("The HTTP URL is invalid: %s") % err_msg
            LOG.info(reason)
            raise exceptions.BadStoreUri(message=reason)
        finally:
            # NOTE(sabari): Close the connection as the request was made with
            # stream=True
            if conn is not None:
                conn.close()
        return size

    def _query(self, location, verb):
        redirects_followed = 0

        while redirects_followed < MAX_REDIRECTS:
            loc = location.store_location

            conn = self._get_response(loc, verb)

            # NOTE(sigmavirus24): If it was generally successful, break early
            if conn.status_code < 300:
                break

            self._check_store_uri(conn, loc)

            redirects_followed += 1

            # NOTE(sigmavirus24): Close the response so we don't leak sockets
            conn.close()

            location = self._new_location(location, conn.headers['location'])
        else:
            reason = (_("The HTTP URL exceeded %s maximum "
                        "redirects.") % MAX_REDIRECTS)
            LOG.debug(reason)
            raise exceptions.MaxRedirectsExceeded(message=reason)

        resp = conn.raw

        content_length = int(resp.getheader('content-length', 0))
        return (conn, resp, content_length)

    def _new_location(self, old_location, url):
        store_name = old_location.store_name
        store_class = old_location.store_location.__class__
        image_id = old_location.image_id
        store_specs = old_location.store_specs
        return glance_store.location.Location(store_name,
                                              store_class,
                                              self.conf,
                                              uri=url,
                                              image_id=image_id,
                                              store_specs=store_specs,
                                              backend=self.backend_group)

    @staticmethod
    def _check_store_uri(conn, loc):
        # TODO(sigmavirus24): Make this a staticmethod
        # Check for bad status codes
        if conn.status_code >= 400:
            if conn.status_code == requests.codes.not_found:
                reason = _("HTTP datastore could not find image at URI.")
                LOG.debug(reason)
                raise exceptions.NotFound(message=reason)

            reason = (_("HTTP URL %(url)s returned a "
                        "%(status)s status code. \nThe response body:\n"
                        "%(body)s") %
                      {'url': loc.path, 'status': conn.status_code,
                       'body': conn.text})
            LOG.debug(reason)
            raise exceptions.BadStoreUri(message=reason)

        if conn.is_redirect and conn.status_code not in (301, 302):
            reason = (_("The HTTP URL %(url)s attempted to redirect "
                        "with an invalid %(status)s status code."),
                      {'url': loc.path, 'status': conn.status_code})
            LOG.info(reason)
            raise exceptions.BadStoreUri(message=reason)

    def _get_response(self, location, verb):
        if not hasattr(self, 'session'):
            self.session = requests.Session()

        if self.backend_group:
            store_conf = getattr(self.conf, self.backend_group)
        else:
            store_conf = self.conf.glance_store

        ca_bundle = store_conf.https_ca_certificates_file
        disable_https = store_conf.https_insecure
        self.session.verify = ca_bundle if ca_bundle else not disable_https
        self.session.proxies = store_conf.http_proxy_information
        return self.session.request(verb, location.get_uri(), stream=True,
                                    allow_redirects=False)


text:
<img title="logo-metatron" src="https://user-images.githubusercontent.com/6300003/44013820-f7647c96-9f02-11e8-8066-1c97f8b1662c.png" alt="metatron-discovery-logo" width="400px">

How to Compile BigQuery JDBC Plugin
==================================
Step 1. Download the JDBC driver from the link below.
----------------------------------
As of writing the guide, the JdbcDriver version is 1.2.11.1014.

Web Page : https://cloud.google.com/bigquery/providers/simba-drivers

Archived JDBC Driver Link in Page : https://storage.googleapis.com/simba-bq-release/jdbc/SimbaJDBCDriverforGoogleBigQuery42_1.2.11.1014.zip

Step 2. After uncompressing the downloaded zip file, copy it under bigquery-connection/src/main/resources/lib.
----------------------------------
```
cp SimbaJDBCDriverforGoogleBigQuery42_1.2.11.1014/* metatron-discovery/discovery-extensions/bigquery-connection/src/main/resources/lib/
```

**Important**
There is a conflict problem with the slf4j library, so when copying the files, you need to exclude the slf4j-api-*.jar files.

Step 3. Execute maven build.
----------------------------------
```
mvn -P extensions-all clean install
```


text:
using ::testing::Return;

namespace omaha {

// Overrides the registry.
class AppTestBase : public testing::Test {
 protected:
  AppTestBase(bool is_machine, bool use_strict_mock)
      : is_machine_(is_machine),
        use_strict_mock_(use_strict_mock) {
  }

  virtual void SetUp() {
    EXPECT_SUCCEEDED(AppManager::CreateInstance(is_machine_));

    // Needed for error strings.
    EXPECT_SUCCEEDED(ResourceManager::Create(
                         is_machine_,
                         app_util::GetCurrentModuleDirectory(),
                         _T("en")));

    if (use_strict_mock_) {
      mock_worker_.reset(new testing::StrictMock<MockWorker>);
    } else {
      mock_worker_.reset(new testing::NiceMock<MockWorker>);
    }

    EXPECT_CALL(*mock_worker_, Lock()).WillRepeatedly(Return(2));
    EXPECT_CALL(*mock_worker_, Unlock()).WillRepeatedly(Return(1));

    model_.reset(new Model(mock_worker_.get()));

    app_bundle_ = model_->CreateAppBundle(is_machine_);
    ASSERT_TRUE(app_bundle_.get());

    EXPECT_SUCCEEDED(app_bundle_->put_displayName(CComBSTR(_T("Test Bundle"))));
    EXPECT_SUCCEEDED(app_bundle_->put_displayLanguage(CComBSTR(_T("en"))));
    EXPECT_SUCCEEDED(app_bundle_->put_installSource(CComBSTR(_T("unittest"))));
    // TODO(omaha3): Address with the TODO in AppBundleInitializedTest::SetUp()
    // then remove app_bundle_state_initialized.h above.
    if (is_machine_) {
      SetAppBundleStateForUnitTest(app_bundle_.get(),
                                   new fsm::AppBundleStateInitialized);
    } else {
      EXPECT_SUCCEEDED(app_bundle_->initialize());
    }
  }

  virtual void TearDown() {
    ResourceManager::Delete();
    AppManager::DeleteInstance();
  }

  const bool is_machine_;
  const bool use_strict_mock_;

  CString hive_override_key_name_;

  scoped_ptr<MockWorker> mock_worker_;
  scoped_ptr<Model> model_;

  shared_ptr<AppBundle> app_bundle_;

 private:
  DISALLOW_COPY_AND_ASSIGN(AppTestBase);
};

class AppTestBaseWithRegistryOverride : public AppTestBase {
 protected:
  AppTestBaseWithRegistryOverride(bool is_machine, bool use_strict_mock)
      : AppTestBase(is_machine, use_strict_mock),
        hive_override_key_name_(kRegistryHiveOverrideRoot) {}

  // Override the registry after initializing the AppBundle so that the latter
  // has the correct network configuration in the event there are pings to send.
  // TODO(omaha3): Ideally we would not send pings from tests: http://b/2911608.
  virtual void SetUp() {
    AppTestBase::SetUp();

    RegKey::DeleteKey(hive_override_key_name_);
    OverrideRegistryHives(hive_override_key_name_);
  }

  virtual void TearDown() {
    RestoreRegistryHives();
    RegKey::DeleteKey(hive_override_key_name_);

    AppTestBase::TearDown();
  }

  CString hive_override_key_name_;
};

}  // namespace omaha

#endif  // OMAHA_GOOPDATE_APP_UNITTEST_BASE_H_