text:
<?php

/*
 *---------------------------------------------------------------
 * APPLICATION ENVIRONMENT
 *---------------------------------------------------------------
 *
 * You can load different configurations depending on your
 * current environment. Setting the environment also influences
 * things like logging and error reporting.
 *
 * This can be set to anything, but default usage is:
 *
 *     development
 *     testing
 *     production
 *
 * NOTE: If you change these, also change the error_reporting() code below
 */
    define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');

/*
 *---------------------------------------------------------------
 * ERROR REPORTING
 *---------------------------------------------------------------
 *
 * Different environments will require different levels of error reporting.
 * By default development will show errors but testing and live will hide them.
 */
switch (ENVIRONMENT)
{
    case 'development':
        error_reporting(-1);
        ini_set('display_errors', 1);
    break;

    case 'testing':
    case 'production':
        ini_set('display_errors', 0);
        if (version_compare(PHP_VERSION, '5.3', '>='))
        {
            error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED);
        }
        else
        {
            error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_USER_NOTICE);
        }
    break;

    default:
        header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
        echo 'The application environment is not set correctly.';
        exit(1); // EXIT_ERROR
}

/*
 *---------------------------------------------------------------
 * SYSTEM FOLDER NAME
 *---------------------------------------------------------------
 *
 * This variable must contain the name of your "system" folder.
 * Include the path if the folder is not in the same directory
 * as this file.
 */
    $system_path = 'system';

/*
 *---------------------------------------------------------------
 * APPLICATION FOLDER NAME
 *---------------------------------------------------------------
 *
 * If you want this front controller to use a different "application"
 * folder than the default one you can set its name here. The folder
 * can also be renamed or relocated anywhere on your server. If
 * you do, use a full server path. For more info please see the user guide:
 * http://codeigniter.com/user_guide/general/managing_apps.html
 *
 * NO TRAILING SLASH!
 */
    $application_folder = 'application';

/*
 *---------------------------------------------------------------
 * VIEW FOLDER NAME
 *---------------------------------------------------------------
 *
 * If you want to move the view folder out of the application
 * folder set the path to the folder here. The folder can be renamed
 * and relocated anywhere on your server. If blank, it will default
 * to the standard location inside your application folder. If you
 * do move this, use the full server path to this folder.
 *
 * NO TRAILING SLASH!
 */

    if( check_wap() ){
        $view_folder = 'views_wap';
    }else{
        $view_folder = 'views';
    }
    function check_wap() {
        if (isset($_SERVER['HTTP_VIA'])) return true;
        if (isset($_SERVER['HTTP_X_NOKIA_CONNECTION_MODE'])) return true;
        if (isset($_SERVER['HTTP_X_UP_CALLING_LINE_ID'])) return true;
        if (strpos(strtoupper($_SERVER['HTTP_ACCEPT']),"VND.WAP.WML") > 0) {
            // Check whether the browser/gateway says it accepts WML.
            $br = "WML";
        } else {
            $browser = isset($_SERVER['HTTP_USER_AGENT']) ? trim($_SERVER['HTTP_USER_AGENT']) : '';
            if(empty($browser)) return true;
            $mobile_os_list=array('Google Wireless Transcoder','Windows CE','WindowsCE','Symbian','Android','armv6l','armv5','Mobile','CentOS','mowser','AvantGo','Opera Mobi','J2ME/MIDP','Smartphone','Go.Web','Palm','iPAQ');

            $mobile_token_list=array('Profile/MIDP','Configuration/CLDC-','160×160','176×220','240×240','240×320','320×240','UP.Browser','UP.Link','SymbianOS','PalmOS','PocketPC','SonyEricsson','Nokia','BlackBerry','Vodafone','BenQ','Novarra-Vision','Iris','NetFront','HTC_','Xda_','SAMSUNG-SGH','Wapaka','DoCoMo','iPhone','iPod');

            $found_mobile=checkSubstrs($mobile_os_list,$browser) ||
                checkSubstrs($mobile_token_list,$browser);
            if($found_mobile)
                $br ="WML";
            else $br = "WWW";
        }
        if($br == "WML") {
            return true;
        } else {
            return false;
        }
    }
    function checkSubstrs($list,$str){
        $flag = false;
        for($i=0;$i<count($list);$i++){
            if(strpos($str,$list[$i]) > 0){
                $flag = true;
                break;
            }
        }
        return $flag;
    }

/*
 * --------------------------------------------------------------------
 * DEFAULT CONTROLLER
 * --------------------------------------------------------------------
 *
 * Normally you will set your default controller in the routes.php file.
 * You can, however, force a custom routing by hard-coding a
 * specific controller class/function here. For most applications, you
 * WILL NOT set your routing here, but it's an option for those
 * special instances where you might want to override the standard
 * routing in a specific front controller that shares a common CI installation.
 *
 * IMPORTANT: If you set the routing here, NO OTHER controller will be
 * callable. In essence, this preference limits your application to ONE
 * specific controller. Leave the function name blank if you need
 * to call functions dynamically via the URI.
 *
 * Un-comment the $routing array below to use this feature
 */
    // The directory name, relative to the "controllers" folder.  Leave blank
    // if your controller is not in a sub-folder within the "controllers" folder
    // $routing['directory'] = '';

    // The controller class file name.  Example:  mycontroller
    // $routing['controller'] = '';

    // The controller function you wish to be called.
    // $routing['function']	= '';

/*
 * -------------------------------------------------------------------
 *  CUSTOM CONFIG VALUES
 * -------------------------------------------------------------------
 *
 * The $assign_to_config array below will be passed dynamically to the
 * config class when initialized. This allows you to set custom config
 * items or override any default config values found in the config.php file.
 * This can be handy as it permits you to share one application between
 * multiple front controller files, with each file containing different
 * config values.
 *
 * Un-comment the $assign_to_config array below to use this feature
 */
    // $assign_to_config['name_of_config_item'] = 'value of config item';

// --------------------------------------------------------------------
// END OF USER CONFIGURABLE SETTINGS.  DO NOT EDIT BELOW THIS LINE
// --------------------------------------------------------------------

/*
 * ---------------------------------------------------------------
 *  Resolve the system path for increased reliability
 * ---------------------------------------------------------------
 */

    // Set the current directory correctly for CLI requests
    if (defined('STDIN'))
    {
        chdir(dirname(__FILE__));
    }

    if (($_temp = realpath($system_path)) !== FALSE)
    {
        $system_path = $_temp.'/';
    }
    else
    {
        // Ensure there's a trailing slash
        $system_path = rtrim($system_path, '/').'/';
    }

    // Is the system path correct?
    if ( ! is_dir($system_path))
    {
        header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
        echo 'Your system folder path does not appear to be set correctly. Please open the following file and correct this: '.pathinfo(__FILE__, PATHINFO_BASENAME);
        exit(3); // EXIT_CONFIG
    }

/*
 * -------------------------------------------------------------------
 *  Now that we know the path, set the main path constants
 * -------------------------------------------------------------------
 */
    // The name of THIS file
    define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME));

    // Path to the system folder
    define('BASEPATH', str_replace('\\', '/', $system_path));

    // Path to the front controller (this file)
    define('FCPATH', dirname(__FILE__).'/');

    // Name of the "system folder"
    define('SYSDIR', trim(strrchr(trim(BASEPATH, '/'), '/'), '/'));

    // The path to the "application" folder
    if (is_dir($application_folder))
    {
        if (($_temp = realpath($application_folder)) !== FALSE)
        {
            $application_folder = $_temp;
        }

        define('APPPATH', $application_folder.DIRECTORY_SEPARATOR);
    }
    else
    {
        if ( ! is_dir(BASEPATH.$application_folder.DIRECTORY_SEPARATOR))
        {
            header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
            echo 'Your application folder path does not appear to be set correctly. Please open the following file and correct this: '.SELF;
            exit(3); // EXIT_CONFIG
        }

        define('APPPATH', BASEPATH.$application_folder.DIRECTORY_SEPARATOR);
    }

    // The path to the "views" folder
    if ( ! is_dir($view_folder))
    {
        if ( ! empty($view_folder) && is_dir(APPPATH.$view_folder.DIRECTORY_SEPARATOR))
        {
            $view_folder = APPPATH.$view_folder;
        }
        elseif ( ! is_dir(APPPATH.'views'.DIRECTORY_SEPARATOR))
        {
            header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
            echo 'Your view folder path does not appear to be set correctly. Please open the following file and correct this: '.SELF;
            exit(3); // EXIT_CONFIG
        }
        else
        {
            $view_folder = APPPATH.'views';
        }
    }

    if (($_temp = realpath($view_folder)) !== FALSE)
    {
        $view_folder = $_temp.DIRECTORY_SEPARATOR;
    }
    else
    {
        $view_folder = rtrim($view_folder, '/\\').DIRECTORY_SEPARATOR;
    }

    define('VIEWPATH', $view_folder);

/*
 * --------------------------------------------------------------------
 * LOAD THE BOOTSTRAP FILE
 * --------------------------------------------------------------------
 *
 * And away we go...
 */
require_once BASEPATH.'core/CodeIgniter.php';


text:
/**
 * 同 request.test.js
 * 只是用的是 hmlt5 的模式
 */

import SMERouter from '@/index'
import chai from 'chai'
import sinon from 'sinon'
import sinonChai from 'chai-sinon'
chai.should()
chai.use(sinonChai)

describe('sme-router test in html5 mode should get same result', function () {
  this.timeout(2000)

  const routePath = '/test/:sme'
  // const info = console.info
  const template = 'some conent'
  const mountPoint = '

'

  document.body.insertAdjacentHTML(
    'afterbegin',
    mountPoint
  )

  afterEach('reset hash', () => {
    window.location.hash = ''
    sessionStorage.clear()
  })

  // #region
  it('should be not match any routes', done => {
    let cc = sinon.spy()
    let router = new SMERouter('route-view', 'html5')
    router.route(routePath, cc)

    router.go('/test-other')

    setTimeout(() => {
      cc.should.have.callCount(0)
      router.stop()
      done()
    }, 500)
  })

  it('should match route', done => {
    let router = new SMERouter('route-view', 'html5')
    router.route(routePath, (req, res, next) => {
      res.render(template)

      let content = ''

      content = document.getElementById('route-view').innerHTML
      content.should.equal(template)
      router.stop()
      done()
    })

    router.go('/test/something')
  })
  // #endregion

  // #region
  it('params.sme should be whattt', done => {
    let router = new SMERouter('route-view', 'html5')
    router.route(routePath, (req) => {
      req.params.sme.should.be.equal('whattt')
      router.stop()
      done()
    })

    router.go('/test/whattt')
  })

  it('request=> /test/oook?info=hallo, query.info should be hallo', done => {
    let router = new SMERouter('route-view', 'html5')
    router.route(routePath, (req) => {
      req.query.info.should.be.equal('hallo')
      router.stop()
      done()
    })

    router.go('/test/oook?info=hallo')
  })

  it('request=> /test/whattt, body should be body', done => {
    const body = {
      mes: 'hi',
      name: 'hwen'
    }

    const temp = {
      mes: 'hi',
      name: 'hwen'
    }

    let router = new SMERouter('route-view', 'html5')
    router.route(routePath, (req) => {
      req.body.should.be.deep.equal(temp)
      router.stop()
      done()
    })

    router.go('/test/whattt', body)
  })
  // #endregion
})

redpajama_set_name: RedPajamaGithub


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

public class SubroutineMovement : MonoBehaviour {

    public static float TimeToInstantiate = 2f;

    public Subroutine Parent {get;set;}

    protected float CurrentInstantiateTime = 0f;
    protected bool BeingFired { get; set; }

	public virtual void Fire(){}

    private static Dictionary<string, uint> RAMCosts = new Dictionary<string, uint>()
    {
        {"tracer", 2},
        {"station", 1 }
    };
    public static uint GetRAMCost(string name)
    {
        return RAMCosts[name.ToLower()];
    }
}


text:
<?php
namespace AJT\FlashBundle\Tests\DependencyInjection\CompilerPass;

use AJT\FlashBundle\DependencyInjection\CompilerPass\CustomCssPass;
use Mockery as m;

class CustomCssPassTest extends \PHPUnit_Framework_TestCase {

    /**
     * @var \Mockery\MockInterface
     */
    private $builder, $definition;

    public function setUp()
    {
        $this->builder = m::mock('Symfony\Component\DependencyInjection\ContainerBuilder');
        $this->definition = m::mock('Symfony\Component\DependencyInjection\Definition');
    }

    public function tearDown()
    {
        m::close();
    }

    /**
     * @test
     */
    public function noDefinition()
    {
        $this->builder->shouldReceive('hasDefinition')->once()->andReturn(false);

        $this->getPass()->process($this->builder);
    }

    /**
     * @test
     */
    public function noParameter()
    {
        $this->builder->shouldReceive('hasDefinition')->once()->andReturn(true);
        $this->builder->shouldReceive('hasParameter')->once()->andReturn(false);

        $this->getPass()->process($this->builder);
    }

    /**
     * @test
     */
    public function notArray()
    {
        $this->builder->shouldReceive('hasDefinition')->once()->andReturn(true);
        $this->builder->shouldReceive('hasParameter')->once()->andReturn(true);
        $this->builder->shouldReceive('getDefinition')->once()->andReturn($this->definition);
        $this->builder->shouldReceive('getParameter')->once()->andReturnNull();

        $this->getPass()->process($this->builder);
    }

    /**
     * @test
     */
    public function loadTypes()
    {
        $this->builder->shouldReceive('hasDefinition')->once()->andReturn(true);
        $this->builder->shouldReceive('hasParameter')->once()->andReturn(true);
        $this->builder->shouldReceive('getDefinition')->once()->andReturn($this->definition);
        $this->builder->shouldReceive('getParameter')->once()->andReturn(array(
            'myType' => array(
                'type' => 'myType',
                'css' => 'myClass'
            )
        ));

        $this->definition->shouldReceive('addMethodCall')->once()->andReturnNull();

        $this->getPass()->process($this->builder);
    }

    public function getPass()
    {
        return new CustomCssPass();
    }

}


text:
import plotly as py
import plotly.graph_objs as go

import utils.names as names
from utils.csvparser import parse
from utils.exporter import export
from utils.args import args

raw_data = parse(args['data_files'], args['start_date'], args['end_date'])

sleep_durations = []
nap_durations = []
for date, rests in raw_data.items():
    has_sleep = has_nap = False
    sleep_total = nap_total = 0
    for r in rests:
        rest, wake, is_nap = r
        delta_h = round((wake - rest).seconds / 3600)
        if is_nap:
            has_nap = True
            nap_total += delta_h
        else:
            has_sleep = True
            sleep_total += delta_h
    # count sleepless nights in the histogram
    if has_sleep or sleep_total == 0:
        sleep_durations.append(sleep_total)
    # however, ignore napless days
    if has_nap:
        nap_durations.append(nap_total)

durations = list(range(0, 13))
sleep_hist = [sleep_durations.count(i) for i in durations]
sleep_trace = go.Bar(x=durations, y=sleep_hist, name='Hours Slept')
nap_hist = [nap_durations.count(i) for i in durations]
nap_trace = go.Bar(x=durations, y=nap_hist, name='Hours Napped')

dates = list(raw_data.keys())

data = go.Data([sleep_trace, nap_trace])
layout = go.Layout(title=names.graph_title('Hours Slept Per Day', dates),
                   xaxis={'title': 'Hours Slept', 'dtick': 1},
                   yaxis={'title': 'Number of Days', 'dtick': 1})
figure = go.Figure(data=data, layout=layout)

export(figure, __file__, dates)


text:
namespace SciHub.Web.Areas.ShortStory.Controllers
{
    using System.Linq;
    using System.Web.Mvc;
    using Common.Constants;
    using Infrastructure.Mapping;
    using Microsoft.AspNet.Identity;
    using Services.Data.Contracts;
    using ViewModels.ShortStories;
    using Web.Controllers;
    using SciHub.Services.Data.Contracts.Comment;
    using SciHub.Web.Areas.Movie.ViewModels.Comments;
    using SciHub.Web.Areas.ShortStory.ViewModels.Comments;

    public class ShortStoriesController : BaseController
    {
        private readonly IShortStoriesService stories;
        private readonly IShortStoryCommentsService comments;

        public ShortStoriesController(IShortStoriesService stories, IShortStoryCommentsService comments)
        {
            this.stories = stories;
            this.comments = comments;
        }

        [HttpGet]
        public ActionResult Index(int id = 1, string order = "newest", string criteria = "")
        {

            if (order != "newest" && order != "top")
            {
                this.Response.StatusCode = 412;
                return this.Content("Order not right");
            }

            var page = id;
            var pagedStories = this.stories.GetAllWithPaging(page, WebConstants.AllShortStoriesPageSize, order, criteria);

            var cachedViewModel = this.Cache.Get("shortStoriesPaged", () => new ShortStoriesPageableListViewModel()
            {
                CurrentPage = page,
                AllItemsCount = pagedStories.AllItemsCount,
                TotalPages = pagedStories.TotalPages,
                ShortStories = pagedStories.ShortStories.To<AllShortStoriesShortStoryViewModel>().ToList()
            }, WebConstants.ShortStoriesCacheTime);

            return this.View(cachedViewModel);
        }

        [HttpGet]
        public ActionResult Details(int id)
        {
            var story = this.stories.GetById(id);
            var viewModel = this.Mapper.Map(story, new ShortStoryDetailsViewModel());
            if (story == null)
            {
                return this.Content("Short story with this id was not found");
            }
            return this.View(viewModel);
        }

        [Authorize]
        [HttpPost]
        public ActionResult Details(int id, float value)
        {
            if (value > 5)
            {
                value = 5;
            }

            if (value < 1)
            {
                value = 1;
            }
            this.stories.Rate(id, value, this.User.Identity.GetUserId());
            return this.RedirectToAction("Details");
        }

        [HttpGet]
        public ActionResult ShortStoriesByAuthor(string id)
        {
            var topStories = this.stories.GetAuthorStories(id).ToList();

            var viewModel = new ShortStoriesByAuthorListViewModel
            {
                ShortStories = topStories
            };

            return this.View(viewModel);
        }

        [HttpGet]
        public ActionResult ShortStoriesByTag(int id)
        {

            var topStories = this.stories.GetTagStories(id).ToList();

            var viewModel = new ShortStoriesByAuthorListViewModel
            {
                ShortStories = topStories
            };

            return this.View(viewModel);
        }

        [HttpGet]
        public ActionResult AddComment(int id)
        {
            var viewModel = new ShortStoryCommentInputModel()
            {
                Content = string.Empty,
                ShortStoryId = id

            };
            return this.PartialView("_AddComment", viewModel);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult AddComment(ShortStoryCommentInputModel comment)
        {
            if (!this.User.Identity.IsAuthenticated)
            {
                this.Response.StatusCode = 401;
                return this.Content("Access is denied");
            }

            if (comment == null || !this.ModelState.IsValid)
            {
                this.Response.StatusCode = 400;
                return this.Content("Bad request");
            }

            var newComment = this.comments.Add(comment.Content, comment.ShortStoryId, this.User.Identity.GetUserId());
            if (newComment == null)
            {
                this.Response.StatusCode = 400;
                return this.Content("Bad request.");
            }

            var viewModel = this.Mapper.Map<ShortStoryCommentViewModel>(newComment);

            return this.PartialView("_ShortStoryComment", viewModel);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#CC2B12" />
    <corners android:bottomRightRadius="50dip"
        android:bottomLeftRadius="50dip"
        android:topRightRadius="50dip"
        android:topLeftRadius="50dip"/>
</shape>


text:
'use strict';

const models = require('./index');

/**
 * @class
 * Initializes a new instance of the HybridConnectionLimits class.
 * @constructor
 * Hybrid Connection limits contract. This is used to return the plan limits of
 * Hybrid Connections.
 *
 * @member {number} [current] The current number of Hybrid Connections.
 *
 * @member {number} [maximum] The maximum number of Hybrid Connections allowed.
 *
 */
class HybridConnectionLimits extends models['Resource'] {
  constructor() {
    super();
  }

  /**
   * Defines the metadata of HybridConnectionLimits
   *
   * @returns {object} metadata of HybridConnectionLimits
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'HybridConnectionLimits',
      type: {
        name: 'Composite',
        className: 'HybridConnectionLimits',
        modelProperties: {
          id: {
            required: false,
            readOnly: true,
            serializedName: 'id',
            type: {
              name: 'String'
            }
          },
          name: {
            required: false,
            serializedName: 'name',
            type: {
              name: 'String'
            }
          },
          kind: {
            required: false,
            serializedName: 'kind',
            type: {
              name: 'String'
            }
          },
          location: {
            required: true,
            serializedName: 'location',
            type: {
              name: 'String'
            }
          },
          type: {
            required: false,
            serializedName: 'type',
            type: {
              name: 'String'
            }
          },
          tags: {
            required: false,
            serializedName: 'tags',
            type: {
              name: 'Dictionary',
              value: {
                  required: false,
                  serializedName: 'StringElementType',
                  type: {
                    name: 'String'
                  }
              }
            }
          },
          current: {
            required: false,
            readOnly: true,
            serializedName: 'properties.current',
            type: {
              name: 'Number'
            }
          },
          maximum: {
            required: false,
            readOnly: true,
            serializedName: 'properties.maximum',
            type: {
              name: 'Number'
            }
          }
        }
      }
    };
  }
}

module.exports = HybridConnectionLimits;


text:
/**
 * {@link org.apache.solr.schema.IndexSchema} and {@link org.apache.solr.schema.FieldType}
 * implementations for powering schema.xml
 */
package org.apache.solr.schema;


text:
package org.apache.camel.component.file.remote;

import com.jcraft.jsch.ChannelSftp;

public class SftpRemoteFileJCraft implements SftpRemoteFile<ChannelSftp.LsEntry> {

    private final ChannelSftp.LsEntry entry;

    public SftpRemoteFileJCraft(ChannelSftp.LsEntry entry) {
        this.entry = entry;
    }

    @Override
    public ChannelSftp.LsEntry getRemoteFile() {
        return entry;
    }

    @Override
    public String getFilename() {
        return entry.getFilename();
    }

    @Override
    public String getLongname() {
        return entry.getLongname();
    }

    @Override
    public boolean isDirectory() {
        return entry.getAttrs().isDir();
    }

    @Override
    public long getFileLength() {
        return entry.getAttrs().getSize();
    }

    @Override
    public long getLastModified() {
        return entry.getAttrs().getMTime() * 1000L;
    }
}


text:
package org.ohdsi.webapi.ircalc;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

/**
 *
 * @author Chris Knoll <cknoll@ohdsi.org>
 */
public interface IncidenceRateAnalysisRepository extends CrudRepository<IncidenceRateAnalysis, Integer> {

  @Query("select ira from IncidenceRateAnalysis AS ira LEFT JOIN FETCH ira.details as d")
  public Iterable<IncidenceRateAnalysis> findAll();

}


text:
$root = $PSScriptRoot
$src = "$root\..\src"
$samples = "$root\..\samples"
$tools = "$root\..\tools"

Task download-nuget `
{
    if (!(Test-Path $tools))
    {
        New-Item -ItemType Directory $tools
    }

    Install-NugetCli -Destination $tools
}

Task get-version `
{
    $script:Version = GitVersion.exe /showvariable MajorMinorPatch
}


text:
<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Messages {
    private $ci;

    function __construct($params = array()) {
        $this->ci = & get_instance();
        $this->ci->load->library('session');
    }

    function clear($type = null) {
        if (!empty($type)) {
            $messages = $this->ci->session->userdata('messages');
            if (!is_array($messages)) {
                $messages = array();
            }

            if (array_key_exists($type, $messages)) {
                unset($messages[$type]);
            }

            $this->ci->session->set_userdata('messages', $messages);
        } else {
            $this->ci->session->set_userdata('messages', array());
        }
    }

    function add($message, $type = 'message') {
        $messages = $this->ci->session->userdata('messages');

        if (!is_array($messages)) {
            $messages = array();
        }

        if (is_a($message, 'Exception')) {
            $message = $message->getMessage();
            $type = 'error';
        }

        if ((!isset($messages[$type]) || !in_array($message, $messages[$type])) && is_string($message) && $message) {
            $messages[$type][] = $message;
        }

        $this->ci->session->set_userdata('messages', $messages);
    }

    function count($type = null) {
        $messages = $this->ci->session->userdata('messages');
        if (!is_array($messages)) {
            $messages = array();
        }

        if (!empty($type)) {
            if (array_key_exists($type, $messages)) {
                return count($messages[$type]);
            } else {
                return 0;
            }
        }

        $i = 0;
        foreach ($messages as $type => $m) {
            $i += count($messages[$type]);
        }
        return $i;
    }

    function get($type = null) {
        $messages = $this->ci->session->userdata('messages');
        if (!is_array($messages)) {
            $messages = array();
        }

        if (!empty($type)) {
            if (array_key_exists($type, $messages)) {
                $messages = $messages[$type];
                $this->clear($type);
                return $messages;
            } else {
                return array();
            }
        }

        $this->clear();
        return $messages;
    }

    public function generateBootstrap($messages, $type = 'error')
    {
        if ($type == 'error')
            $type = 'danger';

        $html = '
';
        $html .= '<button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>';

        foreach ($messages as $text)
            $html .= '
' . $text . '
';

        $html .= '
';

        return $html;
    }

    public function show($type = null)
    {
        $this->resolveValidationErrors();

        $messages = $this->get($type);

        $html = '';

        if (!$type) {
            foreach ($messages as $type => $msg) {
                $html .= $this->generateBootstrap($msg, $type);
            }
        } else {
            $html .= $this->generateBootstrap($messages, $type);
        }

        return $html;
    }

    public function resolveValidationErrors()
    {
        if (FALSE === ($OBJ =& _get_validation_object())) {
            // No action
        } else {
            $errors = $OBJ->error_array();

            foreach ($errors as $error) {
                $this->add($error, 'error');
            }
        }
    }

    public function keepValidationErrors()
    {
        $this->resolveValidationErrors();
    }
}


text:
class EndorsementsController < ApplicationController
  before_filter :authorize

  def destroy
    @endo = Endorsement.find(params[:id])
    @endo.destroy
    redirect_to admin_path
  end

  private

  def authorize
    if !session[:user_id]
      redirect_to root_path
    end
    if session[:user_id]
      if User.find_by(id: session[:user_id]).access != "admin"
        redirect_to root_path
      end
    end
  end
end


text:
angular.module('starter', ['ionic', 'starter.controllers'])

    .run(function ($ionicPlatform) {
        $ionicPlatform.ready(function () {
            // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
            // for form inputs)
            if (window.cordova && window.cordova.plugins.Keyboard) {
                cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
            }
            if (window.StatusBar) {
                // org.apache.cordova.statusbar required
                StatusBar.styleDefault();
            }
        });
    })

    .config(function ($stateProvider, $urlRouterProvider) {
        $stateProvider

            .state('app', {
                url: "/app",
                abstract: true,
                templateUrl: "templates/menu.html",
                controller: 'AppCtrl'
            })

            .state('app.mydailybudgetmonthlygoals', {
                url: "/my-daily-budget/monthly-goals",
                views: {
                    'menuContent': {
                        templateUrl: "templates/my-daily-budget-show-monthly-goals.html",
                        controller: 'MyDailyBudgetMonthlyGoalsController'
                    }
                }
            })

            .state('app.mydailybudget', {
                url: "/my-daily-budget/:monthly_goal_id",
                views: {
                    'menuContent': {
                        templateUrl: "templates/my-daily-budget.html",
                        controller: 'MyDailyBudgetController'
                    }
                }
            })

            .state('app.monthlygoals', {
                url: "/monthly-goals",
                views: {
                    'menuContent': {
                        templateUrl: "templates/monthly-goals.html",
                        controller: "MonthlyGoalController"
                    }
                }
            })
            .state('app.monthlygoals-new', {
                url: "/monthly-goals/new",
                views: {
                    'menuContent': {
                        templateUrl: "templates/monthly-goal-new.html",
                        controller: "MonthlyGoalNewController"
                    }
                }
            })

            .state('app.monthlygoals-edit', {
                url: '/monthly-goals/:monthly_goal_id/edit',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/monthly-goal-new.html',
                        controller: 'MonthlyGoalNewController'
                    }
                }
            })

            .state('app.purchases-months', {
                url: "/purchases",
                views: {
                    'menuContent': {
                        templateUrl: "templates/purchases-months.html",
                        controller: 'ListMonthPurchaseController'
                    }
                }
            })

            .state('app.purchases', {
                url: "/purchases/:year/:month",
                views: {
                    'menuContent': {
                        templateUrl: "templates/purchases.html",
                        controller: 'ListPurchaseController'
                    }
                }
            })

            .state('app.purchases-add', {
                url: "/purchase/new",
                views: {
                    'menuContent': {
                        templateUrl: "templates/purchase-form.html",
                        controller: 'NewPurchaseController'
                    }
                }
            })

            .state('app.purchases-edit', {
                url: "/purchase/:purchase_id/edit",
                views: {
                    'menuContent': {
                        templateUrl: "templates/purchase-form.html",
                        controller: 'EditPurchaseController'
                    }
                }
            });

        // if none of the above states are matched, use this as the fallback
        $urlRouterProvider.otherwise('/app/my-daily-budget/monthly-goals');
    })

    .factory("transformRequestAsFormPost", function () {

        // I prepare the request data for the form post.
        function transformRequest(data) {
            return(serializeData(data));
        }

        // Return the factory value.
        return( transformRequest );

        // ---
        // PRVIATE METHODS.
        // ---

        // I serialize the given Object into a key-value pair string. This
        // method expects an object and will default to the toString() method.
        // --
        // NOTE: This is an atered version of the jQuery.param() method which
        // will serialize a data collection for Form posting.
        // --
        // https://github.com/jquery/jquery/blob/master/src/serialize.js#L45
        function serializeData(data) {

            // If this is not an object, defer to native stringification.
            if (!angular.isObject(data)) {

                return( ( data == null ) ? "" : data.toString() );

            }

            var buffer = [];

            // Serialize each key in the object.
            for (var name in data) {

                if (!data.hasOwnProperty(name)) {

                    continue;

                }

                var value = data[ name ];

                buffer.push(
                    encodeURIComponent(name) +
                        "=" +
                        encodeURIComponent(( value == null ) ? "" : value)
                );

            }

            // Serialize the buffer and clean it up for transportation.
            var source = buffer
                    .join("&")
                    .replace(/%20/g, "+")
                ;

            return( source );

        }

    });


text:
import dtf

from setuptools import setup
from sys import version_info

REQUIRES = ['pyyaml']

if version_info < (2, 7):
    # no argparse in 2.6 standard
    REQUIRES.append('argparse')

setup(
    name='dtf',
    maintainer='tychoish',
    maintainer_email='sam@tychoish.com',
    description='Documentation Testing Framework',
    version=dtf.__version__,
    license='Apache',
    url='http://cyborginstitute.org/projects/dtf',
    packages=['dtf'],
    install_requires=REQUIRES,
    test_suite=None,
    classifiers=[
        'Environment :: Console',
        'Intended Audience :: Developers',
        'Topic :: Documentation',
        'Topic :: Software Development :: Testing',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'License :: OSI Approved :: Apache Software License',
    ],
    entry_points={
        'console_scripts': [
            'dtf = dtf.dtf:main',
            ],
        }
    )


text:
declare enum TKListViewScrollDirection {
    TKListViewScrollDirectionVertical,
    TKListViewScrollDirectionHorizontal
}

declare enum TKListViewItemAlignment {
    TKListViewItemAlignmentStretch,
    TKListViewItemAlignmentLeft,
    TKListViewItemAlignmentCenter,
    TKListViewItemAlignmentRight
}

declare enum TKListViewItemAnimation {
    TKListViewItemAnimationDefault,
    TKListViewItemAnimationFade,
    TKListViewItemAnimationScale,
    TKListViewItemAnimationSlide
}

declare enum TKListViewReorderMode {
    TKListViewReorderModeWithHandle,
    TKListViewReorderModeWithLongPress
}

declare enum TKListViewSelectionBehavior {
    TKListViewSelectionBehaviorNone,
    TKListViewSelectionBehaviorPress,
    TKListViewSelectionBehaviorLongPress
}

declare enum TKListViewLoadOnDemandMode {
    TKListViewLoadOnDemandModeNone,
    TKListViewLoadOnDemandModeManual,
    TKListViewLoadOnDemandModeAuto
}

declare class TKListViewLinearLayout extends UICollectionViewLayout {

    public static new(): TKListViewLinearLayout;

    public scrollDirection: TKListViewScrollDirection;
    public itemInsertAnimation: TKListViewItemAnimation;
    public itemDeleteAnimation: TKListViewItemAnimation;
    public itemAppearAnimation: TKListViewItemAnimation;
    public animationDuration: number;
    public itemAlignment: TKListViewItemAlignment;
    public itemSpacing: number;
    public itemSize: CGSize;
}

declare class TKListViewGridLayout extends TKListViewLinearLayout {
    public static new(): TKListViewGridLayout;

    public spanCount: number;
    public lineSpacing: number;
}

declare class TKListViewStaggeredLayout extends TKListViewGridLayout {
    public static new(): TKListViewStaggeredLayout;

    public alignLastLine: boolean;
}

declare class TKListViewStaggeredLayoutDelegate {

}

export interface TKListViewDelegate {

}

declare class TKDataSourceFilterDescriptor {

}

declare class TKDataSourceSortDescriptor {

}

declare class TKDataSourceGroupDescriptor {

}

declare class TKDataSource extends NSObject implements TKListViewDataSource {

    public itemSource: any;
    public items: NSArray;
    public currentItem: any;
    public displayKey: NSString;
    public valueKey: NSString;
    public groupItemSourceKey: NSString;

    public formatter: NSFormatter;
    public allowItemsReorder: boolean;
    public reloadData(): void;

    public static new();
    public static alloc();

    public initWithItemSource(itemSource: any): TKDataSource;
    public initWithArray(items: NSArray): TKDataSource;
    public initWithArrayDisplayKey(items: NSArray, displayKey: NSString): TKDataSource;
    public initWithArrayDisplayKeyValueKey(items: NSArray, displayKey: NSString, valueKey: NSString): TKDataSource;

    public initWithJSONString(str: NSString): TKDataSource;
    public loadDataFromJSONStringRootItemKeyPath(string: NSString, rootItemKeyPath: NSString): TKDataSource;

    public loadDataFromJSONStringOfTypeRootItemKeyPath(string: NSString, foType: NSString, rootItemKeyPath: NSString): TKDataSource;

    public filterDescriptors: NSArray;
    public addFilterDescriptor(filterDescriptor: TKDataSourceFilterDescriptor): void;
    public removeFilterDescriptor(filterDescriptor: TKDataSourceFilterDescriptor): void;
    public removeAllFilterDescriptors(): void;

    public sortDescriptors: NSArray;
    public addSortDescriptor(sortDescriptor: TKDataSourceSortDescriptor): void;
    public removeSortDescriptor(sortDescriptor: TKDataSourceSortDescriptor): void;
    public removeAllSortDescriptors(): void;

    public groupDescriptors: NSArray;
    public addGroupDescriptor(groupDescriptor: TKDataSourceGroupDescriptor): void;
    public removeGroupDescriptor(groupDescriptor: TKDataSourceGroupDescriptor): void;
    public removeAllGroupDescriptors(): void;

    //TKListViewDataSource
    listViewNumberOfItemsInSection(listView: TKListView, section: number): number;
    listViewCellForItemAtIndexPath(listView: TKListView, indexPath: NSIndexPath): TKListViewCell;
    numberOfSectionsInListView(listView: TKListView): number;
    listViewViewForSupplementaryElementOfKindAtIndexPath(listView: TKListView, kind: NSString, indexPath: NSIndexPath): TKListViewReusableCell;
}

declare class TKListViewLoadOnDemandView extends UIView {

}

declare class TKListViewPullToRefreshView extends UIView {
    public static new(): TKListViewPullToRefreshView;
    public activityIndicator: UIActivityIndicatorView;
    public startAnimating(): void;
    public stopAnimating(): void;
}

declare class TKListViewReusableCell extends UICollectionViewCell {
    public textLabel: UILabel;
}

declare class TKListViewCell extends TKListViewReusableCell {
    public static new(): TKListViewCell;
    public swipeBackgroundView: UIView;
    public imageView: UIImageView;
    public reorderHandle: UIView;
    public detailTextLabel: UILabel;
    public contentInsets: UIEdgeInsets;
}

declare class TKListView extends UIView implements UICollectionViewDataSource, UICollectionViewDelegate {

    public static new(): TKListView;

    public layout: TKListViewLinearLayout;

    public dataSource: TKListViewDataSource;

    public delegate: TKListViewDelegate;

    public allowsMultipleSelection: boolean;
    public allowsCellReorder: boolean;
    public allowsCellSwipe: boolean;
    public allowsPullToRefresh: boolean;
    public cellSwipeLimits: UIEdgeInsets;
    public cellSwipeTreshold: number;//CGFloat;
    public cellSwipeAnimationDuration: number;//  CGFloat;
    public autoScrollTreshold: number; //CGFloat;
    public pullToRefreshTreshold: number; /// CGFloat
    public loadOnDemandMode: TKListViewLoadOnDemandMode;
    public loadOnDemandBufferSize: number;// NSInteger
    public contentInset: UIEdgeInsets;
    public contentOffset: CGPoint;
    public scrollDirection: TKListViewScrollDirection;
    public selectionBehavior: TKListViewSelectionBehavior;
    public pullToRefreshView: TKListViewPullToRefreshView;
    public loadOnDemandView: TKListViewLoadOnDemandView;

    public reloadData();

    public insertItemsAtIndexPaths(indexPaths: any);
    public deleteItemsAtIndexPaths(indexPaths: any);

    public selectItemAtIndexPath(indexPath: NSIndexPath);
    public deselectItemAtIndexPath(indexPath: NSIndexPath);

    //public api
    public registerClassForCellWithReuseIdentifier(classInfo: any, cellName: string);
    public dequeueReusableCellWithReuseIdentifierForIndexPath(identifier: NSString, indexPath: NSIndexPath): any;;

    public scrollToItemAtIndexPathAtScrollPositionAnimated(indexPath: NSIndexPath, scrollPosition: UICollectionViewScrollPosition, animated: boolean);
    public didRefreshOnPull();
    public didLoadDataOnDemand();

    //UICollectionViewDataSource protocol methods
    collectionViewNumberOfItemsInSection(collectionView: UICollectionView, section: number): number;
    collectionViewCellForItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): UICollectionViewCell;
    numberOfSectionsInCollectionView(collectionView: UICollectionView): number;
    collectionViewViewForSupplementaryElementOfKindAtIndexPath(collectionView: UICollectionView, kind: string, indexPath: NSIndexPath): UICollectionReusableView;

    //UICollectionViewDelegate protocol methods
    collectionViewShouldHighlightItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): boolean;
    collectionViewDidHighlightItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): void;
    collectionViewDidUnhighlightItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): void;
    collectionViewShouldSelectItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): boolean;
    collectionViewShouldDeselectItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): boolean;
    collectionViewDidSelectItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): void;
    collectionViewDidDeselectItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): void;
    collectionViewWillDisplayCellForItemAtIndexPath(collectionView: UICollectionView, cell: UICollectionViewCell, indexPath: NSIndexPath): void;
    collectionViewWillDisplaySupplementaryViewForElementKindAtIndexPath(collectionView: UICollectionView, view: UICollectionReusableView, elementKind: string, indexPath: NSIndexPath): void;
    collectionViewDidEndDisplayingCellForItemAtIndexPath(collectionView: UICollectionView, cell: UICollectionViewCell, indexPath: NSIndexPath): void;
    collectionViewDidEndDisplayingSupplementaryViewForElementOfKindAtIndexPath(collectionView: UICollectionView, view: UICollectionReusableView, elementKind: string, indexPath: NSIndexPath): void;
    collectionViewShouldShowMenuForItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): boolean;
    collectionViewCanPerformActionForItemAtIndexPathWithSender(collectionView: UICollectionView, action: any, indexPath: NSIndexPath, sender: any): boolean;
    collectionViewPerformActionForItemAtIndexPathWithSender(collectionView: UICollectionView, action: any, indexPath: NSIndexPath, sender: any): void;
    collectionViewTransitionLayoutForOldLayoutNewLayout(collectionView: UICollectionView, fromLayout: UICollectionViewLayout, toLayout: UICollectionViewLayout): UICollectionViewTransitionLayout;

}

interface TKListViewDelegate extends UIScrollViewDelegate {
    listViewShouldHighlightItemAtIndexPath(listView: TKListView, indexPath: NSIndexPath): boolean;
    listViewDidHighlightItemAtIndexPath(listView: TKListView, indexPath: NSIndexPath): void;
    listViewDidUnhighlightItemAtIndexPath(listView: TKListView, indexPath: NSIndexPath): void;
    listViewShouldSelectItemAtIndexPath(listView: TKListView, indexPath: NSIndexPath): boolean;
    listViewShouldDeselectItemAtIndexPath(listView: TKListView, indexPath: NSIndexPath): boolean;
    listViewDidSelectItemAtIndexPath(listView: TKListView, indexPath: NSIndexPath): void;
    listViewDidDeselectItemAtIndexPath(listView: TKListView, indexPath: NSIndexPath): void;
    listViewDidReorderItemFromIndexPathToIndexPath(listView: TKListView, originalIndexPath: NSIndexPath, targetIndexPath: NSIndexPath);
    listViewShouldSwipeCellAtIndexPath(listView: TKListView, cell: TKListViewCell, indexPath: NSIndexPath): boolean;
    listViewDidSwipeCellAtIndexPathWithOffset(listView: TKListView, cell: TKListViewCell, indexPath: NSIndexPath, offset: CGPoint): void;
    listViewDidFinishSwipeCellAtIndexPathWithOffset(listView: TKListView, cell: TKListViewCell, indexPath: NSIndexPath, offset: CGPoint): void;
    listViewDidPullWithOffset(listView: TKListView, offset: CGPoint): void;
    listViewDidLongPressCellAtIndexPath(listView: TKListView, cell: TKListViewCell, indexPath: NSIndexPath): void;
    listViewShouldLoadMoreDataAtIndexPath(listView: TKListView, indexPath: NSIndexPath): boolean;
    listViewShouldRefreshOnPull(listView: TKListView): boolean;

}

interface TKListViewDataSource extends NSObject {
    listViewNumberOfItemsInSection(listView: TKListView, section: number): number;
    listViewCellForItemAtIndexPath(listView: TKListView, indexPath: NSIndexPath): TKListViewCell;
    numberOfSectionsInListView(listView: TKListView): number;
    listViewViewForSupplementaryElementOfKindAtIndexPath(listView: TKListView, kind: NSString, indexPath: NSIndexPath): TKListViewReusableCell;
}


text:
static int disWidth = 30;//全局变量
static int disHeight = 40;//全局变量

#import <UIKit/UIKit.h>

//声明一个枚举类型
typedef NS_ENUM(NSInteger,NoContentType) {
    //自动消失
    Automaticallydisappear = 0,
    //点击消失
    Clicktodisappear = 1
};

@interface Nonetwork : UIView
//提示内容
@property(nonatomic,copy)NSString *Prompt;
//背景视图
@property(nonatomic,strong)UIView *Bagview;
//内容区域
@property(nonatomic,strong)UIView *Contarea;
//警告图标
@property(nonatomic,strong)UIImageView *Warningicon;
//内容文本
@property(nonatomic,strong)UILabel *Contentext;
//提示框消失类型
@property(nonatomic,assign)NSInteger typeDisappear;

//定义一个Block 回调函数
@property(nonatomic,copy) void(^returnsAnEventBlock)();

//弹出视图
-(void)popupWarningview;

@end


text:
import heapq
import random

from gaps.image_analysis import ImageAnalysis
from gaps.individual import Individual

SHARED_PIECE_PRIORITY = -10
BUDDY_PIECE_PRIORITY = -1

class Crossover(object):
    def __init__(self, first_parent, second_parent):
        self._parents = (first_parent, second_parent)
        self._pieces_length = len(first_parent.pieces)
        self._child_rows = first_parent.rows
        self._child_columns = first_parent.columns

        # Borders of growing kernel
        self._min_row = 0
        self._max_row = 0
        self._min_column = 0
        self._max_column = 0

        self._kernel = {}
        self._taken_positions = set()

        # Priority queue
        self._candidate_pieces = []

    def child(self):
        pieces = [None] * self._pieces_length

        for piece, (row, column) in self._kernel.items():
            index = (row - self._min_row) * self._child_columns + (
                column - self._min_column
            )
            pieces[index] = self._parents[0].piece_by_id(piece)

        return Individual(pieces, self._child_rows, self._child_columns, shuffle=False)

    def run(self):
        self._initialize_kernel()

        while len(self._candidate_pieces) > 0:
            _, (position, piece_id), relative_piece = heapq.heappop(
                self._candidate_pieces
            )

            if position in self._taken_positions:
                continue

            # If piece is already placed, find new piece candidate and put it back to
            # priority queue
            if piece_id in self._kernel:
                self.add_piece_candidate(relative_piece[0], relative_piece[1], position)
                continue

            self._put_piece_to_kernel(piece_id, position)

    def _initialize_kernel(self):
        root_piece = self._parents[0].pieces[
            int(random.uniform(0, self._pieces_length))
        ]
        self._put_piece_to_kernel(root_piece.id, (0, 0))

    def _put_piece_to_kernel(self, piece_id, position):
        self._kernel[piece_id] = position
        self._taken_positions.add(position)
        self._update_candidate_pieces(piece_id, position)

    def _update_candidate_pieces(self, piece_id, position):
        available_boundaries = self._available_boundaries(position)

        for orientation, position in available_boundaries:
            self.add_piece_candidate(piece_id, orientation, position)

    def add_piece_candidate(self, piece_id, orientation, position):
        shared_piece = self._get_shared_piece(piece_id, orientation)
        if self._is_valid_piece(shared_piece):
            self._add_shared_piece_candidate(
                shared_piece, position, (piece_id, orientation)
            )
            return

        buddy_piece = self._get_buddy_piece(piece_id, orientation)
        if self._is_valid_piece(buddy_piece):
            self._add_buddy_piece_candidate(
                buddy_piece, position, (piece_id, orientation)
            )
            return

        best_match_piece, priority = self._get_best_match_piece(piece_id, orientation)
        if self._is_valid_piece(best_match_piece):
            self._add_best_match_piece_candidate(
                best_match_piece, position, priority, (piece_id, orientation)
            )
            return

    def _get_shared_piece(self, piece_id, orientation):
        first_parent, second_parent = self._parents
        first_parent_edge = first_parent.edge(piece_id, orientation)
        second_parent_edge = second_parent.edge(piece_id, orientation)

        if first_parent_edge == second_parent_edge:
            return first_parent_edge

    def _get_buddy_piece(self, piece_id, orientation):
        first_buddy = ImageAnalysis.best_match(piece_id, orientation)
        second_buddy = ImageAnalysis.best_match(
            first_buddy, complementary_orientation(orientation)
        )

        if second_buddy == piece_id:
            for edge in [
                parent.edge(piece_id, orientation) for parent in self._parents
            ]:
                if edge == first_buddy:
                    return edge

    def _get_best_match_piece(self, piece_id, orientation):
        for piece, dissimilarity_measure in ImageAnalysis.best_match_table[piece_id][
            orientation
        ]:
            if self._is_valid_piece(piece):
                return piece, dissimilarity_measure

    def _add_shared_piece_candidate(self, piece_id, position, relative_piece):
        piece_candidate = (SHARED_PIECE_PRIORITY, (position, piece_id), relative_piece)
        heapq.heappush(self._candidate_pieces, piece_candidate)

    def _add_buddy_piece_candidate(self, piece_id, position, relative_piece):
        piece_candidate = (BUDDY_PIECE_PRIORITY, (position, piece_id), relative_piece)
        heapq.heappush(self._candidate_pieces, piece_candidate)

    def _add_best_match_piece_candidate(
        self, piece_id, position, priority, relative_piece
    ):
        piece_candidate = (priority, (position, piece_id), relative_piece)
        heapq.heappush(self._candidate_pieces, piece_candidate)

    def _available_boundaries(self, row_and_column):
        (row, column) = row_and_column
        boundaries = []

        if not self._is_kernel_full():
            positions = {
                "T": (row - 1, column),
                "R": (row, column + 1),
                "D": (row + 1, column),
                "L": (row, column - 1),
            }

            for orientation, position in positions.items():
                if position not in self._taken_positions and self._is_in_range(
                    position
                ):
                    self._update_kernel_boundaries(position)
                    boundaries.append((orientation, position))

        return boundaries

    def _is_kernel_full(self):
        return len(self._kernel) == self._pieces_length

    def _is_in_range(self, row_and_column):
        (row, column) = row_and_column
        return self._is_row_in_range(row) and self._is_column_in_range(column)

    def _is_row_in_range(self, row):
        current_rows = abs(min(self._min_row, row)) + abs(max(self._max_row, row))
        return current_rows < self._child_rows

    def _is_column_in_range(self, column):
        current_columns = abs(min(self._min_column, column)) + abs(
            max(self._max_column, column)
        )
        return current_columns < self._child_columns

    def _update_kernel_boundaries(self, row_and_column):
        (row, column) = row_and_column
        self._min_row = min(self._min_row, row)
        self._max_row = max(self._max_row, row)
        self._min_column = min(self._min_column, column)
        self._max_column = max(self._max_column, column)

    def _is_valid_piece(self, piece_id):
        return piece_id is not None and piece_id not in self._kernel

def complementary_orientation(orientation):
    return {"T": "D", "R": "L", "D": "T", "L": "R"}.get(orientation, None)


text:
KEEP_ALIVE=false
keep_running() {
  while ${KEEP_ALIVE};
  do
    echo "Still alive..."
    sleep 10
  done
}

_stop() {
  echo "clearing stuff before stopping.."
  KEEP_ALIVE=false
}

echo "Trapping SIGINT, SIGTERM and SIGKILL"
trap _stop SIGINT
Trap _stop SIGTERM

echo "All is well"
KEEP_ALIVE=true
keep_running


text:
/* global Vue*/
/* global io*/
/* global $*/
'use strict';
var socket = io.connect(GLOBAL.url);

new Vue({
    el: '#content',
    data: {
        nomPage : 'Quizz IT !',
        loading : false,
        isTimeToReply : true,
        error : GLOBAL.error,
        room : GLOBAL.token,
        state: {
            loading : false,
            step : ''
        },
        user: {
          token : '',
          pseudo: '',
          mail:'',
          score: 0,
          debug : ''
        },
        reponse : {
            id : 0,
            text : '',
            button : 'Afficher',
            display : false
        },
        question: {}
    },
    ready: function() {

        this.state.loading = true;
        this.state.step = 'login';
        $('#content').show();

        var that = this;

        socket.on('start-party-users-' + this.room, function (data) {
            var _reponse = {
                id : 0,
                text : '',
                button : 'Afficher',
                display : false
            };

            that.question = data;
            that.state.step = 'game';
            that.reponse = _reponse;
            that.isTimeToReply = true;
            that.nbPointAAjouter = 0;
        });

        socket.on('reload-party-' + this.room, function (data) {
            console.log('reload-party', data);
            that.state.step = 'reload';
        });

        socket.on('fin-temps-reponse', function () {
            console.log('fin-temps-reponse');
            that.isTimeToReply = false;
            that.user.score = that.user.score + that.nbPointAAjouter;
        });

    },
    methods: {
        login: function () {

            var that = this;

            socket.emit('user', { pseudo: this.user.pseudo, room: this.room }, function (data) {
                that.user.token = data.userToken;
                if (that.user.token !== false) {
                    that.state.step = 'wait';
                } else {
                    that.error = 'Désolé, la partie n\'est pas accessible.';
                }
            });
        },
        reply: function(id) {

            this.reponse.id = id;
            this.reponse.text = this.question['reponse' + this.reponse.id];

            var _data = {
                reponse: 'reponse' + this.reponse.id,
                id: this.question.idquestion
            };

            var that = this;

            socket.emit('recolte-reponse', _data, function (data) {
                that.nbPointAAjouter = data;
            });
        },
        display: function () {
            this.reponse.display = this.reponse.display ? false : true;
            this.reponse.button = this.reponse.display ? 'Dissimuler' : 'Afficher';

        },
        // reloadSameParty: function () {
        //     socket.emit('reloadParty', { displayAdmin: false, pseudo: this.pseudo, room: GLOBAL.token}, function (data) {});
        // },
        // reloadAdmin: function () {
        //     socket.emit('reloadParty', { displayAdmin: true, pseudo: this.pseudo, room: GLOBAL.token}, function (dataRetour) {
        //         document.location = "/admin/" + dataRetour['room'];
        //     });
        // },

    }
});


text:
package com.kancolle.server.controller.kcsapi;

import com.kancolle.server.model.kcsapi.start.StartResult;
import com.kancolle.server.model.response.APIResponse;
import com.kancolle.server.service.start.StartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/kcsapi", method = RequestMethod.POST)
public class StartController {

    @Autowired
    private StartService startService;

    @RequestMapping("/api_start2")
    public APIResponse<StartResult> start2() throws Exception {
        StartResult api_data = startService.getStartModel();
        return new APIResponse<StartResult>().setApi_data(api_data);
    }
}


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

#include "kudu/master/master_service.h"

#include <memory>
#include <ostream>
#include <string>
#include <utility>
#include <vector>

#include <boost/optional/optional.hpp>
#include <gflags/gflags.h>
#include <gflags/gflags_declare.h>
#include <glog/logging.h>

#include "kudu/common/common.pb.h"
#include "kudu/common/wire_protocol.h"
#include "kudu/common/wire_protocol.pb.h"
#include "kudu/consensus/metadata.pb.h"
#include "kudu/consensus/replica_management.pb.h"
#include "kudu/gutil/port.h"
#include "kudu/gutil/strings/substitute.h"
#include "kudu/hms/hms_catalog.h"
#include "kudu/master/authz_provider.h"
#include "kudu/master/catalog_manager.h"
#include "kudu/master/location_cache.h"
#include "kudu/master/master.h"
#include "kudu/master/master.pb.h"
#include "kudu/master/master_cert_authority.h"
#include "kudu/master/ts_descriptor.h"
#include "kudu/master/ts_manager.h"
#include "kudu/rpc/remote_user.h"
#include "kudu/rpc/rpc_context.h"
#include "kudu/security/token.pb.h"
#include "kudu/security/token_signer.h"
#include "kudu/security/token_verifier.h"
#include "kudu/server/server_base.h"
#include "kudu/util/debug/trace_event.h"
#include "kudu/util/flag_tags.h"
#include "kudu/util/logging.h"
#include "kudu/util/monotime.h"
#include "kudu/util/net/sockaddr.h"
#include "kudu/util/pb_util.h"
#include "kudu/util/status.h"

DECLARE_bool(hive_metastore_sasl_enabled);
DECLARE_bool(raft_prepare_replacement_before_eviction);
DECLARE_string(hive_metastore_uris);

DEFINE_int32(master_inject_latency_on_tablet_lookups_ms, 0,
             "Number of milliseconds that the master will sleep before responding to "
             "requests for tablet locations.");
TAG_FLAG(master_inject_latency_on_tablet_lookups_ms, unsafe);
TAG_FLAG(master_inject_latency_on_tablet_lookups_ms, hidden);

DEFINE_bool(master_support_connect_to_master_rpc, true,
            "Whether to support the ConnectToMaster() RPC. Used for testing "
            "version compatibility fallback in the client.");
TAG_FLAG(master_support_connect_to_master_rpc, unsafe);
TAG_FLAG(master_support_connect_to_master_rpc, hidden);

DEFINE_bool(master_non_leader_masters_propagate_tsk, false,
            "Whether a non-leader master sends information about its TSKs in "
            "response to a tablet server's heartbeat. This is intended for "
            "tests scenarios only and should not be used elsewhere.");
TAG_FLAG(master_non_leader_masters_propagate_tsk, hidden);

DEFINE_bool(master_client_location_assignment_enabled, true,
            "Whether masters assign locations to connecting clients. "
            "By default they do if the location assignment command is set, "
            "but in some test scenarios it's useful to make masters assign "
            "locations only to tablet servers, but not clients.");
TAG_FLAG(master_client_location_assignment_enabled, hidden);
TAG_FLAG(master_client_location_assignment_enabled, runtime);
TAG_FLAG(master_client_location_assignment_enabled, unsafe);

DEFINE_bool(master_support_authz_tokens, true,
            "Whether the master supports generating authz tokens. Used for "
            "testing version compatibility in the client.");
TAG_FLAG(master_support_authz_tokens, hidden);

using boost::make_optional;
using google::protobuf::Message;
using kudu::consensus::ReplicaManagementInfoPB;
using kudu::pb_util::SecureDebugString;
using kudu::pb_util::SecureShortDebugString;
using kudu::security::SignedTokenPB;
using kudu::security::TablePrivilegePB;
using kudu::server::ServerBase;
using std::shared_ptr;
using std::string;
using std::vector;
using strings::Substitute;

namespace kudu {
namespace master {

namespace {

// If 's' is not OK and 'resp' has no application specific error set,
// set the error field of 'resp' to match 's' and set the code to
// UNKNOWN_ERROR.
template<class RespClass>
void CheckRespErrorOrSetUnknown(const Status& s, RespClass* resp) {
  if (PREDICT_FALSE(!s.ok() && !resp->has_error())) {
    StatusToPB(s, resp->mutable_error()->mutable_status());
    resp->mutable_error()->set_code(MasterErrorPB::UNKNOWN_ERROR);
  }
}

} // anonymous namespace

MasterServiceImpl::MasterServiceImpl(Master* server)
  : MasterServiceIf(server->metric_entity(), server->result_tracker()),
    server_(server) {
}

bool MasterServiceImpl::AuthorizeClient(const Message* /*req*/,
                                        Message* /*resp*/,
                                        rpc::RpcContext* context) {
  return server_->Authorize(context, ServerBase::SUPER_USER | ServerBase::USER);
}

bool MasterServiceImpl::AuthorizeServiceUser(const Message* /*req*/,
                                             Message* /*resp*/,
                                             rpc::RpcContext* context) {
  // We don't allow superusers to pretend to be tablet servers -- there are no
  // operator tools that do anything like this and since we sign requests for
  // tablet servers, we should be extra tight here.
  return server_->Authorize(context, ServerBase::SERVICE_USER);
}

bool MasterServiceImpl::AuthorizeClientOrServiceUser(const Message* /*req*/,
                                                     Message* /*resp*/,
                                                     rpc::RpcContext* context) {
  return server_->Authorize(context, ServerBase::SUPER_USER | ServerBase::USER |
                            ServerBase::SERVICE_USER);
}

bool MasterServiceImpl::AuthorizeSuperUser(const Message* /*req*/,
                                           Message* /*resp*/,
                                           rpc::RpcContext* context) {
  return server_->Authorize(context, ServerBase::SUPER_USER);
}

void MasterServiceImpl::Ping(const PingRequestPB* /*req*/,
                             PingResponsePB* /*resp*/,
                             rpc::RpcContext* rpc) {
  rpc->RespondSuccess();
}

void MasterServiceImpl::TSHeartbeat(const TSHeartbeatRequestPB* req,
                                    TSHeartbeatResponsePB* resp,
                                    rpc::RpcContext* rpc) {
  // If CatalogManager is not initialized don't even know whether
  // or not we will be a leader (so we can't tell whether or not we can
  // accept tablet reports).
  CatalogManager::ScopedLeaderSharedLock l(server_->catalog_manager());
  if (!l.CheckIsInitializedOrRespond(resp, rpc)) {
    return;
  }
  bool is_leader_master = l.leader_status().ok();

  // 2. All responses contain this.
  resp->mutable_master_instance()->CopyFrom(server_->instance_pb());
  resp->set_leader_master(is_leader_master);

  // 3. Register or look up the tserver.
  shared_ptr<TSDescriptor> ts_desc;
  if (req->has_registration()) {
    const auto scheme = FLAGS_raft_prepare_replacement_before_eviction
        ? ReplicaManagementInfoPB::PREPARE_REPLACEMENT_BEFORE_EVICTION
        : ReplicaManagementInfoPB::EVICT_FIRST;
    const auto ts_scheme = req->has_replica_management_info()
        ? req->replica_management_info().replacement_scheme()
        : ReplicaManagementInfoPB::EVICT_FIRST;
    // If the catalog manager is running with some different replica management
    // scheme, report back an error and do not register the tablet server.
    if (scheme != ts_scheme) {
      const auto& ts_uuid = req->common().ts_instance().permanent_uuid();
      const auto& ts_addr = rpc->remote_address().ToString();
      Status s = Status::ConfigurationError(
          Substitute("replica replacement scheme ($0) of the tablet server "
                     "$1 at $2 differs from the catalog manager's ($3); "
                     "they must be run with the same scheme (controlled "
                     "by the --raft_prepare_replacement_before_eviction flag)",
                     ReplicaManagementInfoPB::ReplacementScheme_Name(ts_scheme),
                     ts_uuid, ts_addr,
                     ReplicaManagementInfoPB::ReplacementScheme_Name(scheme)));
      LOG(WARNING) << s.ToString();

      auto* error = resp->mutable_error();
      StatusToPB(s, error->mutable_status());
      error->set_code(MasterErrorPB::INCOMPATIBLE_REPLICA_MANAGEMENT);

      // Yes, this is confusing: the RPC result is success, but the response
      // contains an application-level error.
      rpc->RespondSuccess();
      return;
    }
    Status s = server_->ts_manager()->RegisterTS(req->common().ts_instance(),
                                                 req->registration(),
                                                 &ts_desc);
    if (!s.ok()) {
      LOG(WARNING) << Substitute("Unable to register tserver ($0): $1",
                                 rpc->requestor_string(), s.ToString());
      // TODO(todd): add service-specific errors
      rpc->RespondFailure(s);
      return;
    }
  } else {
    Status s = server_->ts_manager()->LookupTS(req->common().ts_instance(), &ts_desc);
    if (s.IsNotFound()) {
      LOG(INFO) << Substitute("Got heartbeat from unknown tserver ($0) as $1; "
          "Asking this server to re-register.",
          SecureShortDebugString(req->common().ts_instance()), rpc->requestor_string());
      resp->set_needs_reregister(true);

      // Don't bother asking for a full tablet report if we're a follower;
      // it'll just get ignored anyway.
      resp->set_needs_full_tablet_report(is_leader_master);

      rpc->RespondSuccess();
      return;
    }
    if (!s.ok()) {
      LOG(WARNING) << Substitute("Unable to look up tserver for heartbeat "
          "request $0 from $1: $2", SecureDebugString(*req),
          rpc->requestor_string(), s.ToString());
      rpc->RespondFailure(s.CloneAndPrepend("Unable to lookup tserver"));
      return;
    }
  }

  // 4. Update tserver soft state based on the heartbeat contents.
  ts_desc->UpdateHeartbeatTime();
  ts_desc->set_num_live_replicas(req->num_live_tablets());

  // 5. Only leaders handle tablet reports.
  if (is_leader_master && req->has_tablet_report()) {
    Status s = server_->catalog_manager()->ProcessTabletReport(
        ts_desc.get(), req->tablet_report(), resp->mutable_tablet_report(), rpc);
    if (!s.ok()) {
      rpc->RespondFailure(s.CloneAndPrepend("Failed to process tablet report"));
      return;
    }
  }

  // 6. Only leaders sign CSR from tablet servers (if present).
  if (is_leader_master && req->has_csr_der()) {
    string cert;
    Status s = server_->cert_authority()->SignServerCSR(
        req->csr_der(), rpc->remote_user(), &cert);
    if (!s.ok()) {
      rpc->RespondFailure(s.CloneAndPrepend("invalid CSR"));
      return;
    }
    LOG(INFO) << "Signed X509 certificate for tserver " << rpc->requestor_string();
    resp->mutable_signed_cert_der()->swap(cert);
    resp->add_ca_cert_der(server_->cert_authority()->ca_cert_der());
  }

  // 7. Only leaders send public parts of non-expired TSK which the TS doesn't
  //    have, except if the '--master_non_leader_masters_propagate_tsk'
  //    test-only flag is set.
  if ((is_leader_master ||
       PREDICT_FALSE(FLAGS_master_non_leader_masters_propagate_tsk)) &&
      req->has_latest_tsk_seq_num()) {
    auto tsk_public_keys = server_->token_signer()->verifier().ExportKeys(
        req->latest_tsk_seq_num());
    for (auto& key : tsk_public_keys) {
      resp->add_tsks()->Swap(&key);
    }
  }

  rpc->RespondSuccess();
}

void MasterServiceImpl::GetTabletLocations(const GetTabletLocationsRequestPB* req,
                                           GetTabletLocationsResponsePB* resp,
                                           rpc::RpcContext* rpc) {
  CatalogManager::ScopedLeaderSharedLock l(server_->catalog_manager());
  if (!l.CheckIsInitializedAndIsLeaderOrRespond(resp, rpc)) {
    return;
  }

  if (PREDICT_FALSE(FLAGS_master_inject_latency_on_tablet_lookups_ms > 0)) {
    SleepFor(MonoDelta::FromMilliseconds(FLAGS_master_inject_latency_on_tablet_lookups_ms));
  }

  ServerRegistrationPB reg;
  vector<TSDescriptor*> locs;
  for (const string& tablet_id : req->tablet_ids()) {
    // TODO(todd): once we have catalog data. ACL checks would also go here, probably.
    TabletLocationsPB* locs_pb = resp->add_tablet_locations();
    Status s = server_->catalog_manager()->GetTabletLocations(
        tablet_id, req->replica_type_filter(),
        locs_pb,
        /*ts_infos_dict=*/nullptr,
        make_optional<const string&>(rpc->remote_user().username()));
    if (!s.ok()) {
      resp->mutable_tablet_locations()->RemoveLast();

      GetTabletLocationsResponsePB::Error* err = resp->add_errors();
      err->set_tablet_id(tablet_id);
      StatusToPB(s, err->mutable_status());
    }
  }

  rpc->RespondSuccess();
}

void MasterServiceImpl::CreateTable(const CreateTableRequestPB* req,
                                    CreateTableResponsePB* resp,
                                    rpc::RpcContext* rpc) {
  CatalogManager::ScopedLeaderSharedLock l(server_->catalog_manager());
  if (!l.CheckIsInitializedAndIsLeaderOrRespond(resp, rpc)) {
    return;
  }

  Status s = server_->catalog_manager()->CreateTable(req, resp, rpc);
  CheckRespErrorOrSetUnknown(s, resp);
  rpc->RespondSuccess();
}

void MasterServiceImpl::IsCreateTableDone(const IsCreateTableDoneRequestPB* req,
                                          IsCreateTableDoneResponsePB* resp,
                                          rpc::RpcContext* rpc) {
  CatalogManager::ScopedLeaderSharedLock l(server_->catalog_manager());
  if (!l.CheckIsInitializedAndIsLeaderOrRespond(resp, rpc)) {
    return;
  }

  Status s = server_->catalog_manager()->IsCreateTableDone(
      req, resp, make_optional<const string&>(rpc->remote_user().username()));
  CheckRespErrorOrSetUnknown(s, resp);
  rpc->RespondSuccess();
}

void MasterServiceImpl::DeleteTable(const DeleteTableRequestPB* req,
                                    DeleteTableResponsePB* resp,
                                    rpc::RpcContext* rpc) {
  CatalogManager::ScopedLeaderSharedLock l(server_->catalog_manager());
  if (!l.CheckIsInitializedAndIsLeaderOrRespond(resp, rpc)) {
    return;
  }

  Status s = server_->catalog_manager()->DeleteTableRpc(*req, resp, rpc);
  CheckRespErrorOrSetUnknown(s, resp);
  rpc->RespondSuccess();
}

void MasterServiceImpl::AlterTable(const AlterTableRequestPB* req,
                                   AlterTableResponsePB* resp,
                                   rpc::RpcContext* rpc) {
  CatalogManager::ScopedLeaderSharedLock l(server_->catalog_manager());
  if (!l.CheckIsInitializedAndIsLeaderOrRespond(resp, rpc)) {
    return;
  }

  Status s = server_->catalog_manager()->AlterTableRpc(*req, resp, rpc);
  CheckRespErrorOrSetUnknown(s, resp);
  rpc->RespondSuccess();
}

void MasterServiceImpl::IsAlterTableDone(const IsAlterTableDoneRequestPB* req,
                                         IsAlterTableDoneResponsePB* resp,
                                         rpc::RpcContext* rpc) {
  CatalogManager::ScopedLeaderSharedLock l(server_->catalog_manager());
  if (!l.CheckIsInitializedAndIsLeaderOrRespond(resp, rpc)) {
    return;
  }

  Status s = server_->catalog_manager()->IsAlterTableDone(
      req, resp, make_optional<const string&>(rpc->remote_user().username()));
  CheckRespErrorOrSetUnknown(s, resp);
  rpc->RespondSuccess();
}

void MasterServiceImpl::ListTables(const ListTablesRequestPB* req,
                                   ListTablesResponsePB* resp,
                                   rpc::RpcContext* rpc) {
  CatalogManager::ScopedLeaderSharedLock l(server_->catalog_manager());
  if (!l.CheckIsInitializedAndIsLeaderOrRespond(resp, rpc)) {
    return;
  }

  Status s = server_->catalog_manager()->ListTables(
      req, resp, make_optional<const string&>(rpc->remote_user().username()));
  CheckRespErrorOrSetUnknown(s, resp);
  rpc->RespondSuccess();
}

void MasterServiceImpl::GetTableLocations(const GetTableLocationsRequestPB* req,
                                          GetTableLocationsResponsePB* resp,
                                          rpc::RpcContext* rpc) {
  TRACE_EVENT1("master", "GetTableLocations",
               "requestor", rpc->requestor_string());

  CatalogManager::ScopedLeaderSharedLock l(server_->catalog_manager());
  if (!l.CheckIsInitializedAndIsLeaderOrRespond(resp, rpc)) {
    return;
  }

  if (PREDICT_FALSE(FLAGS_master_inject_latency_on_tablet_lookups_ms > 0)) {
    SleepFor(MonoDelta::FromMilliseconds(FLAGS_master_inject_latency_on_tablet_lookups_ms));
  }
  Status s = server_->catalog_manager()->GetTableLocations(
      req, resp, make_optional<const string&>(rpc->remote_user().username()));
  CheckRespErrorOrSetUnknown(s, resp);
  rpc->RespondSuccess();
}

void MasterServiceImpl::GetTableSchema(const GetTableSchemaRequestPB* req,
                                       GetTableSchemaResponsePB* resp,
                                       rpc::RpcContext* rpc) {
  CatalogManager::ScopedLeaderSharedLock l(server_->catalog_manager());
  if (!l.CheckIsInitializedAndIsLeaderOrRespond(resp, rpc)) {
    return;
  }

  Status s = server_->catalog_manager()->GetTableSchema(
      req, resp, make_optional<const string&>(rpc->remote_user().username()),
      FLAGS_master_support_authz_tokens ? server_->token_signer() : nullptr);
  CheckRespErrorOrSetUnknown(s, resp);
  if (resp->has_error()) {
    // If there was an application error, respond to the RPC.
    rpc->RespondSuccess();
    return;
  }
  rpc->RespondSuccess();
}

void MasterServiceImpl::ListTabletServers(const ListTabletServersRequestPB* req,
                                          ListTabletServersResponsePB* resp,
                                          rpc::RpcContext* rpc) {
  vector<std::shared_ptr<TSDescriptor> > descs;
  server_->ts_manager()->GetAllDescriptors(&descs);
  for (const std::shared_ptr<TSDescriptor>& desc : descs) {
    ListTabletServersResponsePB::Entry* entry = resp->add_servers();
    desc->GetNodeInstancePB(entry->mutable_instance_id());
    desc->GetRegistration(entry->mutable_registration());
    entry->set_millis_since_heartbeat(desc->TimeSinceHeartbeat().ToMilliseconds());
    if (desc->location()) entry->set_location(desc->location().get());
  }
  rpc->RespondSuccess();
}

void MasterServiceImpl::ListMasters(const ListMastersRequestPB* req,
                                    ListMastersResponsePB* resp,
                                    rpc::RpcContext* rpc) {
  vector<ServerEntryPB> masters;
  Status s = server_->ListMasters(&masters);
  if (!s.ok()) {
    StatusToPB(s, resp->mutable_error()->mutable_status());
    resp->mutable_error()->set_code(MasterErrorPB::UNKNOWN_ERROR);

    // Continue setting deprecated error status in order to maintain backwards compat.
    StatusToPB(s, resp->mutable_deprecated_error());
  } else {
    for (const ServerEntryPB& master : masters) {
      resp->add_masters()->CopyFrom(master);
    }
  }
  rpc->RespondSuccess();
}

void MasterServiceImpl::GetMasterRegistration(const GetMasterRegistrationRequestPB* req,
                                              GetMasterRegistrationResponsePB* resp,
                                              rpc::RpcContext* rpc) {
  // instance_id must always be set in order for status pages to be useful.
  resp->mutable_instance_id()->CopyFrom(server_->instance_pb());

  CatalogManager::ScopedLeaderSharedLock l(server_->catalog_manager());
  if (!l.CheckIsInitializedOrRespond(resp, rpc)) {
    return;
  }

  Status s = server_->GetMasterRegistration(resp->mutable_registration());
  CheckRespErrorOrSetUnknown(s, resp);
  resp->set_role(server_->catalog_manager()->Role());
  rpc->RespondSuccess();
}

void MasterServiceImpl::ConnectToMaster(const ConnectToMasterRequestPB* /*req*/,
                                        ConnectToMasterResponsePB* resp,
                                        rpc::RpcContext* rpc) {
  CatalogManager::ScopedLeaderSharedLock l(server_->catalog_manager());
  if (!l.CheckIsInitializedOrRespond(resp, rpc)) {
    return;
  }

  // Set the info about the other masters, so that the client can verify
  // it has the full set of info.
  {
    vector<HostPortPB> hostports;
    WARN_NOT_OK(server_->GetMasterHostPorts(&hostports),
                "unable to get HostPorts for masters");
    resp->mutable_master_addrs()->Reserve(hostports.size());
    for (auto& hp : hostports) {
      *resp->add_master_addrs() = std::move(hp);
    }
  }

  const bool is_leader = l.leader_status().ok();
  if (is_leader) {
    resp->add_ca_cert_der(server_->cert_authority()->ca_cert_der());

    // Issue an authentication token for the caller, unless they are
    // already using a token to authenticate or haven't been authenticated
    // by other means. Don't issue a token if it's about to travel back to the
    // client over a non-confidential channel.
    if (rpc->is_confidential() &&
        rpc->remote_user().authenticated_by() != rpc::RemoteUser::AUTHN_TOKEN) {
      string username = rpc->remote_user().username();
      if (username.empty()) {
        static const char* const kErrMsg = "missing name of the remote user";
        StatusToPB(Status::InvalidArgument(kErrMsg),
                   resp->mutable_error()->mutable_status());
        resp->mutable_error()->set_code(MasterErrorPB::UNKNOWN_ERROR);
        rpc->RespondSuccess();
        KLOG_EVERY_N_SECS(WARNING, 60) << Substitute("invalid request from $0: $1",
                                                     rpc->requestor_string(), kErrMsg);
        return;
      }

      SignedTokenPB authn_token;
      Status s = server_->token_signer()->GenerateAuthnToken(username, &authn_token);
      if (!s.ok()) {
        LOG(FATAL) << Substitute("unable to generate signed token for $0: $1",
                                 rpc->requestor_string(), s.ToString());
      }

      // TODO(todd): this might be a good spot for some auditing code?
      resp->mutable_authn_token()->Swap(&authn_token);
    }
  }

  // Add Hive Metastore information.
  if (hms::HmsCatalog::IsEnabled()) {
    auto* metastore_config = resp->mutable_hms_config();
    metastore_config->set_hms_uris(FLAGS_hive_metastore_uris);
    metastore_config->set_hms_sasl_enabled(FLAGS_hive_metastore_sasl_enabled);
    // TODO(dan): set the hms_uuid field.
  }

  // Assign a location to the client if needed.
  auto* location_cache = server_->location_cache();
  if (location_cache != nullptr &&
      PREDICT_TRUE(FLAGS_master_client_location_assignment_enabled)) {
    string location;
    const auto s = location_cache->GetLocation(
        rpc->remote_address().host(), &location);
    if (s.ok()) {
      resp->set_client_location(location);
    } else {
      LOG(WARNING) << Substitute("unable to assign location to client $0@$1: $2",
                                 rpc->remote_user().ToString(),
                                 rpc->remote_address().ToString(),
                                 s.ToString());
    }
  }

  // Rather than consulting the current consensus role, instead base it
  // on the catalog manager's view. This prevents us from advertising LEADER
  // until we have taken over all the associated responsibilities.
  resp->set_role(is_leader ? consensus::RaftPeerPB::LEADER
                           : consensus::RaftPeerPB::FOLLOWER);
  rpc->RespondSuccess();
}

void MasterServiceImpl::ReplaceTablet(const ReplaceTabletRequestPB* req,
                                      ReplaceTabletResponsePB* resp,
                                      rpc::RpcContext* rpc) {
  LOG(INFO) << "ReplaceTablet: received request to replace tablet " << req->tablet_id()
            << " from " << rpc->requestor_string();

  CatalogManager::ScopedLeaderSharedLock l(server_->catalog_manager());
  if (!l.CheckIsInitializedAndIsLeaderOrRespond(resp, rpc)) {
    return;
  }

  Status s = server_->catalog_manager()->ReplaceTablet(req->tablet_id(), resp);
  CheckRespErrorOrSetUnknown(s, resp);
  rpc->RespondSuccess();
}

void MasterServiceImpl::ResetAuthzCache(
    const ResetAuthzCacheRequestPB* /* req */,
    ResetAuthzCacheResponsePB* resp,
    rpc::RpcContext* rpc) {
  LOG(INFO) << Substitute("request to reset authz privileges cache from $0",
                          rpc->requestor_string());
  CheckRespErrorOrSetUnknown(
      server_->catalog_manager()->authz_provider()->ResetCache(), resp);
  rpc->RespondSuccess();
}

bool MasterServiceImpl::SupportsFeature(uint32_t feature) const {
  switch (feature) {
    case MasterFeatures::RANGE_PARTITION_BOUNDS:    FALLTHROUGH_INTENDED;
    case MasterFeatures::ADD_DROP_RANGE_PARTITIONS: FALLTHROUGH_INTENDED;
    case MasterFeatures::REPLICA_MANAGEMENT:
      return true;
    case MasterFeatures::GENERATE_AUTHZ_TOKEN:
      return FLAGS_master_support_authz_tokens;
    case MasterFeatures::CONNECT_TO_MASTER:
      return FLAGS_master_support_connect_to_master_rpc;
    default:
      return false;
  }
}

} // namespace master
} // namespace kudu


text:
using System.Reflection;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("AssemblyInfo")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AssemblyInfo")]
[assembly: AssemblyCopyright("Copyright ©  2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("b2c13e83-cfd1-40f0-8e1e-fd5188c295a0")]

// [assembly: AssemblyVersion("1.0.*")]

[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]


text:
import { ChartConfiguration } from '../models/ChartConfiguration.class';

export interface ChartFactory {
  createChartOptions(chartConf: ChartConfiguration): Object;
}


text:
import { Component, NgZone } from '@angular/core';
import { Board } from '../models/board';
import { BoardService } from '../board-zone/board/board.service';
import { AuthenticationService } from './app-authentication/authentication.service';
import { MdDialog } from '@angular/material';
import { BoardDialogComponent } from './board-dialog/board-dialog.component';
import { Router } from '@angular/router';

@Component({
  selector: 'authentication-zone',
  templateUrl: './authentication-zone.component.html',
  styleUrls: ['./authentication-zone.component.css']
})
export class AuthenticationZoneComponent {
   private authenticated :boolean;

   constructor(private boardService :BoardService,
     private authenticationService :AuthenticationService,
     private zone: NgZone,
     private dialog: MdDialog,
     private router: Router) {
     if(authenticationService.isAuthenticated()) {
       this.getBoard();
     }
   }

   onAuthentication(authentication :[boolean, Board]) {
     console.log(authentication);
     this.zone.run(() => {
       this.authenticated = authentication[0];
     });
     if(this.authenticated) {
       if(authentication.length === 1 || !authentication[1]) {
         this.dialog
         .open(BoardDialogComponent, {
           disableClose: true
         })
         .afterClosed().subscribe(result => {
          this.createBoard(result);
        });
       } else if(authentication[1]) {
         this.boardService.setBoard(authentication[1]);
         this.router.navigateByUrl('/board');
       }
     }
   }

   createBoard(name) {
     this.boardService
     .createBoard(name)
     .subscribe(data => {
           console.log(this.boardService.hasBoard());
           this.router.navigateByUrl('/board');
         },
         error => {
           console.log(error);
      });
   }

   getBoard() {
      this.boardService
     .getLastModifiedBoard()
     .subscribe(data => {
         console.log(data);
         this.router.navigateByUrl('/board');
       },
       error => {
    });
   }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="commonServiceDaoImpl">

    <!--查询所有有效的映射数据-->
    <select id="getCodeMappingAll" resultType="com.java110.entity.mapping.CodeMapping">
        <![CDATA[
            SELECT
              cm.id,
              cm.name,
              cm.domain,
              cm.h_code,
              cm.p_code,
              cm.description,
              cm.create_dt
            FROM
              code_mapping cm
            WHERE cm.status_cd = '0'
		]]>
    </select>

    <!--根据域查询对应的映射关系-->
    <select id="getCodeMappingByDomain" parameterType="com.java110.entity.mapping.CodeMapping"
            resultType="com.java110.entity.mapping.CodeMapping"
    >
        <![CDATA[
            SELECT
              cm.id,
              cm.name,
              cm.domain,
              cm.h_code,
              cm.p_code,
              cm.description,
              cm.create_dt
            FROM
              code_mapping cm
            WHERE cm.status_cd = '0'
            and cm.domain=#{domain}
        ]]>
    </select>

    <!--根据HCode查询映射关系-->
    <select id="getCodeMappingByHCode" parameterType="com.java110.entity.mapping.CodeMapping"
            resultType="com.java110.entity.mapping.CodeMapping"
    >
        <![CDATA[
            SELECT
              cm.id,
              cm.name,
              cm.domain,
              cm.h_code,
              cm.p_code,
              cm.description,
              cm.create_dt
            FROM
              code_mapping cm
            WHERE cm.status_cd = '0'
            and cm.h_code=#{h_code}

        ]]>
    </select>

    <!--根据PCode查询映射关系-->
    <select id="getCodeMappingByPCode" parameterType="com.java110.entity.mapping.CodeMapping"
            resultType="com.java110.entity.mapping.CodeMapping"
    >
        <![CDATA[
            SELECT
              cm.id,
              cm.name,
              cm.domain,
              cm.h_code,
              cm.p_code,
              cm.description,
              cm.create_dt
            FROM
              code_mapping cm
            WHERE cm.status_cd = '0'
            and cm.p_code=#{p_code}
        ]]>
    </select>

    <!--根据PCode查询映射关系-->
    <select id="getCodeMappingByDomainAndHCode" parameterType="com.java110.entity.mapping.CodeMapping"
            resultType="com.java110.entity.mapping.CodeMapping"
    >
        <![CDATA[
            SELECT
              cm.id,
              cm.name,
              cm.domain,
              cm.h_code,
              cm.p_code,
              cm.description,
              cm.create_dt
            FROM
              code_mapping cm
            WHERE cm.status_cd = '0'
            and cm.h_code=#{p_code}
            and cm.domain=#{domain}
        ]]>
    </select>

    <!--根据PCode查询映射关系-->
    <select id="getCodeMappingByDomainAndPCode" parameterType="com.java110.entity.mapping.CodeMapping"
            resultType="com.java110.entity.mapping.CodeMapping"
    >
        <![CDATA[
            SELECT
              cm.id,
              cm.name,
              cm.domain,
              cm.h_code,
              cm.p_code,
              cm.description,
              cm.create_dt
            FROM
              code_mapping cm
            WHERE cm.status_cd = '0'
            and cm.p_code=#{p_code}
            and cm.domain=#{domain}
        ]]>
    </select>

</mapper>


text:
from django.conf.urls import patterns, include, url

urlpatterns = patterns('marcador.views',
    url(r'^user/(?P<username>[-\w]+)/$', 'bookmark_user',
        name='marcador_bookmark_user'),
    url(r'^create/$', 'bookmark_create', name='marcador_bookmark_create'),
    url(r'^edit/(?P<pk>\d+)/$', 'bookmark_edit', name='marcador_bookmark_edit'),
    url(r'^$', 'bookmark_list', name='marcador_bookmark_list'),
)


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

namespace WyriHaximus\TwigView\Lib;

use Cake\Core\App;
use Cake\Core\Plugin;
use FilesystemIterator;
use Iterator;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use RegexIterator;
use WyriHaximus\TwigView\View\TwigView;

/**
 * Class Scanner.
 */
final class Scanner
{
    /**
     * Return all sections (app & plugins) with an Template directory.
     *
     * @return array
     */
    public static function all(): array
    {
        $sections = [];

        foreach (App::path('templates') as $path) {
            if (is_dir($path)) {
                $sections['APP'] = $sections['APP'] ?? [];
                $sections['APP'] = array_merge($sections['APP'], static::iteratePath($path));
            }
        }

        foreach (static::pluginsWithTemplates() as $plugin) {
            $path = Plugin::templatePath($plugin);
            if (is_dir($path)) {
                $sections[$plugin] = $sections[$plugin] ?? [];
                $sections[$plugin] = array_merge($sections[$plugin], static::iteratePath($path));
            }
        }

        return static::clearEmptySections($sections);
    }

    /**
     * Return all templates for a given plugin.
     *
     * @param string $plugin The plugin to find all templates for.
     * @return string[]
     */
    public static function plugin(string $plugin)
    {
        $path = Plugin::templatePath($plugin);
        $templates = static::iteratePath($path);

        return $templates;
    }

    /**
     * Check sections a remove the ones without anything in them.
     *
     * @param array $sections Sections to check.
     * @return array
     */
    protected static function clearEmptySections(array $sections): array
    {
        array_walk($sections, function ($templates, $index) use (&$sections) {
            if (count($templates) === 0) {
                unset($sections[$index]);
            }
        });

        return $sections;
    }

    /**
     * Finds all plugins with a Template directory.
     *
     * @return array
     */
    protected static function pluginsWithTemplates(): array
    {
        $plugins = Plugin::loaded();

        array_walk($plugins, function ($plugin, $index) use (&$plugins) {
            $path = Plugin::templatePath($plugin);

            if (!is_dir($path)) {
                unset($plugins[$index]);
            }
        });

        return $plugins;
    }

    /**
     * Iterage over the given path and return all matching .tpl files in it.
     *
     * @param string $path Path to iterate over.
     * @return string[]
     */
    protected static function iteratePath(string $path): array
    {
        return static::walkIterator(static::setupIterator($path));
    }

    /**
     * Setup iterator for given path.
     *
     * @param string $path Path to setup iterator for.
     * @return \Iterator
     */
    protected static function setupIterator(string $path): Iterator
    {
        return new RegexIterator(new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator(
                $path,
                FilesystemIterator::KEY_AS_PATHNAME |
                FilesystemIterator::CURRENT_AS_FILEINFO |
                FilesystemIterator::SKIP_DOTS
            ),
            RecursiveIteratorIterator::CHILD_FIRST,
            RecursiveIteratorIterator::CATCH_GET_CHILD
        ), '/.*?' . TwigView::EXT . '$/', RegexIterator::GET_MATCH);
    }

    /**
     * Walk over the iterator and compile all templates.
     *
     * @param \Iterator $iterator Iterator to walk.
     * @return string[]
     */
    protected static function walkIterator(Iterator $iterator): array
    {
        $items = [];

        $array = iterator_to_array($iterator);
        uasort($array, function ($a, $b) {
            if ($a == $b) {
                return 0;
            }

            return $a < $b ? -1 : 1;
        });

        foreach ($array as $paths) {
            foreach ($paths as $path) {
                $items[] = $path;
            }
        }

        return $items;
    }
}


text:
local require = require

local app               = require "cp.app"
local Document          = require "cp.highland2.Document"

local bundleID = "com.quoteunquoteapps.highlandapp2"

local highland = app.forBundleID(bundleID)
    :registerWindowType(Document)

return highland