text:
require File.join(File.dirname(__FILE__), '..', '..', 'helper')

class IQ::Color::RGBTest < Test::Unit::TestCase
  context "class definition" do
    should "inherit from base class" do
      assert_equal IQ::Color::Base, IQ::Color::RGB.superclass
    end
  end

  context "instance methods" do
    context "initialize" do
      context "red" do
        should "raise when red value is not an integer" do
          not_an_integer = stub_everything
          not_an_integer.stubs(:is_a?).with(Integer).returns(false)
          mock_integer = stub_everything(:is_a? => true, :< => false, :> => false)
          assert_raise(ArgumentError) do
            IQ::Color::RGB.new(not_an_integer, mock_integer, mock_integer)
          end
        end

        should "raise when red value is greater than 255" do
          mock_integer = stub_everything(:is_a? => true, :< => false, :> => false)
          assert_raise(ArgumentError) do
            IQ::Color::RGB.new(256, mock_integer, mock_integer)
          end
        end

        should "raise when red value is less than zero" do
          mock_integer = stub_everything(:is_a? => true, :< => false, :> => false)
          assert_raise(ArgumentError) do
            IQ::Color::RGB.new(-1, mock_integer, mock_integer)
          end
        end

        should "store red value in instance variable" do
          mock_integer = stub_everything(:is_a? => true, :< => false, :> => false)
          assert_equal 123, IQ::Color::RGB.new(123, mock_integer, mock_integer).instance_variable_get('@red')
        end
      end

      context "green" do
        should "raise when green value is not an integer" do
          not_an_integer = stub_everything
          not_an_integer.stubs(:is_a?).with(Integer).returns(false)
          mock_integer = stub_everything(:is_a? => true, :< => false, :> => false)
          assert_raise(ArgumentError) do
            IQ::Color::RGB.new(mock_integer, not_an_integer, mock_integer)
          end
        end

        should "raise when green value is greater than 255" do
          mock_integer = stub_everything(:is_a? => true, :< => false, :> => false)
          assert_raise(ArgumentError) do
            IQ::Color::RGB.new(mock_integer, 256, mock_integer)
          end
        end

        should "raise when green value is less than zero" do
          mock_integer = stub_everything(:is_a? => true, :< => false, :> => false)
          assert_raise(ArgumentError) do
            IQ::Color::RGB.new(mock_integer, -1, mock_integer)
          end
        end

        should "store green value in instance variable" do
          mock_integer = stub_everything(:is_a? => true, :< => false, :> => false)
          assert_equal 123, IQ::Color::RGB.new(mock_integer, 123, mock_integer).instance_variable_get('@green')
        end
      end

      context "blue" do
        should "raise when blue value is not an integer" do
          not_an_integer = stub_everything
          not_an_integer.stubs(:is_a?).with(Integer).returns(false)
          mock_integer = stub_everything(:is_a? => true, :< => false, :> => false)
          assert_raise(ArgumentError) do
            IQ::Color::RGB.new(mock_integer, mock_integer, not_an_integer)
          end
        end

        should "raise when blue value is greater than 255" do
          mock_integer = stub_everything(:is_a? => true, :< => false, :> => false)
          assert_raise(ArgumentError) do
            IQ::Color::RGB.new(mock_integer, mock_integer, 256)
          end
        end

        should "raise when blue value is less than zero" do
          mock_integer = stub_everything(:is_a? => true, :< => false, :> => false)
          assert_raise(ArgumentError) do
            IQ::Color::RGB.new(mock_integer, mock_integer, -1)
          end
        end

        should "store blue value in instance variable" do
          mock_integer = stub_everything(:is_a? => true, :< => false, :> => false)
          assert_equal 123, IQ::Color::RGB.new(mock_integer, mock_integer, 123).instance_variable_get('@blue')
        end
      end
    end

    context "red" do
      should "return value of instance variable" do
        mock_integer = stub_everything(:is_a? => true, :< => false, :> => false)
        instance = IQ::Color::RGB.new(mock_integer, mock_integer, mock_integer)
        instance.instance_variable_set '@red', 'the red'
        assert_equal 'the red', instance.red
      end
    end

    context "green" do
      should "return value of instance variable" do
        mock_integer = stub_everything(:is_a? => true, :< => false, :> => false)
        instance = IQ::Color::RGB.new(mock_integer, mock_integer, mock_integer)
        instance.instance_variable_set '@green', 'the green'
        assert_equal 'the green', instance.green
      end
    end

    context "blue" do
      should "return value of instance variable" do
        mock_integer = stub_everything(:is_a? => true, :< => false, :> => false)
        instance = IQ::Color::RGB.new(mock_integer, mock_integer, mock_integer)
        instance.instance_variable_set '@blue', 'the blue'
        assert_equal 'the blue', instance.blue
      end
    end

    context "to_css" do
      should "return colour values as a six digit css hex string" do
        mock_integer = stub_everything(:is_a? => true, :< => false, :> => false)
        instance = IQ::Color::RGB.new(mock_integer, mock_integer, mock_integer)
        instance.stubs(:red).returns(254)
        instance.stubs(:green).returns(220)
        instance.stubs(:blue).returns(186)
        assert_equal '#fedcba', instance.to_css
      end
    end

    context "class methods" do
      context "from_css" do
        should "raise when argument is not a string" do
          not_a_string = stub_everything
          not_a_string.stubs(:is_a?).with(String).returns(false)
          assert_raise(ArgumentError) { IQ::Color::RGB.from_css(not_a_string) }
        end

        should "return new instance for 3 digit hex string" do
          klass = IQ::Color::RGB
          klass.stubs(:new).with(255, 238, 221).returns('the instance')
          assert_equal 'the instance', klass.from_css('#fed')
        end

        should "ignore case when returning new instance for 3 digit hex string" do
          klass = IQ::Color::RGB
          klass.stubs(:new).with(255, 238, 221).returns('the instance')
          assert_equal 'the instance', klass.from_css('#fED')
        end

        should "raise for malformed 3 digit hex string" do
          assert_raise(ArgumentError) { IQ::Color::RGB.from_css('#fzd') }
        end

        should "return new instance for 6 digit hex string" do
          klass = IQ::Color::RGB
          klass.stubs(:new).with(254, 220, 186).returns('the instance')
          assert_equal 'the instance', klass.from_css('#fedcba')
        end

        should "ignore case when returning new instance for 6 digit hex string" do
          klass = IQ::Color::RGB
          klass.stubs(:new).with(254, 220, 186).returns('the instance')
          assert_equal 'the instance', klass.from_css('#fedcba')
        end

        should "raise_for_malformed_6_digit_hex_string" do
          assert_raise(ArgumentError) { IQ::Color::RGB.from_css('#fzdcba') }
        end

        should "raise_given_hex_string_of_wrong_length" do
          assert_raise(ArgumentError) { IQ::Color::RGB.from_css('#febcdaf') }
        end

        should "return new instance for rgb notation string" do
          klass = IQ::Color::RGB
          klass.stubs(:new).with(254, 220, 186).returns('the instance')
          assert_equal 'the instance', klass.from_css('rgb(254,220,186)')
        end

        should "allow spaces before and after values in rgb notation string" do
          klass = IQ::Color::RGB
          klass.stubs(:new).with(254, 220, 186).returns('the instance')
          assert_equal 'the instance', klass.from_css('rgb(  254 ,  220   ,  186  )')
        end

        should "convert percentages in rgb notation to relevant rounded values" do
          klass = IQ::Color::RGB
          klass.stubs(:new).with(67, 38, 220).returns('the instance')
          assert_equal 'the instance', klass.from_css('rgb(26%,15%,86%)')
        end

        should "accept fractional percentages in rgb notation" do
          klass = IQ::Color::RGB
          klass.stubs(:new).with(67, 39, 222).returns('the instance')
          assert_equal 'the instance', klass.from_css('rgb(26.3%,15.2%,86.8%)')
        end

        should "raise when format is unrecognised" do
          assert_raise(ArgumentError) { IQ::Color::RGB.from_css('nonsense') }
        end
      end
    end
  end
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
  "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

  <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
  <meta name="google-site-verification" content="MxsMq6bdLOx0KSuz1MY6yG9ZTIJ7_7DVRfl5NCAT5Yg"/>
  <title>ImageMagick: Exceptions</title>
  <meta http-equiv="content-language" content="en-US"/>
  <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
  <meta http-equiv="reply-to" content="magick-users@imagemagick.org"/>
  <meta name="application-name" content="ImageMagick"/>
  <meta name="description" content="Use ImageMagick to convert, edit, or compose bitmap images in a variety of formats.  In addition resize, rotate, shear, distort and transform images automagically."/>
  <meta name="application-url" content="http://www.imagemagick.org"/>
  <meta name="generator" content="PHP"/>
  <meta name="keywords" content="exceptions, ImageMagick, PerlMagick, image processing, OpenMP, software development library, image, photo, software, Magick++, MagickWand"/>
  <meta name="rating" content="GENERAL"/>
  <meta name="robots" content="INDEX, FOLLOW"/>
  <meta name="generator" content="ImageMagick Studio LLC"/>
  <meta name="author" content="ImageMagick Studio LLC"/>
  <meta name="revisit-after" content="2 DAYS"/>
  <meta name="resource-type" content="document"/>
  <meta name="copyright" content="Copyright (c) 1999-2013 ImageMagick Studio LLC"/>
  <meta name="distribution" content="Global"/>
  <link rel="icon" href="../images/wand.png"/>
  <link rel="shortcut icon" href="../images/wand.ico"  type="images/x-icon"/>
  <link rel="canonical" href="http://www.imagemagick.org" />
  <link rel="meta" type="application/rdf+xml" title="ICI" href="http://imagemagick.org/ici.rdf"/>

  <link rel="stylesheet" href="http://www.imagemagick.org/fancybox/jquery.fancybox.css?v=2.0.4" type="text/css" media="screen" />

  <link rel="stylesheet" href="http://www.imagemagick.org/fancybox/helpers/jquery.fancybox-buttons.css?v=2.0.4" type="text/css" media="screen" />

  <link rel="stylesheet" href="http://www.imagemagick.org/fancybox/helpers/jquery.fancybox-thumbs.css?v=2.0.4" type="text/css" media="screen" />

  <link rel="stylesheet" href="http://www.google.com/cse/style/look/default.css" type="text/css" />

  About ImageMagick

  Binary Releases

    Unix

    Mac OS X

    iOS

    Windows

  Command-line Tools

    Processing

    Options

    Usage

  Program Interfaces

    MagickWand

    MagickCore

    PerlMagick

    Magick++

   Install from Source

    Unix

    Windows

  Resources

  Architecture

  Download

  Search

  Site Map

  Links

  Sponsors:

  The Fastest & Easiest Way to Find Images

  VPS

  Werbebanner Werbeplane

  Entertainment News & Photos

  LED24

  Best Website Hosting

  Android Tablet

  Web Site Hosting

   Premium Quality Stock Photos

   Druckerei

  Managed Server

  Druckerei

   Kaffeemaschinen reparatur

   Waschmaschinen Reparatur Berlin

ImageMagick Exceptions

ImageMagick returns a status of 0 whenever a command or algorithm successfully complete without complaint.  A warning code generally is typically just a notice that something unusual occurred but the command or algorithm still completed and most likely the results are still usable.  An error means the command or algorithm could not complete as expected and any results are unreliable.  A fatal error means the command or algorithm could not complete and the process exits prematurely and no results are returned.

ImageMagick Error and Warning Codes

    Domain
    Description
    Warning
    Error
    Fatal Error

    Success
    the command or algorithm completed successfully without complaint
    0
    0
    0

    Resource Limit
    a program resource is exhausted (e.g. not enough memory)
    300
    400
    700

    Type
    A font is unavailable; a substitution may have occurred
    305
    405
    705

    Option
    a command-line option was malformed
    310
    410
    710

    Delegate
    an ImageMagick delegate failed to complete
    315
    415
    715

    Missing Delegate
    the image type can not be read or written because the appropriate Delegate is missing
    320
    420
    720

    Corrupt Image
    the image file may be corrupt
    325
    425
    725

    FileOpen
    the image file could not be opened for reading or writing
    330
    430
    730

    Blob
    a binary large object could not be allocated, read, or written
    335
    435
    735

    Stream
    there was a problem reading or writing from a stream
    340
    440
    740

    Cache
    pixels could not be read or written to the pixel cache
    345
    445
    745

    Coder
    there was a problem with an image coder
    350
    450
    750

    Module
    there was a problem with an image module
    355
    455
    755

    Draw
    a drawing operation failed
    360
    460
    760

    Image
    the operation could not complete due to an incompatible image
    365
    465
    765

    Wand
    there was a problem specific to the MagickWand API
    370
    470
    770

    Random
    there is a problem generating a true or pseudo-random number
    375
    475
    775

    XServer
    an X resource is unavailable
    380
    480
    780

    Monitor
    there was a problem activating the progress monitor
    385
    485
    785

    Registry
    there was a problem getting or setting the registry
    390
    490
    790

    Configure
    there was a problem getting a configuration file
    395
    495
    795

    Policy
    a policy denies access to a delegate, coder, filter, path, or resource.
    399
    499
    799

      Discourse Server •
      Studio

    © 1999-2013 ImageMagick Studio LLC
     Contact the Wizards

redpajama_set_name: RedPajamaGithub


text:
In response to [Christopher Burke's answer](http://qr.ae/RCI2cL) to the question ['What is the difference between a programmer, a good programmer, and a great programmer?'](http://www.quora.com/What-is-the-difference-between-a-programmer-a-good-programmer-and-a-great-programmer) we have built this technical challenge to assess where you are at after six weeks.

The details of the challenge are included below. Hints are included in the Guidelines.md file. Do your best to complete the challenge independently, without the hints or guidelines. However, use them if you are stuck for 20 minutes.

## The Challenge

Fork this repository. Complete the challenge, push your version with a clear commit history to your own Github profile.

Write a Pair Randomizer application that takes a list of objects and pairs them together. Potential use cases may be creating an app for Pair Programming teams, or matching people for a Secret Santa gift exchange. Add the following features:

1. Add entities to a list
2. Edit the entities
3. Display a list of the added entities, with some visible annotation to convey that two of the entities have been paired together
4. Include a button that allows me to randomize the list
5. Persist the list of entities

Take as much time as needed to complete the challenge. Add a note at the bottom of this README.md file with how long it took you to complete the challenge.

Example:

```Completed in 2.5 hours.```


text:
layout: post
microblog: true
date: 2009-12-30 03:00 +0300
guid: http://desparoz.micro.blog/2009/12/30/t7182561525.html
---
True RT @tonyrobbins: "Have u ever noticed that anybody driving slower than u is an idiot & anyone going faster than u is a maniac?"G Carlin


text:
<?php

if ( !defined( 'MEDIAWIKI' ) ) {
	exit;
}

$dir = __DIR__;
require_once $dir . '/ConfirmEdit.php';
$wgCaptchaClass = 'QuestyCaptcha';

global $wgCaptchaQuestions;
$wgCaptchaQuestions = array();

// Add your questions in LocalSettings.php using this format
// $wgCaptchaQuestions[] = array( 'question' => "A question?", 'answer' => "An answer!" );
// $wgCaptchaQuestions[] = array( 'question' => 'How much wood would a woodchuck chuck if a woodchuck could chuck wood?', 'answer' => 'as much wood as...' );
// $wgCaptchaQuestions[] = array( 'question' => "What is this wiki's name?", 'answer' => "$wgSitename" );
// You can also provide several acceptable answers to a given question (the answers shall be in lowercase):
// $wgCaptchaQuestions[] = array( 'question' => "2 + 2 ?", 'answer' => array( '4', 'four' ) );

$wgExtensionMessagesFiles['QuestyCaptcha'] = $dir . '/QuestyCaptcha.i18n.php';
$wgAutoloadClasses['QuestyCaptcha'] = $dir . '/QuestyCaptcha.class.php';


text:
package com.rollsoftware.br.accountmanager.db.service;

import com.rollsoftware.br.accountmanager.db.entity.LoginInfo;
import com.rollsoftware.br.accountmanager.db.entity.ObjectInterface;
import com.rollsoftware.br.accountmanager.db.entity.TokenInfo;
import com.rollsoftware.br.test.util.EntityManagerInterface;
import java.sql.SQLException;
import java.util.Calendar;
import javax.persistence.EntityManager;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;

/**
 *
 * @author Rogério
 * @date October, 2016
 */
public class TokenInfoServiceTest extends ObjectDataServiceTest {

    private Object loginInfoPKSaved;

    public TokenInfoServiceTest(EntityManagerInterface emInterface) {
        super(emInterface);
    }

    @Override
    public <T extends ObjectInterface> T load(Object id) {
        return (T) load(TokenInfo.class, id);
    }

    @Override
    public <T extends ObjectInterface> T load(EntityManager em, Object id) {
        return (T) load(em, TokenInfo.class, id);
    }

    private Object saveLoginInfo() {

        LoginInfo loginInfo = new LoginInfo();

        loginInfo.setUUID("uuid" + Math.random());
        loginInfo.setType("type");

        loginInfo.setUser("user" + Math.random());
        loginInfo.setPass("pass" + Math.random());
        loginInfo.setFirstName("firstName" + Math.random());
        loginInfo.setLastName("lastName" + Math.random());

        save(loginInfo);

        System.out.println("Save LoginInfo: " + loginInfo.getUUID());

        return loginInfo.getUUID();
    }

    @Override
    protected ObjectInterface createObjectInterface() {

        loginInfoPKSaved = saveLoginInfo();

        LoginInfo loginInfo = load(LoginInfo.class, loginInfoPKSaved);

        TokenInfo tokenInfo = new TokenInfo();

        tokenInfo.setUUID("uuid" + Math.random());
        tokenInfo.setType("type");

        tokenInfo.setAccessToken("accessToken" + Math.random());
        tokenInfo.setUserIP("userIP" + Math.random());

        Calendar instance = Calendar.getInstance();

        instance.add(Calendar.MINUTE, 10);

        tokenInfo.setDateCreated(Calendar.getInstance().getTime());
        tokenInfo.setDateAccessed(Calendar.getInstance().getTime());
        tokenInfo.setDateExpires(instance.getTime());

        tokenInfo.setLoginInfo(loginInfo);

        return tokenInfo;
    }

    @Override
    protected <T extends AbstractServiceFacade>
            T createServiceFacade(EntityManager em) {
        return (T) new TokenInfoService(em);
    }

    @BeforeClass
    public static void setUpClass() {
        ObjectDataServiceTest.setUpClass();
    }

    @AfterClass
    public static void tearDownClass() {
        ObjectDataServiceTest.setUpClass();
    }

    @Before
    @Override
    public void setUp() throws SQLException {
        super.setUp();
    }

    @After
    @Override
    public void tearDown() throws SQLException {
        super.tearDown();
    }
}


text:
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#main-nav-bar" aria-expanded="false">
                Toggle navigation

            </button>
            watchmen

                <% if (user && user.isAdmin) { %>

                    Add New Service

                <% } %>
                <% if (user) { %>

                        <img src="//www.gravatar.com/avatar/<%=user.emailHash%>?s=20"/>

Logout <%=user.email%>

                <% } else { %>

                      Sign In with Google

                <% } %>


text:
<?php namespace Lokielse\AdminGenerator\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Finder\Finder;

class CreateEntityCommand extends Command
{

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'admin:entity:new';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate an entity.';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire()
    {
        $instance  = $this->argument('instance');
        $template  = $this->option('template');
        $force     = $this->option('force');
        $merge     = $this->option('merge');
        $namespace = config('admin-generator.namespace');
        $engine    = config("admin-generator.instances.{$instance}.engine");

        if ( ! $namespace) {
            $this->error("The config 'namespace' in 'config/admin-generator.php' can not be empty, general set it to 'console'");
            exit;
        }

        if ( ! config("admin-generator.instances.{$instance}")) {
            $this->warn("The instance '{$instance}' is not exist, check the typo or add it to config/admin-generator.php first");
            exit;
        }

        if ( ! $engine) {
            $this->warn("The engine of instance '{$instance}' is not exist, check the typo or add it to config/admin-generator.php first");
        }

        $templates = $this->getTemplates($template, $merge, $engine);

        $files = $this->getMergedFiles($templates, $engine);

        $filesystem = new Filesystem();

        foreach ($files as $src) {
            $destName = $this->getFileDest($src, $engine);

            $destName = $this->replaceKeyword($destName);

            if (is_file($destName) && ! $force) {
                $this->error(sprintf("The file %s is already exist, use option '--force' to override it", str_replace(base_path() . '/', '', $destName)));
                exit;
            } else {
                $this->info(sprintf("Copying file to %s", str_replace(base_path() . '/', '', $destName)));
            }

            $content  = $filesystem->get($src);
            $replaced = $this->replaceKeyword($content);

            $filesystem->put($destName, $replaced);
        }

        $this->warn('Done! Please config route and menu in app.coffee and MenuController.coffee');
    }

    public function getFileDest($file, $engine)
    {
        $templatePath = $this->getTemplatePath($engine);
        $path         = preg_replace("#^$templatePath/[^/]+/#", '', $file);

        return base_path("{$path}");
    }

    protected function getMergedFiles($templates, $engine)
    {
        $names  = [ ];

        foreach ($templates as $n => $template) {
            $path = $this->getTemplateDir($template, $engine);

            $finder = new Finder();

            foreach ($finder->in($path) as $file) {
                /**
                 * @var \SplFileInfo $file
                 */
                if ($file->isFile()) {
                    $add = true;

                    for ($k = $n + 1; $k < count($templates); $k++) {
                        if ($this->fileExistInTemplate($path, $file, $engine, $templates[$k])) {
                            $add = false;
                            break;
                        }
                    }

                    if ($add) {
                        $names[] = $file->getPathname();
                    }
                }
            }
        }

        return $names;
    }

    protected function fileExistInTemplate($path, \SplFileInfo $file, $engine, $template)
    {
        $uri = str_replace($path, '',$file->getRealPath());
        $base = $this->getTemplateDir($template, $engine);

        $filename = $base.$uri;

        return is_file($filename);
    }

    protected function getTemplateDir($template, $engine)
    {
        $templatePath = $this->getTemplatePath($engine);

        return "{$templatePath}/{$template}";
    }

    public function getRelativeNameInDir($templatePath)
    {
        $finder = new Finder();
        $names  = [ ];

        foreach ($finder->name('*')->in(base_path($templatePath)) as $file) {
            /**
             * @var \SplFileInfo $file
             */
            if ($file->isFile()) {
                $names[] = str_replace(base_path($templatePath), '', $file->getPathname());
            }
        }

        return $names;
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return [
            [ 'entity', InputArgument::REQUIRED, 'The entity name.' ],
            [ 'instance', InputArgument::REQUIRED, 'The instance name.' ],
        ];
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return [
            [ 'template', 't', InputOption::VALUE_OPTIONAL, 'The template name', 'default' ],
            [ 'force', 'f', InputOption::VALUE_NONE, 'To override an exists file' ],
            [ 'merge', 'm', InputOption::VALUE_OPTIONAL, 'To merge with default template', 1 ]
        ];
    }

    protected function replaceKeyword($content)
    {
        $namespace = camel_case(config('admin-generator.namespace'));
        $instance  = camel_case($this->argument('instance'));
        $entity    = camel_case($this->argument('entity'));

        $replaced = preg_replace([
            '#_theNamespace_#',
            '#_theNamespaces_#',
            '#_the-namespace_#',
            '#_the_namespace_#',
            '#_the-namespaces_#',
            '#_the_namespaces_#',
            '#_TheNamespace_#',
            '#_TheNamespaces_#',
            /**/
            '#_theInstance_#',
            '#_theInstances_#',
            '#_the-instance_#',
            '#_the_instance_#',
            '#_the-instances_#',
            '#_the_instances_#',
            '#_TheInstance_#',
            '#_TheInstances_#',
            /**/
            '#_theEntity_#',
            '#_theEntities_#',
            '#_the-entity_#',
            '#_the_entity_#',
            '#_the-entities_#',
            '#_the_entities_#',
            '#_TheEntity_#',
            '#_TheEntities_#',
        ], [
            camel_case($namespace),
            camel_case(str_plural($namespace)),
            snake_case($namespace, '-'),
            snake_case($namespace, '_'),
            snake_case(str_plural($namespace), '-'),
            snake_case(str_plural($namespace), '_'),
            ucfirst(camel_case($namespace)),
            ucfirst(camel_case(str_plural($namespace))),
            /**/
            camel_case($instance),
            camel_case(str_plural($instance)),
            snake_case($instance, '-'),
            snake_case($instance, '_'),
            snake_case(str_plural($instance), '-'),
            snake_case(str_plural($instance), '_'),
            ucfirst(camel_case($instance)),
            ucfirst(camel_case(str_plural($instance))),
            /**/
            camel_case($entity),
            camel_case(str_plural($entity)),
            snake_case($entity, '-'),
            snake_case($entity, '_'),
            snake_case(str_plural($entity), '-'),
            snake_case(str_plural($entity), '_'),
            ucfirst(camel_case($entity)),
            ucfirst(camel_case(str_plural($entity))),
        ], $content);

        return $replaced;
    }

    /**
     * @return mixed|string
     */
    protected function getTemplatePath($engine)
    {
        $templatePath = config('admin-generator.templates_path', base_path('resources/admin-templates'));
        $templatePath = rtrim($templatePath, '/') . '/' . $engine;

        return $templatePath;
    }

    /**
     * @param $template
     * @param $merge
     *
     * @return array
     *
     * @internal param $engine
     *
     */
    protected function getTemplates($template, $merge)
    {
        $templates = explode(',', $template);

        if ($merge) {
            array_unshift($templates, 'default');
        }

        $templates = array_unique($templates);

        return $templates;
    }

}


text:
#ifndef __jsb_chipmunk_manual
#define __jsb_chipmunk_manual

#import "jsb_config.h"
#ifdef JSB_INCLUDE_CHIPMUNK

#include "chipmunk.h"
#include "jsapi.h"

#import "jsb_chipmunk_auto_classes.h"

// Free Functions
JSBool JSB_cpSpaceAddCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp);
JSBool JSB_cpSpaceRemoveCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp);

JSBool JSB_cpArbiterGetBodies(JSContext *cx, uint32_t argc, jsval *vp);
JSBool JSB_cpArbiterGetShapes(JSContext *cx, uint32_t argc, jsval *vp);

// poly related
JSBool JSB_cpAreaForPoly(JSContext *cx, uint32_t argc, jsval *vp);
JSBool JSB_cpMomentForPoly(JSContext *cx, uint32_t argc, jsval *vp);
JSBool JSB_cpCentroidForPoly(JSContext *cx, uint32_t argc, jsval *vp);
JSBool JSB_cpRecenterPoly(JSContext *cx, uint32_t argc, jsval *vp);

// "Methods" from the OO API
JSBool JSB_cpSpace_addCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp);
JSBool JSB_cpSpace_removeCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp);

// manually wrapped for rooting/unrooting purposes
JSBool JSB_cpSpace_addBody(JSContext *cx, uint32_t argc, jsval *vp);
JSBool JSB_cpSpace_addConstraint(JSContext *cx, uint32_t argc, jsval *vp);
JSBool JSB_cpSpace_addShape(JSContext *cx, uint32_t argc, jsval *vp);
JSBool JSB_cpSpace_addStaticShape(JSContext *cx, uint32_t argc, jsval *vp);
JSBool JSB_cpSpace_removeBody(JSContext *cx, uint32_t argc, jsval *vp);
JSBool JSB_cpSpace_removeConstraint(JSContext *cx, uint32_t argc, jsval *vp);
JSBool JSB_cpSpace_removeShape(JSContext *cx, uint32_t argc, jsval *vp);
JSBool JSB_cpSpace_removeStaticShape(JSContext *cx, uint32_t argc, jsval *vp);

JSBool JSB_cpArbiter_getBodies(JSContext *cx, uint32_t argc, jsval *vp);
JSBool JSB_cpArbiter_getShapes(JSContext *cx, uint32_t argc, jsval *vp);

JSBool JSB_cpBody_constructor(JSContext *cx, uint32_t argc, jsval *vp);
JSBool JSB_cpBody_getUserData(JSContext *cx, uint32_t argc, jsval *vp);
JSBool JSB_cpBody_setUserData(JSContext *cx, uint32_t argc, jsval *vp);

// convertions

jsval JSB_jsval_from_cpBB(JSContext *cx, cpBB bb );
JSBool JSB_jsval_to_cpBB( JSContext *cx, jsval vp, cpBB *ret );
JSBool JSB_jsval_to_array_of_cpvect( JSContext *cx, jsval vp, cpVect**verts, int *numVerts);

// requires cocos2d
#define JSB_jsval_from_cpVect JSB_jsval_from_CGPoint
#define JSB_jsval_to_cpVect JSB_jsval_to_CGPoint

// Object Oriented Chipmunk
void JSB_cpBase_createClass(JSContext* cx, JSObject* globalObj, const char * name );
extern JSObject* JSB_cpBase_object;
extern JSClass* JSB_cpBase_class;

// Manual constructor / destructors
JSBool JSB_cpPolyShape_constructor(JSContext *cx, uint32_t argc, jsval *vp);
void JSB_cpSpace_finalize(JSFreeOp *fop, JSObject *obj);

#endif // JSB_INCLUDE_CHIPMUNK

#endif // __jsb_chipmunk_manual


text:
import { ChangeDetectionStrategy, Component } from '@angular/core';

@Component({
  selector: 'nb-card-colors',
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: './card-colors.component.html',
})
export class CardColorsComponent {
}


text:
The command to send a message to the UDP server that is running on localhost (127.0.0.1) will look like this:

```shell
echo -e 'SN-001,default,temperature,25.7,humidity,69' | nc -q1 -w1 -u 127.0.0.1 11560
```
{: .copy-code}


text:
exports.description = 'Displays general help info or info about a specific command.';

exports.usage = '[command]';

exports.options = {
    command: {
        noName: true,
        description: 'Get more information about a specific command.',
        type: 'string'
    }
};

exports.invoke = function (shell, options) {
    var cmdNames = [];

    // Populate cmdNames with all command module names and sort the array alphabetically.
    for (var key in shell.cmds) {
        var cmd = shell.cmds[key];
        if (cmd && cmd.access(shell, key))
            cmdNames.push(key);
    }
    cmdNames.sort();

    shell.log();

    // If no command was passed in as an argument to the help command then display the generic help menu listing all available commands.
    if (!options.command) {

        // Calculate the length of the largest command name for formatting purposes.
        var maxLength = 0;
        for (var index = 0; index < cmdNames.length; index++) {
            var cmdName = cmdNames[index];
            maxLength = cmdName.length > maxLength ? cmdName.length : maxLength;
        }

        // Iterate over all command modules and add a line of text with the command name and description.
        var inverted = false;
        for (var index = 0; index < cmdNames.length; index++) {
            var cmdName = cmdNames[index],
                cmd = shell.cmds[cmdName],
                helpStr = cmdName;
            if (cmd.description) {
                helpStr += new Array((maxLength - cmdName.length) + 7).join(' ');
                helpStr += cmd.description;
            }

            // If the command is not hidden then add the line.
            // If there are 5 commands or less then type the lines character by character.
            // If there are more than 5 commands then do not type them out as it takes too long and the effect isn't worth the wait.
            if (!cmd.hidden) {
                var lineOptions = { dontType: cmdNames.length > 5, inverted: inverted };
                inverted = !inverted;
                shell.log(helpStr, lineOptions);
            }
        }
        shell.log();
    }
    // If a command was passed in as an argument to the help command then display more specific help information for the specified command.
    else {
        var cmd = shell.cmds[options.command];
        if (!cmd)
            shell.error(options.command + ' is not a valid command name.');
        else {

            var firstLine = options.command;
            // If a "usage key" is specified then display it.
            if (cmd.usage)
                firstLine += ' ' + cmd.usage;
            shell.log(firstLine, { bold: true });
            shell.log();

            // Display the command's description if it has one.
            if (cmd.description) {
                shell.log(cmd.description);
                shell.log();
            }

            // If the command defines options that it recognizes then iterate over those and display information about them.
            if (cmd.options) {
                var strs = [],
                    maxLength = 0;
                for (var key in cmd.options) {
                    var option = cmd.options[key];
                    if (!option.hidden) {
                        var optionStr = (key.length > 1 ? '--' : '-') + key;
                        if (option.aliases) {
                            var aliases = option.aliases;
                            if (typeof(aliases) === 'string')
                                aliases = aliases.toString().replace(/, /, ',').split(',');
                            aliases.forEach(function (alias) {
                                optionStr += ',' + (alias.length > 1 ? '--' : '-') + alias;
                            });
                        }
                        strs.push({ option: option, str: optionStr});
                        maxLength = optionStr.length > maxLength ? optionStr.length : maxLength;
                    }
                }
                if (strs.length > 0) {
                    shell.log('Options:');
                    shell.log();
                    for (var index = 0; index < strs.length; index++) {
                        var option = strs[index].option,
                            optionStr = strs[index].str;
                        if (option.description) {
                            optionStr += new Array((maxLength - optionStr.length) + 5).join(' ');
                            optionStr += option.description;
                        }
                        shell.log(optionStr, { dontType: true });
                    }
                    shell.log();
                }
            }
        }
    }
};


text:
/*
 * ConnectedComponents.cpp
 *
 *  Created on: Dec 16, 2013
 *      Author: cls
 */

#include <set>

#include "ConnectedComponents.h"
#include "../structures/Partition.h"
#include "../auxiliary/Log.h"

namespace NetworKit {

ConnectedComponents::ConnectedComponents(const Graph& G) : G(G), hasRun(false) {
	if (G.isDirected()) {
		throw std::runtime_error("Error, connected components of directed graphs cannot be computed, use StronglyConnectedComponents for them.");
	}
}

void ConnectedComponents::run() {
	DEBUG("initializing labels");
	component = Partition(G.upperNodeIdBound(), none);
	numComponents = 0;

	// perform breadth-first searches
	G.forNodes([&](node u) {
		if (component[u] == none) {
			component.setUpperBound(numComponents+1);
			index c = numComponents;
			G.BFSfrom(u, [&](node v) {
				component[v] = c;
			});
			assert (component[u] != none);
			++numComponents;
		}
	});

	hasRun = true;
}

Partition ConnectedComponents::getPartition() {
	if (!hasRun) throw std::runtime_error("run method has not been called");
	return this->component;
}

std::vector<std::vector<node> > ConnectedComponents::getComponents() {
	if (!hasRun) throw std::runtime_error("run method has not been called");

	// transform partition into vector of unordered_set
	std::vector<std::vector<node> > result(numComponents);

	G.forNodes([&](node u) {
		result[component[u]].push_back(u);
	});

	return result;
}

std::map<index, count> ConnectedComponents::getComponentSizes() {
	if (!hasRun) throw std::runtime_error("run method has not been called");
	return this->component.subsetSizeMap();
}

}


text:
require 'spec_helper'

describe BooleanValidator do
  before(:all) do
    class UserWithBoolean < ActiveRecord::Base
      self.table_name = 'mocked_users'

      validates :active, boolean: true
    end
  end

  let(:user) { UserWithBoolean.new }

  it 'does no accept invalid boolean values' do
    user.active = 'invalid'

    user.should_not be_valid
  end

  it 'accepts "true" as a valid value' do
    user.active = 'true'

    user.should be_valid
  end

  it 'accepts "false" as a valid value' do
    user.active = 'false'

    user.should be_valid
  end

  it 'accepts "0" as a valid value' do
    user.active = '0'

    user.should be_valid
  end

  it 'accepts "1" as a valid value' do
    user.active = 'true'

    user.should be_valid
  end

  it 'accepts true as a valid value' do
    user.active = true

    user.should be_valid
  end

  it 'accepts false as a valid value' do
    user.active = false

    user.should be_valid
  end

  it 'accepts nil as a valid value' do
    user.active = nil

    user.should be_valid
  end
end


text:
module VirtualBox
  # Represents the BIOS settings of a {VM}.
  class BIOS < AbstractModel
    attribute :parent, :readonly => true, :property => false
    attribute :acpi_enabled, :boolean => true
    attribute :io_apic_enabled, :boolean => true

    class << self
      # Populates a relationship with another model.
      #
      # **This method typically won't be used except internally.**
      #
      # @return [BIOS]
      def populate_relationship(caller, imachine)
        data = new(caller, imachine.bios_settings)
      end

      # Saves the relationship.
      #
      # **This method typically won't be used except internally.**
      def save_relationship(caller, instance)
        instance.save
      end
    end

    def initialize(parent, bios_settings)
      write_attribute(:parent, parent)

      # Load the attributes and mark the whole thing as existing
      load_interface_attributes(bios_settings)
      clear_dirty!
      existing_record!
    end

    def validate
      super

      validates_inclusion_of :acpi_enabled, :io_apic_enabled, :in => [true, false]
    end

    def save
      parent.with_open_session do |session|
        machine = session.machine

        # Save them
        save_changed_interface_attributes(machine.bios_settings)
      end
    end
  end
end


text:
package org.elasticsearch.xpack.ilm.action;

import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.action.RestToXContentListener;
import org.elasticsearch.xpack.core.ilm.action.MoveToStepAction;

import java.io.IOException;

public class RestMoveToStepAction extends BaseRestHandler {

    public RestMoveToStepAction(RestController controller) {
        controller.registerHandler(RestRequest.Method.POST,"/_ilm/move/{name}", this);
    }

    @Override
    public String getName() {
        return "ilm_move_to_step_action";
    }

    @Override
    protected RestChannelConsumer prepareRequest(RestRequest restRequest, NodeClient client) throws IOException {
        String index = restRequest.param("name");
        XContentParser parser = restRequest.contentParser();
        MoveToStepAction.Request request = MoveToStepAction.Request.parseRequest(index, parser);
        request.timeout(restRequest.paramAsTime("timeout", request.timeout()));
        request.masterNodeTimeout(restRequest.paramAsTime("master_timeout", request.masterNodeTimeout()));
        return channel -> client.execute(MoveToStepAction.INSTANCE, request, new RestToXContentListener<>(channel));
    }
}


text:
package org.apache.hadoop.yarn.server.nodemanager.amrmproxy;

import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION;
import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION;

import java.io.File;
import java.io.IOException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.ipc.Server;
import org.apache.hadoop.minikdc.MiniKdc;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.registry.client.api.RegistryOperations;
import org.apache.hadoop.registry.client.impl.FSRegistryOperationsService;
import org.apache.hadoop.security.SaslRpcServer.AuthMethod;
import org.apache.hadoop.security.SecurityUtil;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.authorize.PolicyProvider;
import org.apache.hadoop.security.authorize.ProxyUsers;
import org.apache.hadoop.security.authorize.Service;
import org.apache.hadoop.yarn.api.ApplicationClientProtocol;
import org.apache.hadoop.yarn.api.ApplicationClientProtocolPB;
import org.apache.hadoop.yarn.api.protocolrecords.AllocateRequest;
import org.apache.hadoop.yarn.api.protocolrecords.AllocateResponse;
import org.apache.hadoop.yarn.api.protocolrecords.FinishApplicationMasterRequest;
import org.apache.hadoop.yarn.api.protocolrecords.FinishApplicationMasterResponse;
import org.apache.hadoop.yarn.api.protocolrecords.RegisterApplicationMasterRequest;
import org.apache.hadoop.yarn.api.protocolrecords.RegisterApplicationMasterResponse;
import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
import org.apache.hadoop.yarn.api.records.Container;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.FinalApplicationStatus;
import org.apache.hadoop.yarn.api.records.ResourceRequest;
import org.apache.hadoop.yarn.api.records.Token;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.ApplicationMasterNotRegisteredException;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.ipc.YarnRPC;
import org.apache.hadoop.yarn.security.AMRMTokenIdentifier;
import org.apache.hadoop.yarn.server.MockResourceManagerFacade;
import org.apache.hadoop.yarn.server.federation.policies.manager.UniformBroadcastPolicyManager;
import org.apache.hadoop.yarn.server.federation.store.impl.MemoryFederationStateStore;
import org.apache.hadoop.yarn.server.federation.store.records.SubClusterId;
import org.apache.hadoop.yarn.server.federation.store.records.SubClusterInfo;
import org.apache.hadoop.yarn.server.federation.store.records.SubClusterRegisterRequest;
import org.apache.hadoop.yarn.server.federation.store.records.SubClusterState;
import org.apache.hadoop.yarn.server.federation.utils.FederationStateStoreFacade;
import org.apache.hadoop.yarn.server.nodemanager.Context;
import org.apache.hadoop.yarn.server.nodemanager.NodeManager.NMContext;
import org.apache.hadoop.yarn.server.nodemanager.recovery.NMMemoryStateStoreService;
import org.apache.hadoop.yarn.server.nodemanager.recovery.NMStateStoreService;
import org.apache.hadoop.yarn.util.Records;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TestFederationInterceptorSecure extends BaseAMRMProxyTest {

  private static final Logger LOG = LoggerFactory.getLogger(TestFederationInterceptor.class);

  public static final String HOME_SC_ID = "SC-home";
  public static final String SC_ID1 = "SC-1";
  private static final String HOME_RM_ADDRESS = "127.0.0.1:28032";

  private YarnConfiguration conf;
  private TestableFederationInterceptor interceptor;
  private MemoryFederationStateStore stateStore;
  private NMStateStoreService nmStateStore;
  private RegistryOperations registry;

  private Context nmContext;
  private int testAppId;
  private ApplicationAttemptId attemptId;
  private volatile int lastResponseId;

  private MockResourceManagerFacade mockHomeRm = null;
  private Server homeClientRMRpcServer;

  private static File workDir;
  private static final File TEST_ROOT_DIR =
      new File(System.getProperty("test.build.dir", "target/test-dir"),
          TestFederationInterceptorSecure.class.getName() + "-root");
  private static MiniKdc miniKDC;
  private static String serverUserName = "yarn";
  private static String serverPrincipal;
  private static File serverKeytab;

  @ClassRule
  public final static TemporaryFolder FOLDER = new TemporaryFolder();

  @BeforeClass
  public static void setUpCluster() throws Exception {
    miniKDC = new MiniKdc(MiniKdc.createConf(), TEST_ROOT_DIR);
    miniKDC.start();

    workDir = FOLDER.getRoot();
    serverKeytab = new File(workDir, "yarn.keytab");
    serverPrincipal =
        serverUserName + "/" + (Path.WINDOWS ? "127.0.0.1" : "localhost") + "@EXAMPLE.COM";
    miniKDC.createPrincipal(serverKeytab, serverPrincipal);
  }

  @AfterClass
  public static void tearDownCluster() {
    if (miniKDC != null) {
      miniKDC.stop();
    }
    if (FOLDER != null) {
      FOLDER.delete();
    }
  }

  @Override
  public void setUp() throws IOException {
    super.setUp();

    stateStore = new MemoryFederationStateStore();
    stateStore.init(conf);
    FederationStateStoreFacade.getInstance().reinitialize(stateStore, conf);

    nmStateStore = new NMMemoryStateStoreService();
    nmStateStore.init(conf);
    nmStateStore.start();

    registry = new FSRegistryOperationsService();
    registry.init(conf);
    registry.start();

    testAppId = 1;
    attemptId = getApplicationAttemptId(testAppId);
    nmContext = new NMContext(null, null, null, null, nmStateStore, false, conf);
    lastResponseId = 0;
    this.mockHomeRm = new MockResourceManagerFacade(new YarnConfiguration(conf), 0);

    // Login as NodeManager
    conf.set(YarnConfiguration.NM_KEYTAB, this.serverKeytab.getAbsolutePath());
    conf.set(YarnConfiguration.NM_PRINCIPAL, this.serverPrincipal);
    SecurityUtil.login(conf, YarnConfiguration.NM_KEYTAB, YarnConfiguration.NM_PRINCIPAL);

    // start rpc server
    startRpcServer();
  }

  private void startRpcServer() {
    YarnRPC rpc = YarnRPC.create(conf);
    this.homeClientRMRpcServer = rpc.getServer(ApplicationClientProtocol.class, mockHomeRm,
        NetUtils.createSocketAddr(HOME_RM_ADDRESS), conf, null, 2);
    this.homeClientRMRpcServer.start();
    this.homeClientRMRpcServer.refreshServiceAcl(conf, new MockRMPolicyProvider());
  }

  private void stopRpcServer() {
    if (homeClientRMRpcServer != null) {
      homeClientRMRpcServer.stop();
    }
  }

  @Override
  public void tearDown() {
    interceptor.cleanupRegistry();
    interceptor.shutdown();
    registry.stop();
    stopRpcServer();
    super.tearDown();
  }

  @Override
  protected YarnConfiguration createConfiguration() {
    conf = new YarnConfiguration();
    conf.setBoolean(YarnConfiguration.AMRM_PROXY_ENABLED, true);
    conf.setBoolean(YarnConfiguration.FEDERATION_ENABLED, true);
    String mockPassThroughInterceptorClass =
        PassThroughRequestInterceptor.class.getName();

    // Create a request interceptor pipeline for testing. The last one in the
    // chain is the federation interceptor that calls the mock resource manager.
    // The others in the chain will simply forward it to the next one in the
    // chain
    conf.set(YarnConfiguration.AMRM_PROXY_INTERCEPTOR_CLASS_PIPELINE,
        mockPassThroughInterceptorClass + "," + mockPassThroughInterceptorClass
            + "," + TestableFederationInterceptor.class.getName());

    conf.set(YarnConfiguration.FEDERATION_POLICY_MANAGER,
        UniformBroadcastPolicyManager.class.getName());

    conf.set(YarnConfiguration.RM_CLUSTER_ID, HOME_SC_ID);

    // Disable StateStoreFacade cache
    conf.setInt(YarnConfiguration.FEDERATION_CACHE_TIME_TO_LIVE_SECS, 0);

    // Set sub-cluster timeout to 500ms
    conf.setLong(YarnConfiguration.FEDERATION_AMRMPROXY_SUBCLUSTER_TIMEOUT, 500);

    // Enable security mode
    conf.set(HADOOP_SECURITY_AUTHENTICATION, AuthMethod.KERBEROS.toString());
    conf.setBoolean(HADOOP_SECURITY_AUTHORIZATION, true);
    UserGroupInformation.setConfiguration(conf);
    conf.set("hadoop.proxyuser.yarn.hosts", "*");
    conf.set("hadoop.proxyuser.yarn.groups", "*");
    ProxyUsers.refreshSuperUserGroupsConfiguration(conf, ProxyUsers.CONF_HADOOP_PROXYUSER);
    conf.set(YarnConfiguration.RM_PRINCIPAL, serverPrincipal);

    return conf;
  }

  private void registerSubCluster(SubClusterId subClusterId)
      throws YarnException {
    if (subClusterId.getId().equals(HOME_SC_ID)) {
      stateStore.registerSubCluster(SubClusterRegisterRequest.newInstance(SubClusterInfo
          .newInstance(subClusterId, "1.2.3.4:1", HOME_RM_ADDRESS, "1.2.3.4:3", "1.2.3.4:4",
              SubClusterState.SC_RUNNING, 0, "capacity")));
    } else {
      stateStore.registerSubCluster(SubClusterRegisterRequest.newInstance(SubClusterInfo
          .newInstance(subClusterId, "1.2.3.4:1", "1.2.3.4:2", "1.2.3.4:3", "1.2.3.4:4",
              SubClusterState.SC_RUNNING, 0, "capacity")));
    }
  }

  private List<Container> getContainersAndAssert(int numberOfResourceRequests,
      int numberOfAllocationExcepted) throws Exception {
    AllocateRequest allocateRequest = Records.newRecord(AllocateRequest.class);
    List<Container> containers = new ArrayList<Container>(numberOfResourceRequests);
    List<ResourceRequest> askList = new ArrayList<ResourceRequest>(numberOfResourceRequests);
    for (int id = 0; id < numberOfResourceRequests; id++) {
      askList.add(createResourceRequest("test-node-" + Integer.toString(id), 6000, 2, id % 5, 1));
    }

    allocateRequest.setAskList(askList);

    allocateRequest.setResponseId(lastResponseId);
    AllocateResponse allocateResponse = interceptor.allocate(allocateRequest);
    Assert.assertNotNull("allocate() returned null response", allocateResponse);
    checkAMRMToken(allocateResponse.getAMRMToken());
    lastResponseId = allocateResponse.getResponseId();

    containers.addAll(allocateResponse.getAllocatedContainers());
    LOG.info("Number of allocated containers in the original request: {}",
        allocateResponse.getAllocatedContainers().size());

    // Send max 10 heart beats to receive all the containers. If not, we will
    // fail the test
    int numHeartbeat = 0;
    while (containers.size() < numberOfAllocationExcepted && numHeartbeat++ < 10) {
      allocateRequest = Records.newRecord(AllocateRequest.class);
      allocateRequest.setResponseId(lastResponseId);
      allocateResponse = interceptor.allocate(allocateRequest);
      Assert.assertNotNull("allocate() returned null response", allocateResponse);
      checkAMRMToken(allocateResponse.getAMRMToken());
      lastResponseId = allocateResponse.getResponseId();

      // Make sure this request is picked up by all async heartbeat handlers
      interceptor.drainAllAsyncQueue(false);

      containers.addAll(allocateResponse.getAllocatedContainers());
      LOG.info("Number of allocated containers in this request: "
          + Integer.toString(allocateResponse.getAllocatedContainers().size()));
      LOG.info("Total number of allocated containers: {}", containers.size());
      Thread.sleep(10);
    }
    Assert.assertEquals(numberOfAllocationExcepted, containers.size());
    return containers;
  }

  private void releaseContainersAndAssert(List<Container> containers)
      throws Exception {
    Assert.assertTrue(containers.size() > 0);
    AllocateRequest allocateRequest = Records.newRecord(AllocateRequest.class);
    List<ContainerId> relList = new ArrayList<ContainerId>(containers.size());
    for (Container container : containers) {
      relList.add(container.getId());
    }

    allocateRequest.setReleaseList(relList);

    allocateRequest.setResponseId(lastResponseId);
    AllocateResponse allocateResponse = interceptor.allocate(allocateRequest);
    Assert.assertNotNull(allocateResponse);
    checkAMRMToken(allocateResponse.getAMRMToken());
    lastResponseId = allocateResponse.getResponseId();

    // The release request will be split and handled by the corresponding UAM.
    // The release containers returned by the mock resource managers will be
    // aggregated and returned back to us and we can check if total request size
    // and returned size are the same
    List<ContainerId> containersForReleasedContainerIds = new ArrayList<ContainerId>();
    List<ContainerId> newlyFinished = getCompletedContainerIds(
        allocateResponse.getCompletedContainersStatuses());
    containersForReleasedContainerIds.addAll(newlyFinished);
    LOG.info("Number of containers received in the original request: {}", newlyFinished.size());

    // Send max 10 heart beats to receive all the containers. If not, we will fail the test
    int numHeartbeat = 0;
    while (containersForReleasedContainerIds.size() < relList.size() && numHeartbeat++ < 10) {
      allocateRequest = Records.newRecord(AllocateRequest.class);
      allocateRequest.setResponseId(lastResponseId);
      allocateResponse = interceptor.allocate(allocateRequest);
      Assert.assertNotNull(allocateResponse);
      checkAMRMToken(allocateResponse.getAMRMToken());
      lastResponseId = allocateResponse.getResponseId();

      // Make sure this request is picked up by all async heartbeat handlers
      interceptor.drainAllAsyncQueue(false);

      newlyFinished = getCompletedContainerIds(allocateResponse.getCompletedContainersStatuses());
      containersForReleasedContainerIds.addAll(newlyFinished);
      LOG.info("Number of containers received in this request: ", newlyFinished.size());
      LOG.info("Total number of containers received: ", containersForReleasedContainerIds.size());
      Thread.sleep(10);
    }

    Assert.assertEquals(relList.size(), containersForReleasedContainerIds.size());
  }

  private void checkAMRMToken(Token amrmToken) {
    if (amrmToken != null) {
      // The token should be the one issued by home MockRM
      Assert.assertTrue(amrmToken.getKind().equals(Integer.toString(0)));
    }
  }

  @Test
  public void testRecoverWithAMRMProxyHA() throws Exception {
    testRecoverWithRPCClientRM(registry);
  }

  @Test
  public void testRecoverWithoutAMRMProxyHA() throws Exception {
    testRecoverWithRPCClientRM(null);
  }

  protected void testRecoverWithRPCClientRM(
      final RegistryOperations registryObj)
      throws Exception {
    UserGroupInformation ugi = this.getUGIWithToken(attemptId);
    ugi.doAs(new PrivilegedExceptionAction<Object>() {
      @Override
      public Object run() throws Exception {
        interceptor = new TestableFederationInterceptor(mockHomeRm);
        interceptor.init(new AMRMProxyApplicationContextImpl(nmContext, conf, attemptId,
            "test-user", null, null, null, registryObj));
        interceptor.cleanupRegistry();

        // Register the application
        RegisterApplicationMasterRequest registerReq =
            Records.newRecord(RegisterApplicationMasterRequest.class);
        registerReq.setHost(Integer.toString(testAppId));
        registerReq.setRpcPort(testAppId);
        registerReq.setTrackingUrl("");

        RegisterApplicationMasterResponse registerResponse =
            interceptor.registerApplicationMaster(registerReq);
        Assert.assertNotNull(registerResponse);
        lastResponseId = 0;

        Assert.assertEquals(0, interceptor.getUnmanagedAMPoolSize());

        // Allocate one batch of containers
        registerSubCluster(SubClusterId.newInstance(SC_ID1));
        registerSubCluster(SubClusterId.newInstance(HOME_SC_ID));

        int numberOfContainers = 3;
        List<Container> containers =
            getContainersAndAssert(numberOfContainers, numberOfContainers * 2);
        Assert.assertEquals(1, interceptor.getUnmanagedAMPoolSize());

        // Make sure all async hb threads are done
        interceptor.drainAllAsyncQueue(true);

        // Prepare for Federation Interceptor restart and recover
        Map<String, byte[]> recoveredDataMap = recoverDataMapForAppAttempt(nmStateStore, attemptId);
        String scEntry = FederationInterceptor.NMSS_SECONDARY_SC_PREFIX + "SC-1";
        if (registryObj == null) {
          Assert.assertTrue(recoveredDataMap.containsKey(scEntry));
        } else {
          // When AMRMPRoxy HA is enabled, NMSS should not have the UAM token,
          // it should be in Registry
          Assert.assertFalse(recoveredDataMap.containsKey(scEntry));
        }

        // Preserve the mock RM instances
        MockResourceManagerFacade homeRM = interceptor.getHomeRM();
        ConcurrentHashMap<String, MockResourceManagerFacade> secondaries =
            interceptor.getSecondaryRMs();

        // Create a new interceptor instance and recover
        interceptor = new TestableFederationInterceptor(homeRM, secondaries);
        interceptor.init(new AMRMProxyApplicationContextImpl(nmContext, conf, attemptId,
            "test-user", null, null, null, registryObj));
        interceptor.setClientRPC(true);
        interceptor.recover(recoveredDataMap);
        interceptor.setClientRPC(false);

        Assert.assertEquals(1, interceptor.getUnmanagedAMPoolSize());
        // SC-1 should be initialized to be timed out
        Assert.assertEquals(1, interceptor.getTimedOutSCs(true).size());

        // The first allocate call expects a fail-over exception and re-register
        try {
          AllocateRequest allocateRequest = Records.newRecord(AllocateRequest.class);
          allocateRequest.setResponseId(lastResponseId);
          AllocateResponse allocateResponse = interceptor.allocate(allocateRequest);
          lastResponseId = allocateResponse.getResponseId();
          Assert.fail("Expecting an ApplicationMasterNotRegisteredException  "
              + " after FederationInterceptor restarts and recovers");
        } catch (ApplicationMasterNotRegisteredException e) {
        }
        interceptor.registerApplicationMaster(registerReq);
        lastResponseId = 0;

        // Release all containers
        releaseContainersAndAssert(containers);

        // Finish the application
        FinishApplicationMasterRequest finishReq =
            Records.newRecord(FinishApplicationMasterRequest.class);
        finishReq.setDiagnostics("");
        finishReq.setTrackingUrl("");
        finishReq.setFinalApplicationStatus(FinalApplicationStatus.SUCCEEDED);

        FinishApplicationMasterResponse finishResponse =
            interceptor.finishApplicationMaster(finishReq);
        Assert.assertNotNull(finishResponse);
        Assert.assertEquals(true, finishResponse.getIsUnregistered());

        // After the application succeeds, the registry/NMSS entry should be
        // cleaned up
        if (registryObj != null) {
          Assert.assertEquals(0, interceptor.getRegistryClient().getAllApplications().size());
        } else {
          recoveredDataMap = recoverDataMapForAppAttempt(nmStateStore, attemptId);
          Assert.assertFalse(recoveredDataMap.containsKey(scEntry));
        }
        return null;
      }
    });
  }

  private UserGroupInformation getUGIWithToken(
      ApplicationAttemptId appAttemptId) throws IOException {
    UserGroupInformation ugi = UserGroupInformation.getLoginUser();
    AMRMTokenIdentifier token = new AMRMTokenIdentifier(appAttemptId, 1);
    ugi.addTokenIdentifier(token);
    return ugi;
  }

  private class MockRMPolicyProvider extends PolicyProvider {

    private MockRMPolicyProvider() {
    }

    private final Service[] resourceManagerServices =
        new Service[]{
            new Service(
                YarnConfiguration.YARN_SECURITY_SERVICE_AUTHORIZATION_APPLICATIONCLIENT_PROTOCOL,
                ApplicationClientProtocolPB.class),
        };

    @Override
    public Service[] getServices() {
      return resourceManagerServices;
    }
  }
}


text:
package org.springframework.security.web.util;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;

import org.springframework.util.StringUtils;

/**
 * Matches a request based on IP Address or subnet mask matching against the remote address.
 *
 * @author Luke Taylor
 * @since 3.0.2
 */
public class IpAddressMatcher implements RequestMatcher {
    private final int nMaskBits;
    private final InetAddress requiredAddress;

    /**
     * Takes a specific IP address or a range specified using the
     * IP/Netmask (e.g. 192.168.1.0/24 or 202.24.0.0/14).
     *
     * @param ipAddress the address or range of addresses from which the request must come.
     */
    public IpAddressMatcher(String ipAddress) {

        if (ipAddress.indexOf('/') > 0) {
            String[] addressAndMask = StringUtils.split(ipAddress, "/");
            ipAddress = addressAndMask[0];
            nMaskBits = Integer.parseInt(addressAndMask[1]);
        } else {
            nMaskBits = 0;
        }
        requiredAddress = parseAddress(ipAddress);
    }

    public boolean matches(HttpServletRequest request) {
        InetAddress remoteAddress = parseAddress(request.getRemoteAddr());

        if (!requiredAddress.getClass().equals(remoteAddress.getClass())) {
            throw new IllegalArgumentException("IP Address in expression must be the same type as " +
                    "version returned by request");
        }

        if (nMaskBits == 0) {
            return remoteAddress.equals(requiredAddress);
        }

        byte[] remAddr = remoteAddress.getAddress();
        byte[] reqAddr = requiredAddress.getAddress();

        int oddBits = nMaskBits % 8;
        int nMaskBytes = nMaskBits/8 + (oddBits == 0 ? 0 : 1);
        byte[] mask = new byte[nMaskBytes];

        Arrays.fill(mask, 0, oddBits == 0 ? mask.length : mask.length - 1, (byte)0xFF);

        if (oddBits != 0) {
            int finalByte = (1 << oddBits) - 1;
            finalByte <<= 8-oddBits;
            mask[mask.length - 1] = (byte) finalByte;
        }

 //       System.out.println("Mask is " + new sun.misc.HexDumpEncoder().encode(mask));

        for (int i=0; i < mask.length; i++) {
            if ((remAddr[i] & mask[i]) != (reqAddr[i] & mask[i])) {
                return false;
            }
        }

        return true;
    }

    private InetAddress parseAddress(String address) {
        try {
            return InetAddress.getByName(address);
        } catch (UnknownHostException e) {
            throw new IllegalArgumentException("Failed to parse address" + address, e);
        }
    }
}


text:
"""Support for Lutron lights."""
import logging

from homeassistant.components.light import ATTR_BRIGHTNESS, SUPPORT_BRIGHTNESS, Light

from . import LUTRON_CONTROLLER, LUTRON_DEVICES, LutronDevice

_LOGGER = logging.getLogger(__name__)

def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the Lutron lights."""
    devs = []
    for (area_name, device) in hass.data[LUTRON_DEVICES]["light"]:
        dev = LutronLight(area_name, device, hass.data[LUTRON_CONTROLLER])
        devs.append(dev)

    add_entities(devs, True)

def to_lutron_level(level):
    """Convert the given HASS light level (0-255) to Lutron (0.0-100.0)."""
    return float((level * 100) / 255)

def to_hass_level(level):
    """Convert the given Lutron (0.0-100.0) light level to HASS (0-255)."""
    return int((level * 255) / 100)

class LutronLight(LutronDevice, Light):
    """Representation of a Lutron Light, including dimmable."""

    def __init__(self, area_name, lutron_device, controller):
        """Initialize the light."""
        self._prev_brightness = None
        super().__init__(area_name, lutron_device, controller)

    @property
    def supported_features(self):
        """Flag supported features."""
        return SUPPORT_BRIGHTNESS

    @property
    def brightness(self):
        """Return the brightness of the light."""
        new_brightness = to_hass_level(self._lutron_device.last_level())
        if new_brightness != 0:
            self._prev_brightness = new_brightness
        return new_brightness

    def turn_on(self, **kwargs):
        """Turn the light on."""
        if ATTR_BRIGHTNESS in kwargs and self._lutron_device.is_dimmable:
            brightness = kwargs[ATTR_BRIGHTNESS]
        elif self._prev_brightness == 0:
            brightness = 255 / 2
        else:
            brightness = self._prev_brightness
        self._prev_brightness = brightness
        self._lutron_device.level = to_lutron_level(brightness)

    def turn_off(self, **kwargs):
        """Turn the light off."""
        self._lutron_device.level = 0

    @property
    def device_state_attributes(self):
        """Return the state attributes."""
        attr = {"lutron_integration_id": self._lutron_device.id}
        return attr

    @property
    def is_on(self):
        """Return true if device is on."""
        return self._lutron_device.last_level() > 0

    def update(self):
        """Call when forcing a refresh of the device."""
        if self._prev_brightness is None:
            self._prev_brightness = to_hass_level(self._lutron_device.level)


text:
import numpy as np
import cv2

def overlay(img1, img2):

	# I want to put logo on top-left corner, So I create a ROI
	rows,cols,channels = img2.shape
	roi = img1[0:rows, 0:cols ]

	# Now create a mask of logo and create its inverse mask also
	img2gray = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY)
	ret, mask = cv2.threshold(img2gray, 10, 255, cv2.THRESH_BINARY)
	mask_inv = cv2.bitwise_not(mask)

	# Now black-out the area of logo in ROI
	img1_bg = cv2.bitwise_and(roi,roi,mask = mask_inv)

	# Take only region of logo from logo image.
	img2_fg = cv2.bitwise_and(img2,img2,mask = mask)

	# Put logo in ROI and modify the main image
	dst = cv2.add(img1_bg,img2_fg)
	img1[0:rows, 0:cols ] = dst

	return dst

cap = cv2.VideoCapture('serenity.mp4')
overlay_image = cv2.imread('2.png')

while(cap.isOpened()):

	ret, frame = cap.read()

	frame = overlay(frame,overlay_image)

	cv2.imshow('frame',frame)
	if cv2.waitKey(1) & 0xFF == ord('q'):
		break

cap.release()
cv2.destroyAllWindows()


text:
SET(COMPOSITE_SOURCE_DIR ${SOURCE_DIR}/reinit)
set(REINIT_SOURCE_DIR ${SOURCE_DIR}/reinit)
file(GLOB REINIT_SRC ${REINIT_SOURCE_DIR}/*.cc)
add_library(amdis_reinit ${REINIT_SRC})
add_library(AMDiS::reinit ALIAS amdis_reinit)

target_compile_definitions(amdis_reinit PUBLIC
    HAVE_REINIT=1)
target_include_directories(amdis_reinit PUBLIC ${REINIT_SOURCE_DIR})
target_link_libraries(amdis_reinit amdis)

# specify how to install this target:
# -----------------------------------

file(GLOB RINIT_HEADERS "${REINIT_SOURCE_DIR}/*.h*")
install(FILES ${RINIT_HEADERS} DESTINATION include/amdis/reinit)
install(TARGETS amdis_reinit DESTINATION lib/amdis/ )


text:
<?php

class LceService extends ObjectModel
{
    public $id_service;
    public $id_carrier;
    public $carrier_code;
    public $code;
    public $name;
    public $pickup_available;
    public $dropoff_available;
    public $relay_delivery;
    public $tracking_url;
    public $date_add;
    public $date_upd;

    public static $definition = array(
        'table' => 'lce_services',
        'primary' => 'id_service',
        'multilang' => false,
        'fields' => array(
            'id_carrier' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true),
            'carrier_code' => array('type' => self::TYPE_STRING),
            'code' => array('type' => self::TYPE_STRING),
            'name' => array('type' => self::TYPE_STRING),
            'pickup_available' => array('type' => self::TYPE_BOOL),
            'dropoff_available' => array('type' => self::TYPE_BOOL),
            'relay_delivery' => array('type' => self::TYPE_BOOL),
            'tracking_url' => array('type' => self::TYPE_STRING),
            'date_add' => array('type' => self::TYPE_DATE, 'validate' => 'isDate'),
            'date_upd' => array('type' => self::TYPE_DATE, 'validate' => 'isDate'),
        ),
        'associations' => array(
            'carrier' => array('type' => self::HAS_ONE, 'field' => 'id_carrier', 'object' => 'Carrier'),
        ),
    );

    public static function findByCarrierId($id_carrier)
    {
        $sql = 'SELECT * FROM '._DB_PREFIX_.'lce_services as s
                WHERE s.`id_carrier` = '.(int)$id_carrier;
        $row = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($sql);
        $service = new self((int) $row['id_service']);

        return $service;
    }

    public static function findByCode($service_code)
    {
        $sql = 'SELECT * FROM '._DB_PREFIX_.'lce_services as s
                WHERE s.`code` = "'.pSQL($service_code).'"';
        $row = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($sql);
        if ($row) {
            $service = new self((int) $row['id_service']);
        } else {
            $service = false;
        }
        return $service;
    }

    public static function findAll()
    {
        $sql = 'SELECT * FROM '._DB_PREFIX_.'lce_services as s';
        $collection = array();
        if ($rows = Db:: getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql)) {
            foreach ($rows as $row) {
                $collection[] = new self((int) $row['id_service']);
            }
        }
        return $collection;
    }

    public function carrierName()
    {
        if (Tools::strlen($this->carrier_code) > 4) {
            return Tools::ucfirst($this->carrier_code);
        } else {
            return Tools::strtoupper($this->carrier_code);
        }
    }

    public function logoFileName()
    {
        if (!empty($this->carrier_code)) {
            return $this->carrier_code.'.png';
        } else {
            return 'myflyingbox.png';
        }
    }

    public function getCarrier()
    {
        $carrier = new Carrier((int)$this->id_carrier);
        return $carrier;
    }

    public static function getRelayDeliveryCarrierIds()
    {
        $sql = 'SELECT * FROM '._DB_PREFIX_.'lce_services WHERE relay_delivery = 1';
        $collection = array();
        if ($rows = Db:: getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql)) {
            foreach ($rows as $row) {
                $collection[] = $row['id_carrier'];
            }
        }

        return $collection;
    }

    public function getTrackingUrl()
    {
        if ($this->carrier_code == 'chronopost') {
            return 'http://www.chronopost.fr/fr/chrono_suivi_search?listeNumerosLT=@';
        } elseif ($this->carrier_code == 'dhl') {
            return 'http://www.dhl.fr/fr/dhl_express/suivi_expedition.html?AWB=@';
        } elseif ($this->carrier_code == 'ups') {
            return 'https://wwwapps.ups.com/WebTracking/track?loc=fr_FR&track.x=Track&trackNums=@';
        } elseif ($this->carrier_code == 'colissimo') {
            return 'http://www.colissimo.fr/portail_colissimo/suivre.do?colispart=@';
        } else {
            return '';
        }
    }

    public static function totalCount()
    {
        $sql = 'SELECT COUNT(*) as total FROM '._DB_PREFIX_.'lce_services';
        $row = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($sql);
        return $row['total'];
    }
}


text:
// Only compile this code on Mac. These files should not be included on your iOS project.
// But in case they are included, it won't be compiled.
#import <Availability.h>
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED)

#import <QuartzCore/CVDisplayLink.h>
#import "../../CCDirector.h"

enum  {
	/// If the window is resized, it won't be autoscaled
	kCCDirectorResize_NoScale,
	/// If the window is resized, it will be autoscaled (default behavior)
	kCCDirectorResize_AutoScale,
};

@interface CCDirector (MacExtension)
/** converts an NSEvent to GL coordinates */
-(CGPoint) convertEventToGL:(NSEvent*)event;
@end

/** Base class of Mac directors
 @since v0.99.5
 */
@interface CCDirectorMac : CCDirector
{
	BOOL			isFullScreen_;
	int				resizeMode_;
	CGPoint			winOffset_;
    CGSize			originalWinSize_;

	NSWindow		*fullScreenWindow_;

	// cache
	NSWindow		*windowGLView_;
    NSView          *superViewGLView_;
    NSRect          originalWinRect_; // Original size and position
}

// whether or not the view is in fullscreen mode
@property (nonatomic, readonly) BOOL isFullScreen;

// resize mode: with or without scaling
@property (nonatomic, readwrite) int resizeMode;

@property (nonatomic, readwrite) CGSize originalWinSize;

/** Sets the view in fullscreen or window mode */
- (void) setFullScreen:(BOOL)fullscreen;

/** Converts window size coordiantes to logical coordinates.
 Useful only if resizeMode is kCCDirectorResize_Scale.
 If resizeMode is kCCDirectorResize_NoScale, then no conversion will be done.
*/
- (CGPoint) convertToLogicalCoordinates:(CGPoint)coordinates;
@end

/** DisplayLinkDirector is a Director that synchronizes timers with the refresh rate of the display.
 *
 * Features and Limitations:
 * - Only available on 3.1+
 * - Scheduled timers & drawing are synchronizes with the refresh rate of the display
 * - Only supports animation intervals of 1/60 1/30 & 1/15
 *
 * It is the recommended Director if the SDK is 3.1 or newer
 *
 * @since v0.8.2
 */
@interface CCDirectorDisplayLink : CCDirectorMac
{
	CVDisplayLinkRef displayLink;
}
@end

#endif // __MAC_OS_X_VERSION_MAX_ALLOWED


text:
@class UIViewController;
@interface FSAPPConfigure : NSObject

+ (UIViewController *)getRootController;

@end


text:
Dawn is a source code scanner designed to review your ruby code for security
issues.

Dawn is able to scan plain ruby scripts (e.g. command line applications) but
all its features are unleashed when dealing with web applications source code.
Dawn is able to scan major MVC (Model View Controller) frameworks, out of the
box:

* [Ruby on Rails](http://rubyonrails.org)
* [Sinatra](http://www.sinatrarb.com)
* [Padrino](http://www.padrinorb.com)

---

[![Gem Version](https://badge.fury.io/rb/dawnscanner.png)](http://badge.fury.io/rb/dawnscanner)
[![Build Status](https://travis-ci.org/thesp0nge/dawnscanner.png?branch=master)](https://travis-ci.org/thesp0nge/dawnscanner)
[![Dependency Status](https://gemnasium.com/thesp0nge/dawnscanner.png)](https://gemnasium.com/thesp0nge/dawnscanner)
[![Coverage Status](https://coveralls.io/repos/thesp0nge/dawnscanner/badge.png)](https://coveralls.io/r/thesp0nge/dawnscanner)
[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/thesp0nge/dawnscanner/trend.png)](https://bitdeli.com/free "Bitdeli Badge")
[![Inline docs](http://inch-ci.org/github/thesp0nge/dawnscanner.png?branch=master)](http://inch-ci.org/github/thesp0nge/dawnscanner)

---

Dawn version 1.3 has 180 security checks loaded in its knowledge
base. Most of them are CVE bulletins applying to gems or the ruby interpreter
itself. There are also some check coming from Owasp Ruby on Rails cheatsheet.

## An overall introduction

When you run Dawn on your code it parses your project Gemfile.lock
looking for the gems used and it tries to detect the ruby interpreter version
you are using or you declared in your ruby version management tool you like
most (RVM, rbenv, ...).

Then the tool tries to detect the MVC framework your web application uses and
it applies the security check accordingly. There checks designed to match rails
application or checks that are appliable to any ruby code.

Dawn can also understand the code in your views and to backtrack
sinks to spot cross site scripting and sql injections introduced by the code
you actually wrote. In the project roadmap this is the code most of the future
development effort will be focused on.

Dawn security scan result is a list of vulnerabilities with some
mitigation actions you want to follow in order to build a stronger web
application.

## Installation

dawnscanner rubygem is cryptographically signed. To be sure the gem you
install hasn't been tampered, you must first add ```paolo@dawnscanner.org```
public signing certificate as trusted to your gem specific keyring.

```
$ gem cert --add <(curl -Ls https://raw.githubusercontent.com/thesp0nge/dawnscanner/master/certs/paolo_at_dawnscanner_dot_org.pem)
```

You can install latest Dawn version, fetching it from
[Rubygems](https://rubygems.org) by typing:

```
$ gem install dawnscanner -P MediumSecurity
```

The MediumSecurity trust profile will verify signed gems, but allow the
installation of unsigned dependencies. This is necessary because not all of
Dawn's dependencies are signed, so we cannot use HighSecurity.

In order to install a release candidate version, the gem install command line
is the following:

```
$ gem install dawnscanner --pre -P MediumSecurity
```

If you want to add dawn to your project Gemfile, you must add the following:

    group :development do
      gem 'dawnscanner', :require=>false
    end

And then upgrade your bundle

    $ bundle install

You may want to build it from source, so you have to check it out from github first:

    $ git clone https://github.com/thesp0nge/dawnscanner.git
    $ cd dawnscanner
    $ bundle install
    $ rake install

And the dawnscanner gem will be built in a pkg directory and then installed
on your system. Please note that you have to manage dependencies on your own
this way. It makes sense only if you want to hack the code or something like
that.

## Usage

You can start your code review with Dawn very easily. Simply tell the tool
where the project root directory.

Underlying MVC framework is autodetected by Dawn using target Gemfile.lock
file. If autodetect fails for some reason, the tool will complain about it and
you have to specify if it's a rails, sinatra or padrino web application by
hand.

Basic usage is to specify some optional command line option to fit best your
needs, and to specify the target directory where your code is stored.

```
$ dawn [options] target
```

In case of need, there is a quick command line option reference running
```dawn -h``` at your OS prompt.

```
$ dawn -h
Usage: dawn [options] target_directory

Examples:
  $ dawn a_sinatra_webapp_directory
  $ dawn -C the_rails_blog_engine
  $ dawn -C --json a_sinatra_webapp_directory
  $ dawn --ascii-tabular-report my_rails_blog_ecommerce
  $ dawn --html -F my_report.html my_rails_blog_ecommerce

   -r, --rails          force dawn to consider the target a rails application
   -s, --sinatra        force dawn to consider the target a sinatra application
   -p, --padrino        force dawn to consider the target a padrino application
   -G, --gem-lock       force dawn to scan only for vulnerabilities affecting dependencies in Gemfile.lock
   -a, --ascii-tabular-report   cause dawn to format findings using table in ascii art
   -j, --json                   cause dawn to format findings using json
   -C, --count-only             dawn will only count vulnerabilities (useful for scripts)
   -z, --exit-on-warn           dawn will return number of found vulnerabilities as exit code
   -F, --file filename          tells dawn to write output to filename
   -c, --config-file filename   tells dawn to load configuration from filename

Disable security check family

       --disable-cve-bulletins  disable all CVE security checks
       --disable-code-quality   disable all code quality checks
       --disable-code-style     disable all code style checks
       --disable-owasp-ror-cheatsheet   disable all Owasp Ruby on Rails cheatsheet checks
       --disable-owasp-top-10           disable all Owasp Top 10 checks

Flags useful to query Dawn

       -S, --search-knowledge-base [check_name]   search check_name in the knowledge base
           --list-knowledge-base                  list knowledge-base content
           --list-known-families                  list security check families contained in dawn's knowledge base
           --list-known-framework                 list ruby MVC frameworks supported by dawn

Service flags

   -D, --debug                                  enters dawn debug mode
   -V, --verbose                                the output will be more verbose
   -v, --version                                show version information
   -h, --help                                   show this help
```

### Rake task

To include Dawn in your rake task list, you simply have to put this line in
your ```Rakefile```

```
require 'dawn/tasks'
```

Then executing ```$ rake -T``` you will have a ```dawn:run``` task you want to
execute.

```
$ rake -T
...
rake dawn:run                  # Execute dawnscanner on the current directory
...
```

### Interacting with the knowledge base

You can dump all security checks in the knowledge base this way

```
$ dawn --list-knowledge-base
```

Useful in scripts, you can use ```--search-knowledge-base``` or ```-S``` with
as parameter the check name you want to see if it's implemented as a security
control or not.

```
$ dawn -S CVE-2013-6421
07:59:30 [*] dawn v1.1.0 is starting up
CVE-2013-6421 found in knowledgebase.

$ dawn -S this_test_does_not_exist
08:02:17 [*] dawn v1.1.0 is starting up
this_test_does_not_exist not found in knowledgebase
```

### Dawn security scan in action

As output, Dawn will put all security checks that are failed during the scan.

This the result of Codedake::Dawn running against a
[Sinatra 1.4.2 web application](https://github.com/thesp0nge/railsberry2013) wrote for a talk I
delivered in 2013 at [Railsberry conference](http://www.railsberry.com).

As you may see, Dawn first detects MVC running the application by
looking at Gemfile.lock, than it discards all security checks not appliable to
Sinatra (49 security checks, in version 1.0, especially designed for Ruby on
Rails) and it applies them.

```
$ dawn ~/src/hacking/railsberry2013
18:40:27 [*] dawn v1.1.0 is starting up
18:40:27 [$] dawn: scanning /Users/thesp0nge/src/hacking/railsberry2013
18:40:27 [$] dawn: sinatra v1.4.2 detected
18:40:27 [$] dawn: applying all security checks
18:40:27 [$] dawn: 109 security checks applied - 0 security checks skipped
18:40:27 [$] dawn: 1 vulnerabilities found
18:40:27 [!] dawn: CVE-2013-1800 check failed
18:40:27 [$] dawn: Severity: high
18:40:27 [$] dawn: Priority: unknown
18:40:27 [$] dawn: Description: The crack gem 0.3.1 and earlier for Ruby does not properly restrict casts of string values, which might allow remote attackers to conduct object-injection attacks and execute arbitrary code, or cause a denial of service (memory and CPU consumption) by leveraging Action Pack support for (1) YAML type conversion or (2) Symbol type conversion, a similar vulnerability to CVE-2013-0156.
18:40:27 [$] dawn: Solution: Please use crack gem version 0.3.2 or above. Correct your gemfile
18:40:27 [$] dawn: Evidence:
18:40:27 [$] dawn:      Vulnerable crack gem version found: 0.3.1
18:40:27 [*] dawn is leaving
```

---

When you run Dawn on a web application with up to date dependencies,
it's likely to return a friendly _no vulnerabilities found_ message. Keep it up
working that way!

This is Dawn running against a Padrino web application I wrote for [a
scorecard quiz game about application security](http://scorecard.armoredcode.com).
Italian language only. Sorry.

```
18:42:39 [*] dawn v1.1.0 is starting up
18:42:39 [$] dawn: scanning /Users/thesp0nge/src/CORE_PROJECTS/scorecard
18:42:39 [$] dawn: padrino v0.11.2 detected
18:42:39 [$] dawn: applying all security checks
18:42:39 [$] dawn: 109 security checks applied - 0 security checks skipped
18:42:39 [*] dawn: no vulnerabilities found.
18:42:39 [*] dawn is leaving
```

If you need a fancy HTML report about your scan, just ask it to Dawn
with the ```--html``` flag used with the ```--file``` since I wanto to save the
HTML to disk.

```
$ dawn /Users/thesp0nge/src/hacking/rt_first_app --html --file report.html

09:00:54 [*] dawn v1.1.0 is starting up
09:00:54 [*] dawn: report.html created (2952 bytes)
09:00:54 [*] dawn is leaving
```

---

## Useful links

Project homepage: [http://dawnscanner.org](http://dawnscanner.org)

Twitter profile:  [@dawnscanner](https://twitter.com/dawnscanner)

Github repository:   [https://github.com/thesp0nge/dawnscanner](https://github.com/thesp0nge/dawnscanner)

Mailing list: [https://groups.google.com/forum/#!forum/dawnscanner](https://groups.google.com/forum/#!forum/dawnscanner)

## Support us

Feedbacks are great and we really love to hear your voice.

If you're a proud dawnscanner user, if you find it useful, if you integrated
it in your release process and if you want to openly support the project you
can put your reference here. Just open an
[issue](https://github.com/thesp0nge/dawn/issues/new) with a statement saying
how do you feel the tool and your company logo if any.

More easily you can drop an email to
[paolo@dawnscanner.org](mailto:paolo@dawnscanner.org) sending a statement about your
success story and I'll put on the website.

Thank you.

## Thanks to

[saten](https://github.com/saten): first issue posted about a typo in the README

[presidentbeef](https://github.com/presidentbeef): for his outstanding work that inspired me creating dawn and for double check comparison matrix. Issue #2 is yours :)

[marinerJB](https://github.com/marinerJB): for misc bug reports and further ideas

[Matteo](https://github.com/matteocollina): for ideas on API and their usage with [github.com](https://github.com) hooks

## Contribute to Dawn

Are you interested in contributing to Dawn project? Great, here is
some very basic rules in order to make rocking pull requests.

First of all, I use the branching model described in [this
post](http://nvie.com/posts/a-successful-git-branching-model/). There are two
major branches:

* master: it contains in every moment the code for the latest dawnscanner
  released gem. You can't make branches from here unless you're working on a
  bugfix.
* development: it contains the unstable code that is going to be the next
  dawnscanner realease. You start from here. Pick a task on the Roadmap.md
  and create a separated branch to work on your feature to. When you're ready
  (remember to include also spec files), submit your pull request. If the code
  will be fine, it will be merged into the development tree ready to be include
  in upcoming gem version.

No branch from master it would be analyzed unless they are related to bugfix.
In this case, the branch name must be something like _issue\_#xx\_description_

## LICENSE

Copyright (c) 2013, 2014, 2015 Paolo Perego

MIT License

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
module Testy
  class Printer
    def test_name(name)
      print "\n#{name} -- "
    end

    def pass
      print "PASS\n"
    end

    def fail(message = nil, exception = nil)
      print "FAIL\n"
    end

    def error(exception = nil)
      print "ERROR\n"
      print "\n#{exception.message}\n===\n"
      print exception.backtrace.join "\n"
    end

    def report(hash)
      print "Tests finished\n"
      print "#{hash[:count]} tests completed. "
      print "#{hash[:passed]} tests successfull. "
      print "#{hash[:failed]} tests failed. "
      print "#{hash[:error]} tests with errors.\n"
    end
  end
end


text:
/*
 * DC/OS
 *
 * DC/OS API
 *
 * API version: 1.0.0
 */

// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.

package dcos

type EdgelbV2PoolVirtualNetworks struct {
	// The name of the virtual network to join.
	Name string `json:"name,omitempty"`
	// Labels to pass to the virtual network plugin.
	Labels map[string]string `json:"labels,omitempty"`
}


text:
package gr.iti.mklab.mmcomms16;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import org.apache.log4j.Logger;

import gr.iti.mklab.util.EasyBufferedReader;
import gr.iti.mklab.util.EasyBufferedWriter;

@SuppressWarnings("unchecked")
public class VisualSampling extends Sampling{

	private static Logger logger = Logger.getLogger(
			"gr.iti.mklab.eval.VisualSampling");

	public static Object sample(String testFile) throws Exception{

		logger.info("Sampling: Visual Strategy");

		VisualSampling sampling =
				new VisualSampling();

		return sampling.writeInFile(sampling.loadData(testFile));
	}

	protected Object loadData(String testFile) {

		Map<String, Set<String>> concepts =
				new HashMap<String, Set<String>>();

		EasyBufferedReader reader =
				new EasyBufferedReader(testFile);
		String line;
		while((line = reader.readLine())!=null){
			String imageID = line.split("\t")[0];
			for(String concept:line .split("\t")[1].split(",")){
				if(concepts.containsKey(concept.split(":")[0])){
					concepts.get(concept.split(":")[0]).add(imageID);
				}else{
					concepts.put(concept.split(":")[0], new HashSet<String>());
					concepts.get(concept.split(":")[0]).add(imageID);
				}
			}
		}
		reader.close();
		logger.info(concepts.size() + " Concepts loaded");

		return concepts;
	}

	protected Object writeInFile(Object data) {

		Map<String, Set<String>> concepts =
				(Map<String, Set<String>>) data;

		EasyBufferedWriter writer = new EasyBufferedWriter(
				"samples/visual_sampling.txt");
		for(Entry<String, Set<String>> concept:concepts.entrySet()){
			writer.write(concept.getKey() + "\t");
			for(String images:concept.getValue()){
				writer.write(images + " ");
			}
			writer.newLine();
		}
		writer.close();

		return concepts;
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>

<resources>
    <string name="app_name">Subaru SSM</string>

    <!--  SubaruSsm -->
    <string name="not_connected">You are not connected to a car BT device</string>
    <string name="bt_not_enabled_leaving">Bluetooth was not enabled. Leaving Subaru Ssm.</string>
    <string name="title_connecting">Connecting…</string>
    <string name="title_connected_to">Connected to: </string>
    <string name="title_not_connected">Not connected</string>
    <string name="drawer_open">Open navigation drawer</string>
    <string name="drawer_close">Close navigation drawer</string>

    <!--  DeviceListActivity -->
    <string name="scanning">Scanning for BT devices…</string>
    <string name="select_device">Select a proper BT device</string>
    <string name="none_paired">No devices have been paired</string>
    <string name="none_found">No devices found</string>
    <string name="title_paired_devices">Paired Devices</string>
    <string name="title_other_devices">Other Available Devices</string>
    <string name="button_scan">Scan for BT devices</string>

    <!-- Options Menu -->
    <string name="connect">Connect to a BT device</string>

    <string name="select_parameters">Select parameters</string>
    <string name="ok">OK</string>
</resources>


text:
<link href="../concordion.css" rel="stylesheet" type="text/css" />

Concordion

        The Concordion framework
        brings together testing and specification.
        Concrete examples of expected behaviour (written in HTML) can be
        instrumented with Concordion commands that run tests against the
        real system via some Java fixture code.
        The fixture code helps to decouple the specs from the system.

        See here for a simple example.

Further Details

What commands are available?

What annotations are available?

How are the results displayed?

How do you run an active specification?


text:
"""2016 advent of code day 2.

You finally arrive at the bathroom (it's a several minute walk from the lobby
so visitors can behold the many fancy conference rooms and water coolers on
this floor) and go to punch in the code. Much to your bladder's dismay, the
keypad is not at all like you imagined it. Instead, you are confronted with
the result of hundreds of man-hours of bathroom-keypad-design meetings:

    1
  2 3 4
5 6 7 8 9
  A B C
    D

You still start at "5" and stop when you're at an edge, but given the same
instructions as above, the outcome is very different:

You start at "5" and don't move at all (up and left are both edges), ending
at 5.
Continuing from "5", you move right twice and down three times (through "6",
"7", "B", "D", "D"), ending at D.
Then, from "D", you move five more times (through "D", "B", "C", "C", "B"),
ending at B.
Finally, after five more moves, you end at 3.
So, given the actual keypad layout, the code would be 5DB3.

Using the same instructions in your puzzle input, what is the correct bathroom
code?
"""

import string
import sys

def move(movements, cur):
    """Move around the keypad."""
    new_loc = cur[:]
    for direction in movements:
        dir_index = dirs[direction][0]
        dir_impact = dirs[direction][1]
        new_loc[dir_index] = cur[dir_index] + dir_impact
        if new_loc[dir_index] < 0:
            new_loc[dir_index] = 0
        elif new_loc[dir_index] > 4:
            new_loc[dir_index] = 4
        if keypad[new_loc[0]][new_loc[1]] == "*":
            new_loc = cur[:]
        else:
            cur = new_loc[:]
    return cur

with open(sys.argv[1]) as f:
    lines = f.read().rstrip("\n").split("\n")

keypad = (("*", "*", "1", "*", "*"), ("*", "2", "3", "4", "*"),
          ("5", "6", "7", "8", "9"), ("*", "A", "B", "C", "*"),
          ("*", "*", "D", "*", "*"))

# Use dirs to track available keypad directions and their impact on movement
#   through the keypad hash
dirs = {"U": [0, -1], "D": [0, 1], "L": [1, -1], "R": [1, 1]}
keyseq = []
cur_loc = [2, 0]

for keydir in lines:
    # print(cur_loc)
    cur_loc = move(keydir.strip(), cur_loc)
    keyseq.append(keypad[cur_loc[0]][cur_loc[1]])

print("".join(keyseq))


text:
SELECT
    t_id,
    nbgeometrie_von,
    geometrie
FROM
    agi_plz_ortschaften.nummerierngsbrche_nbgeometrie
;


text:
using System.ComponentModel;

namespace ElmahLogAnalyzer.Core.Domain
{
	public enum ReportTypes
	{
		[Description("Number of errors per type")]
		Type,
		[Description("Number of errors per source")]
		Source,
		[Description("Number of errors per user")]
		User,
		[Description("Number of errors per url")]
		Url,
		[Description("Number of errors per day")]
		Day,
		[Description("Number of errors per browser")]
		Browser
	}
}