text:
<?php
namespace IComeFromTheNet\BookMe;

/**
 * Events That this library will emmit
 *
 * @author Lewis Dyer <getintouch@icomefromthenet.com>
 * @since 1.0
 *
 */
final class BookMeEvents
{

    /**
     * When a new year is added to the calender this event will
     * be emitted.
     */
    const CALENDAR_ADD = 'bookme.calendar.add';

    /**
     * When a new slot is added and days generate this event will
     * be emitted.
     */
    const SLOT_ADD = 'bookme.slot.add';

    /**
     * When a rollover timeslots into new calendar year
     */
    const SLOT_ROLLOVER = 'bookme.slot.rollover';

    /**
     * When a new member is registerd
     */
    const MEMBER_REGISTER = 'bookme.member.register';

    /**
     * When a new team is registerd
     */
    const TEAM_REGISTER = 'bookme.team.register';

    /**
     * When a member is assigned to a team
     */
    const TEAM_MEMBER_ASSIGN = 'bookme.team.assign';

    /**
     * When a member is removed from a team
     */
    const TEAM_MEMBER_WITHDRAWL = 'bookme.team.withdrawl';

    /**
     * When a schedule is started, note this not emitted when a schedule is carried over
     * from a previous period into new period
     */
    const SCHEDULE_START = 'bookme.schedule.start';

    /**
     * When a schedule has been stopped, no more appointments and no carryover!
     */
    const SCHEDULE_STOP = 'bookme.schedule.stop';

    /**
     * When a stopped schedule is resumed
     *
     */
    const SCHEDULE_RESUME = 'bookme.schedule.resume';

    /**
     * When a rollover a schedule (copy carryon to the next calendar year)
     */
    const SCHEDULE_ROLLOVER = 'bookme.schedule.rollover';

    /**
     * When a rollover of teams members  (create new relations for new schedules)
     */
    const TEAM_ROLLOVER = 'bookme.team.rollover';

    /**
     * When a booking has been sucessfuly scheduled
     */
    const BOOKING_TAKEN = 'bookme.booking.taken';

    /**
     * When a booking has been sucessfuly removed from schedule
     */
    const BOOKING_CLEARED = 'bookme.booking.cleared';

    /**
     * When emitt when a conflict check has completed
     */
    const BOOKING_CONFLICT = 'bookme.booking.conflict';

    /**
     * When a rollover rules
     */
    const RULE_ROLLOVER = 'bookme.rule.rollover';

    /**
     * When a create a new rule
     */
    const RULE_CREATE = 'bookme.rule.create';

    /**
     * When a rule is removed
     */
    const RULE_REMOVE = 'bookme.rule.remove';
}
/* End of File */


text:
export enum Side {
    WHITE,
    BLACK
}

redpajama_set_name: RedPajamaGithub


text:
// 2.A.1.1
if ( condition ) {
  // statements
}

while ( condition ) {
  // statements
}

for ( var i = 0; i < 100; i++ ) {
  // statements
}

var prop;

for ( prop in object ) {
  // statements
}

if ( true ) {
  // statements
} else {
  // statements
}

// 2.B.2.1
// Named Function Declaration
function foo( arg1, argN ) {

}

// Usage
foo( arg1, argN );

// 2.B.2.2
// Named Function Declaration
function square( number ) {
  return number * number;
}

// Usage
square( 10 );

// Really contrived continuation passing style
function square( number, callback ) {
  callback( number * number );
}

square( 10, function( square ) {
  // callback statements
} );

// 2.B.2.3
// Function Expression
var square = function( number ) {
  // Return something valuable and relevant
  return number * number;
};

// Function Expression with Identifier
// This preferred form has the added value of being
// able to call itself and have an identity in stack traces:
var factorial = function factorial( number ) {
  if ( number < 2 ) {
    return 1;
  }

  return number * factorial( number - 1 );
};

// 2.B.2.4
// Constructor Declaration
function FooBar( options ) {

  this.options = options;
}

// Usage
var fooBar = new FooBar( { a: "alpha" } );

fooBar.options;
// { a: "alpha" }

// 2.C.1.1
// Functions with callbacks
foo( function( ) {
  // Note there is no extra space between the first paren
  // of the executing function call and the word "function"
} );

// Function accepting an array, no space
foo( [ "alpha", "beta" ] );

// 2.C.1.2
// Function accepting an object, no space
foo( {
  a: "alpha",
  b: "beta"
} );

// Single argument string literal, no space
foo( "bar" );

// Inner grouping parens, no space
if ( !( "foo" in obj ) ) {

}


text:
<?php

namespace Symfony\Component\Security\Core\Tests\Encoder;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Encoder\SodiumPasswordEncoder;

class SodiumPasswordEncoderTest extends TestCase
{
    protected function setUp()
    {
        if (!SodiumPasswordEncoder::isSupported()) {
            $this->markTestSkipped('Libsodium is not available.');
        }
    }

    public function testValidation()
    {
        $encoder = new SodiumPasswordEncoder();
        $result = $encoder->encodePassword('password', null);
        $this->assertTrue($encoder->isPasswordValid($result, 'password', null));
        $this->assertFalse($encoder->isPasswordValid($result, 'anotherPassword', null));
    }

    public function testBCryptValidation()
    {
        $encoder = new SodiumPasswordEncoder();
        $this->assertTrue($encoder->isPasswordValid('$2y$04$M8GDODMoGQLQRpkYCdoJh.lbiZPee3SZI32RcYK49XYTolDGwoRMm', 'abc', null));
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
     */
    public function testEncodePasswordLength()
    {
        $encoder = new SodiumPasswordEncoder();
        $encoder->encodePassword(str_repeat('a', 4097), 'salt');
    }

    public function testCheckPasswordLength()
    {
        $encoder = new SodiumPasswordEncoder();
        $result = $encoder->encodePassword(str_repeat('a', 4096), null);
        $this->assertFalse($encoder->isPasswordValid($result, str_repeat('a', 4097), null));
        $this->assertTrue($encoder->isPasswordValid($result, str_repeat('a', 4096), null));
    }

    public function testUserProvidedSaltIsNotUsed()
    {
        $encoder = new SodiumPasswordEncoder();
        $result = $encoder->encodePassword('password', 'salt');
        $this->assertTrue($encoder->isPasswordValid($result, 'password', 'anotherSalt'));
    }

    public function testNeedsRehash()
    {
        $encoder = new SodiumPasswordEncoder(4, 11000);

        $this->assertTrue($encoder->needsRehash('dummyhash'));

        $hash = $encoder->encodePassword('foo', 'salt');
        $this->assertFalse($encoder->needsRehash($hash));

        $encoder = new SodiumPasswordEncoder(5, 11000);
        $this->assertTrue($encoder->needsRehash($hash));
    }
}


text:
//******************************************************************************************************
//  ScheduledEmailType.cs - Gbtc
//
//  Copyright © 2017, Grid Protection Alliance.  All Rights Reserved.
//
//  Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
//  the NOTICE file distributed with this work for additional information regarding copyright ownership.
//  The GPA licenses this file to you under the MIT License (MIT), the "License"; you may
//  not use this file except in compliance with the License. You may obtain a copy of the License at:
//
//      http://opensource.org/licenses/MIT
//
//  Unless agreed to in writing, the subject software distributed under the License is distributed on an
//  "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
//  License for the specific language governing permissions and limitations.
//
//  Code Modification History:
//  ----------------------------------------------------------------------------------------------------
//  11/09/2021 - Samuel Robinson
//       Generated original version of source code.
//
//******************************************************************************************************

using GSF.Data.Model;

namespace openXDA.Model
{
    public class ScheduledEmailType : EmailTypeBase
    {

        public bool SMS { get; set; }

        public string TriggerEmailSQL { get; set; }

        public string Schedule { get; set; }

        public int EmailCategoryID { get; set; }
    }
}


text:
<?php

namespace LaravelAdminPanel\Policies;

use LaravelAdminPanel\Contracts\User;
use LaravelAdminPanel\Facades\Admin;
use LaravelAdminPanel\Models\DataType;

class MenuItemPolicy extends BasePolicy
{
    protected static $datatypes = [];

    /**
     * Check if user has an associated permission.
     *
     * @param User   $user
     * @param object $model
     * @param string $action
     *
     * @return bool
     */
    protected function checkPermission(User $user, $model, $action)
    {
        $regex = str_replace('/', '\/', preg_quote(route('admin.dashboard')));
        $slug = preg_replace('/'.$regex.'/', '', $model->link(true));
        $slug = str_replace('/', '', explode('/', ltrim($slug, '/'))[0]);

        if (!isset(self::$datatypes[$slug])) {
            self::$datatypes[$slug] = DataType::where('slug', $slug)->first();
        }

        if ($str = self::$datatypes[$slug]) {
            $slug = $str->slug;
        }

        if ($slug == '') {
            $slug = 'admin';
        }

        // If permission doesn't exist, we can't check it!
        if (!Admin::model('Permission')->where('key', 'browse_'.$slug)->exists()) {
            return true;
        }

        return $user->hasPermission('browse_'.$slug);
    }
}


text:
Even if function is passed as variable.

## Classes: nous, camel case
Even if class is passed as variable.

## Bool variables: positive affirmative sentences, lowercased, underscores
### Yes: with `if` and `and` it reads naturally
```
if user_agrees and conditions_are_met:
    make_offer()
```
### Yes: with `while` and `not` it reads naturally
```
while not tests_are_passed:
    tests.setup()
    tests_are_passed = tests.run()
```
### Yes: subject is obvious from context
```
if form.is_valid:
    Model.from_raw(form.to_raw()).save()
```
### Yes: subject is obvious from context
```
if is_disconnected:
    reconnect()
```

## Contenxt managers: verb in past form
### Yes: `contextmanager` decorator
```
@contextmanager
def opened_connection(address):
    connection_handle = open_connection(address)
    try:
        yield connection_handle
    finally:
        close_connection(connection_handle)

def ask_peer(address):
    with opened_connection(address) as connection_handle:
        send_question_to_peer(connection_handle)
        return receive_answer_from_peer(connection_handle)
```
### Yes: class context manager
```
class OpenedConnection:
    def __init__(self, address):
        self._connection_handle = None
	self._address = address

    def __enter__():
        self._connection_handle = open_connection(self._address)
	return self._connection_handle

    def __exit__():
        close_connection(self._connection_handle)

def ask_peer(address):
    with OpenedConnection(address) as connection_handle:
        send_question_to_peer(connection_handle)
        return receive_answer_from_peer(connection_handle)
```

## Files, Dirs, Paths and File Object

Dirs are easiest part: there is no dir objects, there can be only paths to directories.
All dirs should have suffix `_dir`.

The word _file_ meants either file object (with `.read()` and `.write(...)` methods) or path. If you use `pathlib` or its backport `pathlib2`, you probably never open files using `with open(...) as ...:` because you usually write or read file as a whole and, therefore, you don't need file object. So, if first case, use `_file` suffix and, when working with file objects (it's rare), use `_file_object`.


text:
class Engine
{
	friend class Render;
public:
	Engine();
	virtual ~Engine();

	static Engine& Get() { return *engine; }

	bool ChangeMode(bool fullscreen);
	bool ChangeMode(const Int2& size, bool fullscreen, int hz = 0);
	void DoPseudotick(bool msg_only = false);
	void EngineShutdown();
	void FatalError(cstring err);
	void ShowError(cstring msg, Logger::Level level = Logger::L_ERROR);
	bool Start(StartupOptions& options);
	void UnlockCursor(bool lock_on_focus = true);
	void LockCursor();

	bool IsActive() const { return active; }
	bool IsCursorLocked() const { return locked_cursor; }
	bool IsCursorVisible() const { return cursor_visible; }
	bool IsEngineShutdown() const { return engine_shutdown; }
	bool IsFullscreen() const { return fullscreen; }

	float GetFps() const { return fps; }
	float GetWindowAspect() const { return float(wnd_size.x) / wnd_size.y; }
	HWND GetWindowHandle() const { return hwnd; }
	const Int2& GetWindowSize() const { return wnd_size; }
	Render* GetRender() { return render.get(); }

	void SetTitle(cstring title);
	void SetUnlockPoint(const Int2& pt) { unlock_point = pt; }

	// ----- ZMIENNE -----
	// directx
	Color clear_color;

	CustomCollisionWorld* phy_world;
	std::unique_ptr<SoundManager> sound_mgr;

	// constants
	static const Int2 MIN_WINDOW_SIZE;
	static const Int2 DEFAULT_WINDOW_SIZE;

	CameraBase* cam_base;

protected:
	// funkcje implementowane przez Game
	virtual bool InitGame() = 0;
	virtual void OnChar(char c) = 0;
	virtual void OnCleanup() = 0;
	virtual void OnDraw() = 0;
	virtual void OnReload() = 0;
	virtual void OnReset() = 0;
	virtual void OnResize() = 0;
	virtual void OnTick(float dt) = 0;
	virtual void OnFocus(bool focus, const Int2& activation_point) = 0;

private:
	void Init(StartupOptions& options);
	void AdjustWindowSize();
	void ChangeMode();
	void Cleanup();
	void DoTick(bool update_game);
	long HandleEvent(HWND hwnd, uint msg, uint wParam, long lParam);
	bool MsgToKey(uint msg, uint wParam, byte& key, int& result);
	void InitWindow(StartupOptions& options);
	void PlaceCursor();
	void ShowCursor(bool show);
	void UpdateActivity(bool is_active);
	void WindowLoop();
	bool IsWindowActive();
	void SetWindowSizeInternal(const Int2& size);

	static Engine* engine;
	uint frames;
	float frame_time;
	Timer timer;
	bool engine_shutdown, cursor_visible, replace_cursor, locked_cursor, lock_on_focus;

	// window
	HWND hwnd;
	Int2 wnd_size, real_size, unlock_point, activation_point;
	float fps;
	bool active, fullscreen;

	std::unique_ptr<Render> render;
};


text:
module Azure::SecurityInsights::Mgmt::V2020_01_01
  module Models
    #
    # ThreatIntelligence property bag.
    #
    class ThreatIntelligence

      include MsRestAzure

      # @return [Float] Confidence (must be between 0 and 1)
      attr_accessor :confidence

      # @return [String] Name of the provider from whom this Threat
      # Intelligence information was received
      attr_accessor :provider_name

      # @return [String] Report link
      attr_accessor :report_link

      # @return [String] Threat description (free text)
      attr_accessor :threat_description

      # @return [String] Threat name (e.g. "Jedobot malware")
      attr_accessor :threat_name

      # @return [String] Threat type (e.g. "Botnet")
      attr_accessor :threat_type

      #
      # Mapper for ThreatIntelligence class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'ThreatIntelligence',
          type: {
            name: 'Composite',
            class_name: 'ThreatIntelligence',
            model_properties: {
              confidence: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'confidence',
                type: {
                  name: 'Double'
                }
              },
              provider_name: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'providerName',
                type: {
                  name: 'String'
                }
              },
              report_link: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'reportLink',
                type: {
                  name: 'String'
                }
              },
              threat_description: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'threatDescription',
                type: {
                  name: 'String'
                }
              },
              threat_name: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'threatName',
                type: {
                  name: 'String'
                }
              },
              threat_type: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'threatType',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
<!DOCTYPE html>

	<meta http-equiv="content=-type" content"text/html;charset=utf-8">
	<title></title>


text:
//  SDLScrollableMessageResponse.h
//

#import "SDLRPCResponse.h"

/**
 * Scrollable Message Response is sent, when SDLScrollableMessage has been called
 *
 * Since SmartDeviceLink 2.0
 */

NS_ASSUME_NONNULL_BEGIN

@interface SDLScrollableMessageResponse : SDLRPCResponse

@end

NS_ASSUME_NONNULL_END


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:fresco="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="180dp"
    android:orientation="vertical">

    <com.facebook.drawee.view.SimpleDraweeView
        android:id="@+id/sdv"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_margin="10dp"
        fresco:failureImage="@drawable/loading"
        fresco:retryImage="@drawable/warning"
        fresco:roundedCornerRadius="10dp"
        fresco:roundTopLeft="true"
        fresco:roundTopRight="true"
        fresco:roundBottomLeft="true"
        fresco:roundBottomRight="true"
        fresco:placeholderImage="@color/action_bar_background" />

        <TextView
            android:id="@+id/tv_title"
            android:gravity="center_horizontal"
            android:layout_width="match_parent"
            android:layout_height="25dp"
            android:textSize="18sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/tv_desc"
            android:gravity="center_horizontal"
            android:layout_width="match_parent"
            android:layout_height="25dp"
            android:textSize="16sp" />
</LinearLayout>


text:
package org.apache.flume.conf;

import org.apache.flume.FlumeException;

public class ConfigurationException extends FlumeException {

  /**
   *
   */
  private static final long serialVersionUID = 1L;

  public ConfigurationException(String arg0) {
    super(arg0);
  }

  public ConfigurationException(Throwable arg0) {
    super(arg0);
  }

  public ConfigurationException(String arg0, Throwable arg1) {
    super(arg0, arg1);
  }

}


text:
import React from 'react';
import { connect } from 'react-redux';
import Comment from './Comment';
import {updateCommentText} from '../CommentBox/Actions';

const mapStateToProps = (state) => {
  return {
    commentText: state.comments.text,
    insertQuoteFn: state.comments.insertQuoteFn
  }
}

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
      updateCommentText: (text) => {
	    dispatch(updateCommentText(text));
	  }
  }
}

const ConnectedComment = connect(
  mapStateToProps,
  mapDispatchToProps
)(Comment)

export default ConnectedComment;


text:
Datagrid for Symfony2 inspired by Zfdatagrid and Magento Grid.
This bundle was initiated by Stanislav Turza (Sorien).

**Version**: 2.1-dev
**Compatibility**: Symfony >= 2.0.0, Twig >= 1.5.0

[![Build Status](https://secure.travis-ci.org/Abhoryo/APYDataGridBundle.png?branch=master)](http://travis-ci.org/Abhoryo/APYDataGridBundle)

See [CHANGELOG](https://github.com/Abhoryo/APYDataGridBundle/blob/master/CHANGELOG.md) and [UPGRADE 2.0](https://github.com/Abhoryo/APYDataGridBundle/blob/master/UPGRADE-2.0.md)

## Features

- Supports Entity (ORM), Document (ODM) and Vector (Array) sources
- Sortable and Filterable with operators (Comparison operators, range, starts/ends with, (not) contains, is (not) defined, regex)
- Auto-typing columns (Text, Number, Boolean, Array, DateTime, Date, ...)
- Locale support for DateTime, Date and Number columns (Decimal, Currency, Percent, Duration, Scientific, Spell out)
- Input, Select, checkbox and radio button filters filled with the data of the grid or an array of values
- Export (CSV, Excel, _PDF_, XML, JSON, HTML, ...)
- Mass actions
- Row actions
- Supports mapped fields with Entity source
- Securing the columns, actions and export with security roles
- Annotations and PHP configuration
- External filters box
- Ajax loading
- Pagination (You can also use Pagerfanta)
- Column width and column align
- Prefix tranlated titles
- Grid manager for multi-grid on the same page
- Groups configuration for ORM and ODM sources
- Easy templates overriding (twig)
- Custom columns and filters creation
- ...

## Documentation

See the [summary](https://github.com/Abhoryo/APYDataGridBundle/blob/master/Resources/doc/summary.md).

## Screenshot

Full example with this [CSS style file](https://github.com/Abhoryo/APYDataGridBundle/blob/master/Resources/doc/grid_configuration/working_example.css):

![test](https://github.com/Abhoryo/APYDataGridBundle/blob/master/Resources/doc/images/screenshot_full.png?raw=true)

Simple example with the external filter box in english:

![test](https://github.com/Abhoryo/APYDataGridBundle/blob/master/Resources/doc/images/screenshot_en.png?raw=true)

Same example in french:

![test](https://github.com/Abhoryo/APYDataGridBundle/blob/master/Resources/doc/images/screenshot_fr.png?raw=true)

Data used in these screenshots (this is a phpMyAdmin screenshot):

![test](https://github.com/Abhoryo/APYDataGridBundle/blob/master/Resources/doc/images/screenshot_database.png?raw=true)

## Simple grid with an ORM source

```php
<?php
namespace MyProject\MyBundle\Controller;

use APY\DataGridBundle\Grid\Source\Entity;

class DefaultController extends Controller
{
	public function myGridAction()
	{
		// Creates a simple grid based on your entity (ORM)
		$source = new Entity('MyProjectMyBundle:MyEntity');

		// Get a Grid instance
		$grid = $this->get('grid');

		// Attach the source to the grid
		$grid->setSource($source);

		// Return the response of the grid to the template
		return $grid->getGridResponse('MyProjectMyBundle::myGrid.html.twig');
	}
}
```

#### Simple configuration of the grid in the entity

```php
<?php
namespace MyProject\MyBundle\Entity

use Doctrine\ORM\Mapping as ORM;
use APY\DataGridBundle\Grid\Mapping as GRID;

/**
 * @GRID\Source(columns="id, my_datetime")
 */
class MyEntity
{
	/*
	 * @ORM\Column(type="integer")
	 */
	protected $id;

	/*
	 * @ORM\Column(type="datetime")
	 */
	protected $my_datetime;
}
```

#### Display the grid in a twig template

```php
<?php
<!-- MyProject\MyBundle\Resources\views\myGrid.html.twig -->

{{ grid(grid) }}
```

And clear your cache.

## Special thanks to all contributors

Abhoryo, golovanov, touchdesign, Spea, nurikabe, print, Gregory McLean, centove, lstrojny, Benedikt Wolters, Martin Parsiegla, evan and all bug reporters

## Todo list

See this [Pull Request](https://github.com/Abhoryo/APYDataGridBundle/issues/121)


text:
class PlanDecorator < Draper::Decorator
  decorates :plan
  include Draper::LazyHelpers
  include AutoHtml

  def short_description
    truncate source.description, length: 35
  end

  def medium_description
    truncate source.description, length: 65
  end

  def display_description
    auto_html(source.description){ html_escape; simple_format }
  end
end


text:
namespace Envoy {
namespace Extensions {
namespace HttpFilters {
namespace KillRequest {
namespace {

using ::testing::AnyNumber;
using ::testing::Return;

class KillRequestFilterTest : public testing::Test {
protected:
  void
  setUpTest(const envoy::extensions::filters::http::kill_request::v3::KillRequest& kill_request) {
    filter_ = std::make_unique<KillRequestFilter>(kill_request, random_generator_);

    filter_->setDecoderFilterCallbacks(decoder_filter_callbacks_);
    EXPECT_CALL(decoder_filter_callbacks_.dispatcher_, pushTrackedObject(_)).Times(AnyNumber());
    EXPECT_CALL(decoder_filter_callbacks_.dispatcher_, popTrackedObject(_)).Times(AnyNumber());
  }

  std::unique_ptr<KillRequestFilter> filter_;
  testing::NiceMock<Random::MockRandomGenerator> random_generator_;
  testing::NiceMock<Http::MockStreamDecoderFilterCallbacks> decoder_filter_callbacks_;
  Http::TestRequestHeaderMapImpl request_headers_;
  Http::TestResponseHeaderMapImpl response_headers_;
};

TEST_F(KillRequestFilterTest, KillRequestCrashEnvoy) {
  envoy::extensions::filters::http::kill_request::v3::KillRequest kill_request;
  kill_request.mutable_probability()->set_numerator(1);
  setUpTest(kill_request);
  request_headers_.addCopy("x-envoy-kill-request", "true");

  ON_CALL(random_generator_, random()).WillByDefault(Return(0));
  EXPECT_DEATH(filter_->decodeHeaders(request_headers_, false),
               "KillRequestFilter is crashing Envoy!!!");
}

TEST_F(KillRequestFilterTest, KillRequestCrashEnvoyWithCustomKillHeader) {
  envoy::extensions::filters::http::kill_request::v3::KillRequest kill_request;
  kill_request.mutable_probability()->set_numerator(1);
  kill_request.set_kill_request_header("x-custom-kill-request");
  setUpTest(kill_request);
  request_headers_.addCopy("x-custom-kill-request", "true");

  ON_CALL(random_generator_, random()).WillByDefault(Return(0));
  EXPECT_DEATH(filter_->decodeHeaders(request_headers_, false),
               "KillRequestFilter is crashing Envoy!!!");
}

TEST_F(KillRequestFilterTest, KillRequestWithMillionDenominatorCrashEnvoy) {
  envoy::extensions::filters::http::kill_request::v3::KillRequest kill_request;
  kill_request.mutable_probability()->set_numerator(1);
  kill_request.mutable_probability()->set_denominator(envoy::type::v3::FractionalPercent::MILLION);
  setUpTest(kill_request);
  request_headers_.addCopy("x-envoy-kill-request", "yes");

  ON_CALL(random_generator_, random()).WillByDefault(Return(0));
  EXPECT_DEATH(filter_->decodeHeaders(request_headers_, false),
               "KillRequestFilter is crashing Envoy!!!");
}

TEST_F(KillRequestFilterTest, KillRequestDisabledWhenIsKillRequestEnabledReturnsFalse) {
  envoy::extensions::filters::http::kill_request::v3::KillRequest kill_request;
  kill_request.mutable_probability()->set_numerator(0);
  setUpTest(kill_request);
  request_headers_.addCopy("x-envoy-kill-request", "true");

  ON_CALL(random_generator_, random()).WillByDefault(Return(1));
  EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->decodeHeaders(request_headers_, false));
}

// Kill request should be enabled when isKillRequestEnabled returns true
// from the route level configuration.
TEST_F(KillRequestFilterTest, KillRequestEnabledFromRouteLevelConfiguration) {
  envoy::extensions::filters::http::kill_request::v3::KillRequest kill_request;
  kill_request.mutable_probability()->set_numerator(0);
  setUpTest(kill_request);
  request_headers_.addCopy("x-envoy-kill-request", "true");

  envoy::extensions::filters::http::kill_request::v3::KillRequest route_level_kill_request;
  route_level_kill_request.mutable_probability()->set_numerator(1);
  route_level_kill_request.set_kill_request_header("x-custom-kill-request");

  KillSettings kill_settings = KillSettings(route_level_kill_request);

  ON_CALL(random_generator_, random()).WillByDefault(Return(0));
  ON_CALL(*decoder_filter_callbacks_.route_, mostSpecificPerFilterConfig(_))
      .WillByDefault(Return(&kill_settings));
  EXPECT_DEATH(filter_->decodeHeaders(request_headers_, false), "");
}

// Kill request should be disabled when isKillRequestEnabled returns false
// from the route level configuration.
TEST_F(KillRequestFilterTest, KillRequestDisabledRouteLevelConfiguration) {
  envoy::extensions::filters::http::kill_request::v3::KillRequest kill_request;
  kill_request.mutable_probability()->set_numerator(0);
  setUpTest(kill_request);
  request_headers_.addCopy("x-envoy-kill-request", "true");

  ON_CALL(random_generator_, random()).WillByDefault(Return(0));
  ON_CALL(*decoder_filter_callbacks_.route_, mostSpecificPerFilterConfig(_))
      .WillByDefault(Return(nullptr));
  EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->decodeHeaders(request_headers_, false));
}

TEST_F(KillRequestFilterTest, KillRequestDisabledWhenHeaderIsMissing) {
  envoy::extensions::filters::http::kill_request::v3::KillRequest kill_request;
  kill_request.mutable_probability()->set_numerator(100);
  setUpTest(kill_request);

  ON_CALL(random_generator_, random()).WillByDefault(Return(0));
  EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->decodeHeaders(request_headers_, false));
}

TEST_F(KillRequestFilterTest, KillRequestDisabledWhenHeaderValueIsInvalid) {
  envoy::extensions::filters::http::kill_request::v3::KillRequest kill_request;
  kill_request.mutable_probability()->set_numerator(100);
  setUpTest(kill_request);
  request_headers_.addCopy("x-envoy-kill-request", "invalid");

  ON_CALL(random_generator_, random()).WillByDefault(Return(0));
  EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->decodeHeaders(request_headers_, false));
}

TEST_F(KillRequestFilterTest, DecodeDataReturnsContinue) {
  envoy::extensions::filters::http::kill_request::v3::KillRequest kill_request;
  setUpTest(kill_request);
  Buffer::OwnedImpl data;
  EXPECT_EQ(Http::FilterDataStatus::Continue, filter_->decodeData(data, false));
}

TEST_F(KillRequestFilterTest, DecodeTrailersReturnsContinue) {
  envoy::extensions::filters::http::kill_request::v3::KillRequest kill_request;
  setUpTest(kill_request);
  Http::TestRequestTrailerMapImpl request_trailers;
  EXPECT_EQ(Http::FilterTrailersStatus::Continue, filter_->decodeTrailers(request_trailers));
}

TEST_F(KillRequestFilterTest, Encode1xxHeadersReturnsContinue) {
  envoy::extensions::filters::http::kill_request::v3::KillRequest kill_request;
  setUpTest(kill_request);
  Http::TestResponseHeaderMapImpl response_headers;
  EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->encode1xxHeaders(response_headers));
}

TEST_F(KillRequestFilterTest, EncodeTrailersReturnsContinue) {
  envoy::extensions::filters::http::kill_request::v3::KillRequest kill_request;
  setUpTest(kill_request);
  Http::TestResponseTrailerMapImpl response_trailers;
  EXPECT_EQ(Http::FilterTrailersStatus::Continue, filter_->encodeTrailers(response_trailers));
}

TEST_F(KillRequestFilterTest, EncodeMetadataReturnsContinue) {
  envoy::extensions::filters::http::kill_request::v3::KillRequest kill_request;
  setUpTest(kill_request);
  Http::MetadataMap metadata_map;
  EXPECT_EQ(Http::FilterMetadataStatus::Continue, filter_->encodeMetadata(metadata_map));
}

TEST_F(KillRequestFilterTest, CanKillOnResponse) {
  envoy::extensions::filters::http::kill_request::v3::KillRequest kill_request;
  kill_request.mutable_probability()->set_numerator(1);
  kill_request.set_direction(
      envoy::extensions::filters::http::kill_request::v3::KillRequest::RESPONSE);
  setUpTest(kill_request);

  // We should crash on the OUTBOUND request
  ON_CALL(random_generator_, random()).WillByDefault(Return(0));
  response_headers_.addCopy("x-envoy-kill-request", "true");
  EXPECT_DEATH(filter_->encodeHeaders(response_headers_, false),
               "KillRequestFilter is crashing Envoy!!!");
}

TEST_F(KillRequestFilterTest, KillsBasedOnDirection) {
  envoy::extensions::filters::http::kill_request::v3::KillRequest kill_request;
  kill_request.mutable_probability()->set_numerator(1);
  kill_request.set_direction(
      envoy::extensions::filters::http::kill_request::v3::KillRequest::RESPONSE);
  setUpTest(kill_request);

  // We shouldn't crash on the REQUEST direction kill request
  request_headers_.addCopy("x-envoy-kill-request", "true");
  ASSERT_EQ(filter_->decodeHeaders(request_headers_, false), Http::FilterHeadersStatus::Continue);

  // We should crash on the RESPONSE kill request
  ON_CALL(random_generator_, random()).WillByDefault(Return(0));
  response_headers_.addCopy("x-envoy-kill-request", "true");
  EXPECT_DEATH(filter_->encodeHeaders(response_headers_, false),
               "KillRequestFilter is crashing Envoy!!!");
}

TEST_F(KillRequestFilterTest, PerRouteKillSettingFound) {
  envoy::extensions::filters::http::kill_request::v3::KillRequest kill_request;
  setUpTest(kill_request);
  request_headers_.addCopy("x-envoy-kill-request", "true");

  envoy::extensions::filters::http::kill_request::v3::KillRequest route_level_kill_request;
  // Set probability to zero to make isKillRequestEnabled return false
  route_level_kill_request.mutable_probability()->set_numerator(0);
  route_level_kill_request.set_kill_request_header("x-custom-kill-request");

  // Return valid kill setting on the REQUEST direction
  const KillSettings kill_settings(route_level_kill_request);
  ON_CALL(*decoder_filter_callbacks_.route_, mostSpecificPerFilterConfig(_))
      .WillByDefault(Return(&kill_settings));
  ASSERT_EQ(filter_->decodeHeaders(request_headers_, false), Http::FilterHeadersStatus::Continue);
}

} // namespace
} // namespace KillRequest
} // namespace HttpFilters
} // namespace Extensions
} // namespace Envoy


text:
package de.kaiserpfalzEdv.vaadin.i18n;

import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Locale;

/**
 * @author klenkes
 * @version 2015Q1
 * @since 28.08.15 10:38
 */
public interface I18NHandler extends Serializable {
    /**
     * Retrieves the filename for this localization resource bundle file.
     *
     * @return The name set for this resource bundle file.
     */
    String getI18NFileName();

    /**
     * Sets the name of the localization resource bundle file.
     *
     * @param i18nFileName The filename of the resource bundle.
     *
     * @throws IllegalArgumentException if the file name given is NULl or empty.
     */
    void setI18NFileName(@NotNull String i18nFileName);

    Locale getLocale();

    void setLocale(@NotNull Locale locale);

    String get(String key);

    String get(String key, Object[] parameters);
}


text:
@implementation CASStyleSelector

- (id)init {
    self = [super init];
    if (!self) return nil;

    self.shouldSelectSubclasses = NO;
    self.shouldSelectIndirectSuperview = YES;

    return self;
}

- (id)copyWithZone:(NSZone *)zone {
    CASStyleSelector *newSelector = [[self.class allocWithZone:zone] init];
    if (!newSelector) return nil;

    newSelector.objectClass = self.objectClass;
    newSelector.styleClass = self.styleClass;
    newSelector.shouldSelectSubclasses = self.shouldSelectSubclasses;
    newSelector.shouldSelectIndirectSuperview = self.shouldSelectIndirectSuperview;
    newSelector.shouldConcatToParent = self.shouldConcatToParent;
    newSelector.arguments = [self.arguments copy];
    newSelector.parentSelector = [self.parentSelector copy];

    return newSelector;
}

#pragma mark - properties

- (CASStyleSelector *)lastSelector {
    return self.parentSelector.lastSelector ?: self;
}

#pragma mark - public

- (NSInteger)precedence {
    NSInteger precedence = 0;
    if (self.objectClass) {
        if (self.isParent) {
            precedence += self.shouldSelectIndirectSuperview ? 2 : 3;
        } else {
            precedence += 4;
        }
        if (self.shouldSelectSubclasses) {
            precedence -= 1;
        }
    }

    if (self.styleClass) {
        if (self.isParent) {
            precedence += self.shouldSelectIndirectSuperview ? 1000 : 2000;
        } else {
            precedence += 3000;
        }
    }

    precedence += self.parentSelector.precedence;
    return precedence;
}

- (BOOL)shouldSelectItem:(id<CASStyleableItem>)item {
    if (![self matchesItem:item]) {
        return NO;
    }

    if (self.parentSelector) {
        return [self.parentSelector matchesAncestorsOfItem:item traverse:self.shouldSelectIndirectSuperview];
    }

    return YES;
}

- (NSString *)stringValue {
    NSMutableString *stringValue = NSMutableString.new;
    if (self.parentSelector) {
        [stringValue appendFormat:self.shouldSelectIndirectSuperview ? @"%@ " : @"%@ > ", [self.parentSelector stringValue]];
    }
    if (self.shouldSelectSubclasses) {
        [stringValue appendString:@"^"];
    }
    if (self.objectClass) {
        [stringValue appendString:NSStringFromClass(self.objectClass)];
    }
    if (self.arguments) {
        [stringValue appendString:@"["];
        NSArray *keys = [self.arguments.allKeys sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
        [keys enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop) {
            [stringValue appendFormat:@"%@:%@", key, self.arguments[key]];
            if (idx != keys.count - 1) {
                [stringValue appendString:@", "];
            }
        }];
        [stringValue appendString:@"]"];
    }
    if (self.styleClass) {
        [stringValue appendFormat:@".%@", self.styleClass];
    }
    return stringValue;
}

#pragma mark - private

- (BOOL)matchesAncestorsOfItem:(id<CASStyleableItem>)item traverse:(BOOL)traverse {
    id<CASStyleableItem> currentItem = item;

    while (currentItem.cas_parent != nil || currentItem.cas_alternativeParent != nil) {
        id<CASStyleableItem> ancestor;
        if ([self matchesItem:currentItem.cas_parent]) {
            ancestor = currentItem.cas_parent;
        } else if ([self matchesItem:currentItem.cas_alternativeParent]) {
            ancestor = currentItem.cas_alternativeParent;
        }

        if (ancestor) {
            if (!self.parentSelector) return YES;
            BOOL traverse = self.shouldSelectIndirectSuperview;
            if ([self.parentSelector matchesAncestorsOfItem:ancestor traverse:traverse]) return YES;
        }
        if (!traverse) return NO;
        currentItem = currentItem.cas_parent;
    }

    return NO;
}

- (BOOL)matchesItem:(id<CASStyleableItem>)item {
    if (self.objectClass) {
        if (self.shouldSelectSubclasses) {
            if (![item isKindOfClass:self.objectClass]) return NO;
        } else {
            if (![item isMemberOfClass:self.objectClass]) return NO;
        }
    }

    if (self.styleClass.length && ![item cas_hasStyleClass:self.styleClass]) {
        return NO;
    }
    return YES;
}

@end


text:
/**
 * Created by pingfengafei on 16/11/29.
 */
import React from 'react';
import './Pagination.less';

class Pagination extends React.Component {
  constructor(props) {
    super(props);
    //学到了个碉堡的bind方法
    ['_prev', '_next', '_handleClick', '_hasPrev', '_hasNext'].forEach((val) => {
      this[val] = this[val].bind(this);
    });
  }

  static defaultProps = {
    total: 1,
    selectedPage: 1,
    onChange: () => null
  };

  static propTypes = {
    total: React.PropTypes.number,
    selectedPage: React.PropTypes.number,
    onChange: React.PropTypes.func
  };

  _handleClick(pageNumber) {
    this.props.onChange(pageNumber);
  }

  _hasPrev() {
    return this.props.selectedPage > 1;
  }

  _hasNext() {
    return this.props.selectedPage < this.props.total;
  }

  _prev() {

    console.log('_prev');

    if (this._hasPrev()) {
      this._handleClick(this.props.selectedPage - 1);
    }
  }

  _next() {

    console.log('_next');

    if (this._hasNext()) {
      this._handleClick(this.props.selectedPage + 1);
    }
  }

  render() {
    let {total, selectedPage} = this.props;

    let pre = null, next = null;
    this._hasPrev() ?
      pre =

 :
      pre =

;
    this._hasNext() ?
      next =

 :
      next =

;

    let liList = [];

    if (total <= 6) {
      for (let i = 1; i <= total; i++) {
        let className = (i === selectedPage ? 'pagination-li selected' : 'pagination-li');
        liList.push(
          <li
            key={`${i}`}
            className={className}
            onClick={this._handleClick.bind(null, i)}
          >{i}

        );
      }
    } else {
      let firstPage = (

1

      );
      let lastPage = (
        <li
          key={`${total}`}
          className={total === selectedPage ? 'pagination-li selected' : 'pagination-li'}
          onClick={this._handleClick.bind(null, total)}
        >{total}

      );

      let leftPoint = Math.max(1, selectedPage - 2);
      let rightPoint = Math.min(selectedPage + 2, total);

      //显示中间5个数据
      for (let i = leftPoint; i <= rightPoint; i++) {
        let className = (i === selectedPage ? 'pagination-li selected' : 'pagination-li');
        liList.push(
          <li
            key={`${i}`}
            className={className}
            onClick={this._handleClick.bind(null, i)}
          >{i}

        );
      }
      //判断是否向左添加。。。
      if (selectedPage - 2 > 2) {
        liList.unshift(

);
      }
      //判断是否向右添加。。。
      if (selectedPage + 2 < total - 1) {
        liList.push(

);
      }

      //判断是到达最左边情况
      if (selectedPage - 2 >= 2) {
        liList.unshift(firstPage);
      }
      //判断到达最右边情况
      if (selectedPage + 2 <= total - 1) {
        liList.push(lastPage);
      }
    }

    let content = (

        {pre}
        {liList}
        {next}

    );
    return (

        {content}

    );
  }
}

export default Pagination;


text:
export default function clearUnused (cache) {
  for (var key in cache) {
    if (cache[key].meshes.length === 0) {
      delete cache[key]
    }
  }
}


text:
<?php namespace Fungku\NetSuite\Classes;

class ResourceAllocationSearch extends SearchRecord {
	public $basic;
	public $customerJoin;
	public $employeeJoin;
	public $jobJoin;
	public $requestedByJoin;
	public $resourceJoin;
	public $userJoin;
	public $vendorJoin;
	public $customSearchJoin;
	static $paramtypesmap = array(
		"basic" => "ResourceAllocationSearchBasic",
		"customerJoin" => "CustomerSearchBasic",
		"employeeJoin" => "EmployeeSearchBasic",
		"jobJoin" => "JobSearchBasic",
		"requestedByJoin" => "EntitySearchBasic",
		"resourceJoin" => "EntitySearchBasic",
		"userJoin" => "EmployeeSearchBasic",
		"vendorJoin" => "VendorSearchBasic",
		"customSearchJoin" => "CustomSearchJoin[]",
	);
}


text:
<?php

declare(strict_types=1);

namespace WyriHaximus\CpuCoreDetector\Tests\Core\Affinity;

use WyriHaximus\CpuCoreDetector\Core\Affinity\CmdExe;
use WyriHaximus\CpuCoreDetector\Core\AffinityInterface;

final class CmdExeTest extends AbstractAffinityTest
{
    protected function getStrategy(): AffinityInterface
    {
        return new CmdExe();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="包含RecyclerView" />

            <com.fangxu.library.DragContainer
                android:id="@+id/drag_recycler_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                app:dc_reset_animator_duration="500">

                <android.support.v7.widget.RecyclerView
                    android:id="@+id/recycler_view"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="@android:color/white" />

            </com.fangxu.library.DragContainer>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="包含HorizontalScrollView" />

            <com.fangxu.library.DragContainer
                android:id="@+id/drag_scroll_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                app:dc_reset_animator_duration="500">

                <HorizontalScrollView
                    android:id="@+id/scroll_view"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="@android:color/white"
                    android:scrollbars="none">

                    <LinearLayout
                        android:id="@+id/linear_layout"
                        android:layout_width="match_parent"
                        android:layout_height="170dp"
                        android:orientation="horizontal" />

                </HorizontalScrollView>

            </com.fangxu.library.DragContainer>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="包含ImageView" />

            <com.fangxu.library.DragContainer
                android:id="@+id/drag_image_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                app:dc_drag_damp="0.66"
                app:dc_reset_animator_duration="500">

                <ImageView
                    android:id="@+id/image_view"
                    android:layout_width="150dp"
                    android:layout_height="200dp"
                    android:scaleType="centerCrop" />

            </com.fangxu.library.DragContainer>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="包含TextView, Button" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="20dp"
                android:orientation="horizontal">

                <com.fangxu.library.DragContainer
                    android:id="@+id/drag_text_view"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    android:layout_weight="1"
                    app:dc_reset_animator_duration="500">

                    <TextView
                        android:id="@+id/text_view"
                        android:layout_width="match_parent"
                        android:layout_height="80dp"
                        android:background="#66ee66"
                        android:gravity="center"
                        android:scaleType="centerCrop"
                        android:text="TextView" />

                </com.fangxu.library.DragContainer>

                <com.fangxu.library.DragContainer
                    android:id="@+id/drag_button"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="10dp"
                    android:layout_weight="1"
                    app:dc_reset_animator_duration="500">

                    <Button
                        android:id="@+id/button"
                        android:layout_width="match_parent"
                        android:layout_height="80dp"
                        android:background="#ff6600"
                        android:scaleType="centerCrop"
                        android:text="Button" />

                </com.fangxu.library.DragContainer>

            </LinearLayout>
        </LinearLayout>

    </ScrollView>
</FrameLayout>


text:
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/image_fetcher/core/cached_image_fetcher.h"

#include <utility>

#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/metrics/histogram_macros.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/thread_pool.h"
#include "base/time/time.h"
#include "base/timer/elapsed_timer.h"
#include "components/image_fetcher/core/cache/image_cache.h"
#include "components/image_fetcher/core/image_decoder.h"
#include "components/image_fetcher/core/image_fetcher_metrics_reporter.h"
#include "components/image_fetcher/core/request_metadata.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia.h"

namespace image_fetcher {

struct CachedImageFetcherRequest {
  // The url to be fetched.
  const GURL url;

  ImageFetcherParams params;

  // Analytic events below.

  // True if there was a cache hit during the fetch sequence.
  bool cache_hit_before_network_request;

  // The start time of the fetch sequence.
  base::Time start_time;
};

namespace {

void DataCallbackIfPresent(ImageDataFetcherCallback data_callback,
                           const std::string& image_data,
                           const image_fetcher::RequestMetadata& metadata) {
  if (data_callback.is_null()) {
    return;
  }
  std::move(data_callback).Run(image_data, metadata);
}

void ImageCallbackIfPresent(ImageFetcherCallback image_callback,
                            const gfx::Image& image,
                            const image_fetcher::RequestMetadata& metadata) {
  if (image_callback.is_null()) {
    return;
  }
  std::move(image_callback).Run(image, metadata);
}

std::string EncodeSkBitmapToPNG(const std::string& uma_client_name,
                                const SkBitmap& bitmap) {
  std::vector<unsigned char> encoded_data;
  bool result = gfx::PNGCodec::Encode(
      static_cast<const unsigned char*>(bitmap.getPixels()),
      gfx::PNGCodec::FORMAT_RGBA, gfx::Size(bitmap.width(), bitmap.height()),
      static_cast<int>(bitmap.rowBytes()), /* discard_transparency */ false,
      std::vector<gfx::PNGCodec::Comment>(), &encoded_data);
  if (!result) {
    ImageFetcherMetricsReporter::ReportEvent(
        uma_client_name, ImageFetcherEvent::kTranscodingError);
    return "";
  } else {
    return std::string(encoded_data.begin(), encoded_data.end());
  }
}

}  // namespace

CachedImageFetcher::CachedImageFetcher(ImageFetcher* image_fetcher,
                                       scoped_refptr<ImageCache> image_cache,
                                       bool read_only)
    : image_fetcher_(image_fetcher),
      image_cache_(image_cache),
      read_only_(read_only) {
  DCHECK(image_fetcher_);
  DCHECK(image_cache_);
}

CachedImageFetcher::~CachedImageFetcher() = default;

ImageDecoder* CachedImageFetcher::GetImageDecoder() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return image_fetcher_->GetImageDecoder();
}

void CachedImageFetcher::FetchImageAndData(
    const GURL& image_url,
    ImageDataFetcherCallback image_data_callback,
    ImageFetcherCallback image_callback,
    ImageFetcherParams params) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  // TODO(wylieb): Inject a clock for better testability.
  CachedImageFetcherRequest request = {
      image_url, std::move(params),
      /* cache_hit_before_network_request */ false,
      /* start_time */ base::Time::Now()};

  ImageFetcherMetricsReporter::ReportEvent(request.params.uma_client_name(),
                                           ImageFetcherEvent::kImageRequest);

  if (request.params.skip_disk_cache_read()) {
    EnqueueFetchImageFromNetwork(std::move(request),
                                 std::move(image_data_callback),
                                 std::move(image_callback));
  } else {
    // First, try to load the image from the cache, then try the network.
    image_cache_->LoadImage(
        read_only_, image_url.spec(),
        base::BindOnce(&CachedImageFetcher::OnImageFetchedFromCache,
                       weak_ptr_factory_.GetWeakPtr(), std::move(request),
                       std::move(image_data_callback),
                       std::move(image_callback)));
  }
}

void CachedImageFetcher::OnImageFetchedFromCache(
    CachedImageFetcherRequest request,
    ImageDataFetcherCallback image_data_callback,
    ImageFetcherCallback image_callback,
    bool cache_result_needs_transcoding,
    std::string image_data) {
  if (image_data.empty()) {
    ImageFetcherMetricsReporter::ReportEvent(request.params.uma_client_name(),
                                             ImageFetcherEvent::kCacheMiss);

    // Fetching from the DB failed, start a network fetch.
    EnqueueFetchImageFromNetwork(std::move(request),
                                 std::move(image_data_callback),
                                 std::move(image_callback));
  } else {
    DataCallbackIfPresent(std::move(image_data_callback), image_data,
                          RequestMetadata());
    ImageFetcherMetricsReporter::ReportEvent(request.params.uma_client_name(),
                                             ImageFetcherEvent::kCacheHit);

    // Only continue with decoding if the user actually asked for an image, or
    // the image hadn't been transcoded yet and NOT loaded in the reduced mode.
    if (!image_callback.is_null() ||
        (cache_result_needs_transcoding &&
         !request.params.allow_needs_transcoding_file())) {
      auto* data_decoder = request.params.data_decoder();
      GetImageDecoder()->DecodeImage(
          image_data, gfx::Size(), data_decoder,
          base::BindOnce(&CachedImageFetcher::OnImageDecodedFromCache,
                         weak_ptr_factory_.GetWeakPtr(), std::move(request),
                         ImageDataFetcherCallback(), std::move(image_callback),
                         cache_result_needs_transcoding));
    }
  }
}

void CachedImageFetcher::OnImageDecodedFromCache(
    CachedImageFetcherRequest request,
    ImageDataFetcherCallback image_data_callback,
    ImageFetcherCallback image_callback,
    bool cache_result_needs_transcoding,
    const gfx::Image& image) {
  if (image.IsEmpty()) {
    ImageFetcherMetricsReporter::ReportEvent(
        request.params.uma_client_name(),
        ImageFetcherEvent::kCacheDecodingError);

    // Upon failure, fetch from the network.
    request.cache_hit_before_network_request = true;
    EnqueueFetchImageFromNetwork(std::move(request),
                                 std::move(image_data_callback),
                                 std::move(image_callback));
  } else {
    ImageCallbackIfPresent(std::move(image_callback), image, RequestMetadata());
    ImageFetcherMetricsReporter::ReportImageLoadFromCacheTime(
        request.params.uma_client_name(), request.start_time);

    // If cache_result_needs_transcoding is true, then this should be stored
    // again to replace the image data already on disk with the transcoded data.
    if (cache_result_needs_transcoding) {
      ImageFetcherMetricsReporter::ReportEvent(
          request.params.uma_client_name(),
          ImageFetcherEvent::kImageQueuedForTranscodingDecoded);
      EncodeAndStoreData(/* cache_result_needs_transcoding */ true,
                         /* is_image_data_transcoded */ true,
                         std::move(request), image);
    }
  }
}

void CachedImageFetcher::EnqueueFetchImageFromNetwork(
    CachedImageFetcherRequest request,
    ImageDataFetcherCallback image_data_callback,
    ImageFetcherCallback image_callback) {
  base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
      FROM_HERE,
      base::BindOnce(&CachedImageFetcher::FetchImageFromNetwork,
                     weak_ptr_factory_.GetWeakPtr(), std::move(request),
                     std::move(image_data_callback),
                     std::move(image_callback)));
}

void CachedImageFetcher::FetchImageFromNetwork(
    CachedImageFetcherRequest request,
    ImageDataFetcherCallback image_data_callback,
    ImageFetcherCallback image_callback) {
  const GURL& url = request.url;

  ImageDataFetcherCallback wrapper_data_callback;
  ImageFetcherCallback wrapper_image_callback;

  bool skip_transcoding = request.params.skip_transcoding();
  ImageFetcherParams params_copy(request.params);
  if (skip_transcoding) {
    wrapper_data_callback =
        base::BindOnce(&CachedImageFetcher::OnImageFetchedWithoutTranscoding,
                       weak_ptr_factory_.GetWeakPtr(), std::move(request),
                       std::move(image_data_callback));
  } else {
    // Transcode the image when its downloaded from the network.
    // 1. Download the data.
    // 2. Decode the data to a gfx::Image in a utility process.
    // 3. Encode the data as a PNG in the browser process using
    //    base::ThreadPool.
    // 4. Cache the result.
    wrapper_data_callback = std::move(image_data_callback);
    wrapper_image_callback =
        base::BindOnce(&CachedImageFetcher::OnImageFetchedForTranscoding,
                       weak_ptr_factory_.GetWeakPtr(), std::move(request),
                       std::move(image_callback));
  }
  image_fetcher_->FetchImageAndData(url, std::move(wrapper_data_callback),
                                    std::move(wrapper_image_callback),
                                    std::move(params_copy));
}

void CachedImageFetcher::OnImageFetchedWithoutTranscoding(
    CachedImageFetcherRequest request,
    ImageDataFetcherCallback image_data_callback,
    const std::string& image_data,
    const RequestMetadata& request_metadata) {
  DataCallbackIfPresent(std::move(image_data_callback), image_data,
                        request_metadata);

  if (image_data.empty()) {
    ImageFetcherMetricsReporter::ReportEvent(request.params.uma_client_name(),
                                             ImageFetcherEvent::kTotalFailure);
  }

  StoreData(/* cache_result_needs_transcoding */ false,
            /* is_image_data_transcoded */ false, std::move(request),
            image_data);
}

void CachedImageFetcher::OnImageFetchedForTranscoding(
    CachedImageFetcherRequest request,
    ImageFetcherCallback image_callback,
    const gfx::Image& image,
    const RequestMetadata& request_metadata) {
  ImageCallbackIfPresent(std::move(image_callback), image, request_metadata);

  // Report to different histograms depending upon if there was a cache hit.
  if (request.cache_hit_before_network_request) {
    ImageFetcherMetricsReporter::ReportImageLoadFromNetworkAfterCacheHit(
        request.params.uma_client_name(), request.start_time);
  } else {
    ImageFetcherMetricsReporter::ReportImageLoadFromNetworkTime(
        request.params.uma_client_name(), request.start_time);
  }

  EncodeAndStoreData(/* cache_result_needs_transcoding */ false,
                     /* is_image_data_transcoded */ true, std::move(request),
                     image);
}

void CachedImageFetcher::EncodeAndStoreData(bool cache_result_needs_transcoding,
                                            bool is_image_data_transcoded,
                                            CachedImageFetcherRequest request,
                                            const gfx::Image& image) {
  // Copy the image data out and store it on disk.
  const SkBitmap* bitmap = image.IsEmpty() ? nullptr : image.ToSkBitmap();
  // If the bitmap is null or otherwise not ready, skip encoding.
  if (bitmap == nullptr || bitmap->isNull() || !bitmap->readyToDraw()) {
    ImageFetcherMetricsReporter::ReportEvent(request.params.uma_client_name(),
                                             ImageFetcherEvent::kTotalFailure);

    image_cache_->DeleteImage(request.url.spec());
  } else {
    std::string uma_client_name = request.params.uma_client_name();
    // Post a task to another thread to encode the image data downloaded.
    base::ThreadPool::PostTaskAndReplyWithResult(
        FROM_HERE,
        base::BindOnce(&EncodeSkBitmapToPNG, uma_client_name, *bitmap),
        base::BindOnce(&CachedImageFetcher::StoreData,
                       weak_ptr_factory_.GetWeakPtr(),
                       cache_result_needs_transcoding, is_image_data_transcoded,
                       std::move(request)));
  }
}

void CachedImageFetcher::StoreData(bool cache_result_needs_transcoding,
                                   bool is_image_data_transcoded,
                                   CachedImageFetcherRequest request,
                                   std::string image_data) {
  std::string url = request.url.spec();
  // If the image is empty, delete the image.
  if (image_data.empty()) {
    image_cache_->DeleteImage(std::move(url));
    return;
  }

  if (!read_only_) {
    if (cache_result_needs_transcoding) {
      ImageFetcherMetricsReporter::ReportEvent(
          request.params.uma_client_name(),
          ImageFetcherEvent::kImageQueuedForTranscodingStoredBack);
      if (!is_image_data_transcoded)
        return;
    }

    // |needs_transcoding| is only true when the image to save isn't transcoded
    // and |allow_needs_transcoding_file()| is true (set by
    // ReducedModeImageFetcher).
    bool needs_transcoding = !is_image_data_transcoded &&
                             request.params.allow_needs_transcoding_file();
    image_cache_->SaveImage(std::move(url), std::move(image_data),
                            /* needs_transcoding */ needs_transcoding,
                            request.params.expiration_interval());
  }
}

}  // namespace image_fetcher


text:
export const programaRules = {
  rules: [{ required: true, message: 'Campo obrigatório' }],
};

export const nomeRules = {
  rules: [
    { required: true, message: 'Campo obrigatório' },
    { min: 10, message: 'O nome deve ter, ao menos, 10 caracteres' },
    { max: 50, message: 'O nome deve ter, no máximo, 50 caracteres' },
  ],
};

export const descricaoRules = {
  rules: [
    { required: true, message: 'Campo obrigatório' },
    { min: 20, message: 'O nome deve ter, ao menos, 20 caracteres' },
    { max: 200, message: 'O nome deve ter, no máximo, 200 caracteres' },
  ],
};

export const dataRules = {
  rules: [{ type: 'object', required: true, message: 'Campo obrigatório' }],
};

export const vagasRules = {
  rules: [{ required: true, message: 'Campo obrigatório' }],
};


text:
<?php
Class Library_Form_FrmBook extends Zend_Dojo_Form {
	protected $tr;
	public function init()
	{
		$this->tr = Application_Form_FrmLanguages::getCurrentlanguage();
	}
	public function frmBook($data=null){
		$db = new Library_Model_DbTable_DbCategory();
		$request=Zend_Controller_Front::getInstance()->getRequest();

		$book_name = new Zend_Dojo_Form_Element_ValidationTextBox('book_name');
		$book_name->setAttribs(array(
				'dojoType'=>'dijit.form.ValidationTextBox',
				'class'=>'fullside',
				'required'=>'true',
				"autocomplete"=>'on',
				'placeholder'=>$this->tr->translate("BOOK_NAME")
		        ));

		$author_name = new Zend_Dojo_Form_Element_ValidationTextBox('author_name');
		$author_name->setAttribs(array(
				'dojoType'=>'dijit.form.ValidationTextBox',
				'class'=>'fullside',
				'placeholder'=>$this->tr->translate("AUTHOR_NAME")
		         ));

		$serial_no = new Zend_Dojo_Form_Element_ValidationTextBox('serial_no');
		$serial_no->setAttribs(array(
				'dojoType'=>'dijit.form.ValidationTextBox',
				'class'=>'fullside',
				'placeholder'=>$this->tr->translate("SERIAL_NO")
		));

		$barcode = new Zend_Dojo_Form_Element_ValidationTextBox('barcode');
		$barcode->setAttribs(array(
				'dojoType'=>'dijit.form.ValidationTextBox',
				'class'=>'fullside',
				'placeholder'=>$this->tr->translate("BARCODE"),
		));

		$publisher = new Zend_Dojo_Form_Element_ValidationTextBox('publisher');
		$publisher->setAttribs(array(
				'dojoType'=>'dijit.form.ValidationTextBox',
				'class'=>'fullside',
				'placeholder'=>$this->tr->translate("PUBLISHER")
		        ));

		$remark = new Zend_Dojo_Form_Element_TextBox('remarks');
		$remark->setAttribs(array(
				'dojoType'=>'dijit.form.ValidationTextBox',
				'class'=>'fullside',
				'placeholder'=>$this->tr->translate("Remark")
		        ));

		$status = new Zend_Dojo_Form_Element_FilteringSelect("status");
		$opt=array(
				"1"=>$this->tr->translate("ACTIVE"),
				"0"=>$this->tr->translate("DEACTIVE"),
		         );
		$status->setMultiOptions($opt);
		$status->setAttribs(array(
				'dojoType'=>'dijit.form.FilteringSelect',
				'class'=>'fullside',
				));

		$note = new Zend_Dojo_Form_Element_TextBox('remark');
		$note->setAttribs(array('dojoType'=>'dijit.form.TextBox','class'=>'fullside',
				'style'=>'width:98%;min-height:60px;'
				));

		$_cateory_parent = new Zend_Dojo_Form_Element_FilteringSelect("cat_id");
		$_cateory_parent->setAttribs(array(
				'dojoType'=>'dijit.form.FilteringSelect',
				'required'=>'true',
				'autoComplete'=>"false",
				'queryExpr'=>'*${0}*',
				'class'=>'fullside',
				'onChange'=>'showAddCat()'
				));
		$option = array("0"=>$this->tr->translate("SELECT_CATEGORY"),"-1"=>$this->tr->translate("ADD_NEW"));
		$result = $db->getCategory();
		if(!empty($result))foreach($result AS $row){
			$option[$row['id']]=$row['name'];
		}
		$_cateory_parent->setMultiOptions($option);
		$_cateory_parent->setValue($request->getParam('cat_id'));

		$_block_id = new Zend_Dojo_Form_Element_FilteringSelect("block_id");
		$_block_id->setAttribs(array(
				'dojoType'=>'dijit.form.FilteringSelect',
				'required'=>'true',
				'class'=>'fullside',
				'onchange'=>'showAddBlock();'
		));
		$option = array("0"=>$this->tr->translate("SELECT_BLOCK"),"-1"=>$this->tr->translate("ADD_NEW"));
		$results = $db->getAllBlockName();
		if(!empty($results))foreach($results AS $row){
			$option[$row['id']]=$row['name'];
		}

		$_block_id->setMultiOptions($option);
		$_block_id->setValue($request->getParam('block_id'));

		$id = new Zend_Form_Element_Hidden("id");
		$_photo = new Zend_Form_Element_File('photo');
		$old_photo = new Zend_Form_Element_Hidden("old_photo");

		$note = new Zend_Dojo_Form_Element_ValidationTextBox('note');
		$note->setAttribs(array(
				'dojoType'=>'dijit.form.ValidationTextBox',
				'class'=>'fullside',
				'placeholder'=>$this->tr->translate("NOTE")
		));

		if($data!=null){
			//print_r($data);exit();
			$book_name	->setValue($data['title']);
			$author_name->setValue($data['author']);
			$_cateory_parent->setValue($data['cat_id']);
			$publisher	->setValue($data['publisher']);
			$remark		->setValue($data['note']);
			$status		->setValue($data['status']);
			$old_photo	->setValue($data['photo']);
			$_block_id	->setValue($data['block_id']);
		}
		$this->addElements(array($barcode,$note,$_block_id,$old_photo,$id,$book_name,$author_name,$serial_no,$publisher,$_photo,
				                 $remark,$status,$note,$_cateory_parent));
		return $this;
	}

}


text:
package org.gradle.initialization;

import org.gradle.api.internal.GradleInternal;
import org.gradle.configuration.InitScriptProcessor;
import org.gradle.groovy.scripts.UriScriptSource;

import java.io.File;

/**
 * Finds and executes all init scripts for a given build.
 */
public class InitScriptHandler {
    private final InitScriptProcessor processor;

    public InitScriptHandler(InitScriptProcessor processor) {
        this.processor = processor;
    }

    public void executeScripts(GradleInternal gradle) {
        for (File script : gradle.getStartParameter().getAllInitScripts()) {
            processor.process(new UriScriptSource("initialization script", script), gradle);
        }
    }
}


text:
package org.apache.james.mailbox;

import java.io.Serializable;
import java.util.Comparator;

import org.apache.james.mailbox.model.MailboxConstants;
import org.apache.james.mailbox.model.MailboxMetaData;

/**
 * Orders by name with INBOX first.
 */
public class StandardMailboxMetaDataComparator implements Comparator<MailboxMetaData>, Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * Static comparison.
     *
     * @param one
     *            possibly null
     * @param two
     *            possibly null
     * @return {@link Comparator#compare(Object, Object)}
     */
    public static int order(MailboxMetaData one, MailboxMetaData two) {
        final String nameTwo = two.getPath().getName();
        final int result;
        final String nameOne = one.getPath().getName();
        if (MailboxConstants.INBOX.equals(nameOne)) {
            result = MailboxConstants.INBOX.equals(nameTwo) ? 0 : -1;
        } else if (MailboxConstants.INBOX.equals(nameTwo)) {
            result = 1;
        } else if (nameOne == null) {
            result = nameTwo == null ? 0 : 1;
        } else if (nameTwo == null) {
            result = -1;
        } else {
            result = nameOne.compareTo(nameTwo);
        }
        return result;
    }

    /**
     * @see Comparator#compare(Object, Object)
     */
    public int compare(MailboxMetaData one, MailboxMetaData two) {
        return order(one, two);
    }

}


text:
if ! which pip > /dev/null; then
	echo "Installing PIP..."
	sudo apt-get -y install python-pip
fi

echo "Installing markdown2..."
sudo pip install markdown2

echo "Initializing submodules..."
git submodule init
git submodule update

echo "Done."


text:
package org.sana.api;

import java.util.Date;

/**
 * Declares creation and modification dates and a universally unique id.
 *
 * @author Sana Development
 *
 */
public interface IModel {

	/** The format which will be used for persisting Date objects */
	public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

	/** The regular expression for validating uuid Strings */
	public static final String UUID_REGEX =
		"[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}";

	/** Returns a universally unique identifier */
	String getUuid();

	/**
	 * Returns a {@link java.util.Date Date} when this object was created.
	 * @return a Date object.
	 */
	Date getCreated();

	/**
	 * Returns a {@link java.util.Date Date} when this object was last modified.
	 * @return a Date object.
	 */
	public Date getModified();

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.apache.accumulo</groupId>
    <artifactId>accumulo-project</artifactId>
    <version>1.7.0-SNAPSHOT</version>
  </parent>
  <artifactId>accumulo-trace</artifactId>
  <name>Trace</name>
  <description>A distributed tracing library for Apache Accumulo.</description>
  <dependencies>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.thrift</groupId>
      <artifactId>libthrift</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.zookeeper</groupId>
      <artifactId>zookeeper</artifactId>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>findbugs-maven-plugin</artifactId>
          <configuration>
            <excludeFilterFile>src/main/findbugs/exclude-filter.xml</excludeFilterFile>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
  <profiles>
    <profile>
      <id>thrift</id>
      <build>
        <plugins>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <executions>
              <execution>
                <id>generate-thrift</id>
                <goals>
                  <goal>exec</goal>
                </goals>
                <phase>generate-sources</phase>
                <configuration>
                  <executable>${basedir}/src/main/scripts/generate-thrift.sh</executable>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>
</project>


text:
package sanchez.sergio;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.config.server.EnableConfigServer;

@EnableConfigServer
@EnableDiscoveryClient
@SpringBootApplication
public class ConfigServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConfigServiceApplication.class, args);
    }
}


text:
/***********************************************************
* Developer: Minhas Kamal (minhaskamal024@gmail.com)       *
* Date: May-2015                                           *
* License: MIT License                                     *
***********************************************************/

package com.minhasKamal.skinDetector;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class SkinDetectorTester {
	public void recogniseImage(String testImagePath, String knowledgeFilePath) throws Exception{
		recogniseImage(testImagePath, knowledgeFilePath, 0.15);
	}

	public void recogniseImage(String testImagePath, String knowledgeFilePath, double threshHold) throws Exception{
		recogniseImage(testImagePath, knowledgeFilePath, testImagePath+"_mask.png", threshHold);
	}

	public void recogniseImage(String testImagePath, String knowledgeFilePath, String outputFilePath, double threshHold) throws Exception{

		double[][][] ratio = getData(knowledgeFilePath);

		Matrix matImage = new Matrix(testImagePath, Matrix.RED_GREEN_BLUE);
		Matrix matMask = new Matrix(matImage.getRows(), matImage.getCols(), Matrix.BLACK_WHITE);

		System.out.println("\n\n## \t\tProcessing Image...");	//notification
		int rows = matImage.getRows();
		int cols = matImage.getCols();
		for(int row=0, col; row<rows; row++){
			for(col=0; col<cols; col++){
				if(ratio[matImage.pixels[row][col][0]][matImage.pixels[row][col][1]]
						[matImage.pixels[row][col][2]] > threshHold){

					matMask.pixels[row][col][0] = 250;
				}else{
					matMask.pixels[row][col][0] = 0;
				}
			}
		}

		matMask.write(outputFilePath);
	}

	private double[][][] getData(String knowledgePath) throws IOException{
		String string = "";	//for temporary data store
		BufferedReader mainBR = new BufferedReader(new FileReader(knowledgePath));
		double[][][] ratio = new double[256][256][256];

		System.out.println("## \t\tReading Knowledge File...");
		for(int i=0; i<256; i++){
			for(int j=0; j<256; j++){
				for(int k=0; k<256; k++){
					string = mainBR.readLine();
					ratio[i][j][k] = Double.parseDouble(string);
				}
			}
			System.out.print(".");	//notification
		}

		mainBR.close();

		return ratio;
	}

	/** MAIN **/
	public static void main(String[] args) {

		String testImagePath = "data\\test.jpg";
		String knowledgePath = "data\\image_knowledge.dat";

		try {
			new SkinDetectorTester().recogniseImage(testImagePath, knowledgePath);
			System.out.println("\n\n## \t\tSuccessful!!");
		} catch (Exception e) {
			System.out.println("\n\n## \t\t File Path Error!!");
		}
	}
}


text:
IF(BULLET_FOUND)
    # Already in cache, be silent
    SET(BULLET_FIND_QUIETLY TRUE)
ENDIF()

IF(BUILD_BULLET OR ACGL_GLOBAL_EXTERN_DIR_FOUND_FIRST_TIME OR BUILD_TYPE_CHANGED)
    UNSET(BULLET_INCLUDE_DIR CACHE)
    UNSET(BULLET_LIBRARIES CACHE)
ENDIF()

IF(BUILD_BULLET)
    SET(BULLET_INCLUDE_DIR "${ACGL_LOCAL_EXTERN_DIR}/bullet/src")
    SET(BULLET_LIBRARIES BulletCollision${COMPILE_POSTFIX} BulletDynamics${COMPILE_POSTFIX} BulletMultiThreaded${COMPILE_POSTFIX} BulletSoftBody${COMPILE_POSTFIX} BulletSoftBodySolvers_OpenCL_Mini${COMPILE_POSTFIX} LinearMath${COMPILE_POSTFIX} MiniCL${COMPILE_POSTFIX})
ELSE()
    # Look for the header file.
    IF(ACGL_GLOBAL_EXTERN_DIR)
        FIND_PATH(BULLET_INCLUDE_DIR NAMES btBulletCollisionCommon.h PATHS "${ACGL_GLOBAL_EXTERN_DIR}/bullet/src" NO_DEFAULT_PATH)
    ENDIF()
    IF(NOT BULLET_INCLUDE_DIR)
        FIND_PATH(BULLET_INCLUDE_DIR NAMES btBulletCollisionCommon.h)
    ENDIF()

    # Look for the library file.
    IF(ACGL_GLOBAL_EXTERN_DIR)
        FIND_LIBRARY(BULLET_LIBRARIES NAMES BulletCollision${COMPILE_POSTFIX} BulletDynamics${COMPILE_POSTFIX} BulletMultiThreaded${COMPILE_POSTFIX} BulletSoftBody${COMPILE_POSTFIX} BulletSoftBodySolvers_OpenCL_Mini${COMPILE_POSTFIX} LinearMath${COMPILE_POSTFIX} MiniCL${COMPILE_POSTFIX} PATHS "${ACGL_GLOBAL_EXTERN_DIR}/bullet/lib" NO_DEFAULT_PATH)
    ENDIF()
    IF(NOT BULLET_LIBRARIES)
        FIND_LIBRARY(BULLET_LIBRARIES NAMES BulletCollision${COMPILE_POSTFIX} BulletDynamics${COMPILE_POSTFIX} BulletMultiThreaded${COMPILE_POSTFIX} BulletSoftBody${COMPILE_POSTFIX} BulletSoftBodySolvers_OpenCL_Mini${COMPILE_POSTFIX} LinearMath${COMPILE_POSTFIX} MiniCL${COMPILE_POSTFIX})
    ENDIF()
ENDIF()

# Copy the results to the output variables.
IF(BULLET_INCLUDE_DIR AND BULLET_LIBRARIES)
    SET(BULLET_FOUND TRUE CACHE INTERNAL "")
ELSE()
    SET(BULLET_FOUND FALSE CACHE INTERNAL "")
ENDIF()

# Report the results.
IF(NOT BULLET_FOUND)
    SET(BULLET_MESSAGE "bullet was not found. Make sure BULLET_INCLUDE_DIR AND BULLET_LIBRARIES are set correctly.")
    IF(BULLET_FIND_REQUIRED)
        MESSAGE(FATAL_ERROR "${BULLET_MESSAGE}")
    ELSEIF(NOT BULLET_FIND_QUIETLY)
        MESSAGE(STATUS "${BULLET_MESSAGE}")
    ENDIF()
ELSEIF(NOT BULLET_FIND_QUIETLY)
    MESSAGE(STATUS "Looking for bullet - found")
ENDIF()

MESSAGE(STATUS "BULLET_INCLUDE_DIR:${BULLET_INCLUDE_DIR}")
MESSAGE(STATUS "BULLET_LIBRARIES:${BULLET_LIBRARIES}")


text:
#ifndef _HGPU_CONSTANTS_H_
#define _HGPU_CONSTANTS_H_

// permanent constants
#define _KB                                  1024    ///< size: 1 kilobyte
#define _MB                             (_KB*_KB)    ///< size: 1 megabyte
#define _GB                             (_KB*_MB)    ///< size: 1 gigabyte

// logging severity
#define HGPU_LOGGING_EVERYTHING                 0   ///< logging: output everything
#define HGPU_LOGGING_DETAILS                    1   ///< logging: output detailed information
#define HGPU_LOGGING_INFO                       2   ///< logging: output information
#define HGPU_LOGGING_WARNING                    3   ///< logging: output warnings
#define HGPU_LOGGING_ERROR                      4   ///< logging: output errors
#define HGPU_LOGGING_FATAL                      5   ///< logging: output fatal information
#define HGPU_LOGGING_MAX                        6   ///< logging: maximal possible level of logging

// path symbols and vars
#define HGPU_CHAR_PATH_LINUX                  '/'   ///< char: path separator for Linux platform
#define HGPU_CHAR_PATH_WINDOWS               '\\'   ///< char: path separator for Windows platform
#define HGPU_FILENAME_MAX            FILENAME_MAX   ///< the maximum allowed length of string with filename or path

#define HGPU_PATH_SEPARATOR_LINUX             "/"
#define HGPU_PATH_SEPARATOR_WINDOWS          "\\"

// char constants
#define HGPU_CHAR_EMPTY                         0   ///< char: empty character (end of string)
#define HGPU_CHAR_NEWLINE                    '\n'   ///< char: new line (end of line)
#define HGPU_CHAR_CR                         '\r'   ///< char: carriage return
#define HGPU_CHAR_TAB                        '\t'
#define HGPU_CHAR_EQ                         '='
#define HGPU_CHAR_MINUS                      '-'
#define HGPU_CHAR_SLASH                      '/'
#define HGPU_CHAR_SPACE                      ' '
#define HGPU_CHAR_DOT                        '.'

// precision constants
#define HGPU_PRECISION_SINGLE           "SINGLE"
#define HGPU_PRECISION_DOUBLE           "DOUBLE"
#define HGPU_PRECISION_MIXED             "MIXED"

// string constants
#define HGPU_MAX_STR_INFO_LENGHT            4096    ///<  maximal length of the temporary buffers
#define HGPU_MAX_FILE_READ_BUFFER           8192    ///<  maximal length for reading buffer
#define HGPU_MAX_ENVIRONMENT_LENGTH         8192    ///<  maximal length for environment variable

// GPU vendors
#define HGPU_VENDOR_AMD                        "Advanced Micro Devices"
#define HGPU_VENDOR_APPLE                      "APPLE"
#define HGPU_VENDOR_INTEL                      "Intel"
#define HGPU_VENDOR_NVIDIA                     "NVIDIA"

// constants for parameters
#define HGPU_MAX_PARAMETERS                 1024
#define HGPU_PARAMETERS_STEP                  64

// WARNING!: new parameters should be also included in HGPU_parameters_get_from_environment() procedure
#define HGPU_PARAMETER_DEVICE                  "DEVICE"
#define HGPU_PARAMETER_PLATFORM                "PLATFORM"
#define HGPU_PARAMETER_DEVICE_TYPE             "DEVICE_TYPE"
#define HGPU_PARAMETER_WAIT_FOR_KEYPRESS       "WAIT_FOR_KEYPRESS"
#define HGPU_PARAMETER_SHOW_STAGE              "SHOW_STAGE"
#define HGPU_PARAMETER_PROFILING               "PROFILING"
#define HGPU_PARAMETER_BRIEF_REPORT            "BRIEF_REPORT"
#define HGPU_PARAMETER_REBUILD_BINARIES        "REBUILD_BINARIES"
#define HGPU_PARAMETER_PATH_CL_ROOT            "PATH_CL_ROOT"
#define HGPU_PARAMETER_PATH_INF                "PATH_INF"
#define HGPU_PARAMETER_PATH_WORKING            "PATH_WORKING"
#define HGPU_PARAMETER_WARNING_ERROR           "WARNING_ERROR"
#define HGPU_PARAMETER_NO_CACHE                "NO_CACHE"
#define HGPU_PARAMETER_MAX_WORKGROUP_SIZE      "MAX_WORKGROUP_SIZE"
#define HGPU_PARAMETER_DEVICES_NUMBER          "DEVICES_NUMBER"
#define HGPU_PARAMETER_PRNG                    "PRNG"
#define HGPU_PARAMETER_PRNG_RANDSERIES         "PRNG_RANDSERIES"
#define HGPU_PARAMETER_PRNG_PRECISION          "PRNG_PRECISION"
#define HGPU_PARAMETER_PRNG_SAMPLES            "PRNG_SAMPLES"
#define HGPU_PARAMETER_PRNG_INSTANCES          "PRNG_INSTANCES"
#define HGPU_PARAMETER_PRNG_SEED1              "PRNG_SEED1"
#define HGPU_PARAMETER_PRNG_SEED2              "PRNG_SEED2"
#define HGPU_PARAMETER_PRNG_SEED3              "PRNG_SEED3"
#define HGPU_PARAMETER_PRNG_SEED4              "PRNG_SEED4"
#define HGPU_PARAMETER_PRNG_RANLUX_NSKIP       "PRNG_RANLUX_NSKIP"
#define HGPU_PARAMETER_PRNG_TEST_MAX_PASSES    "PRNG_TEST_MAX_DURATION"
#define HGPU_PARAMETER_PRNG_TEST_MAX_DURATION  "PRNG_TEST_MAX_DURATION"

#define HGPU_PARAMETER_INF_PLATFORM            "PLATFORM"
#define HGPU_PARAMETER_INF_DEVICE              "DEVICE"
#define HGPU_PARAMETER_INF_MD5                 "MD5"
#define HGPU_PARAMETER_INF_NUMBER              "NUMBER"
#define HGPU_PARAMETER_INF_OPTIONS             "OPTIONS"
#define HGPU_PARAMETER_INF_DATE                "DATE"

#define HGPU_ENVIRONMENT_PREFIX                "HGPU_"

#define HGPU_GPU_ROOT_FILE                     "hgpucl.txt"

#define HGPU_SYMBOL_NEWLINE                    "\n"
#define HGPU_SYMBOL_REMARK                     "#"
#define HGPU_SYMBOL_EQ                         "="

#ifndef FILENAME_MAX
#define FILENAME_MAX    4096
#endif

#define HGPU_FILENAME_MAX   FILENAME_MAX // MIN(FILENAME_MAX,4096)

// SAFE_LINUX_TIMER = turn on safe timer for linux (timer counts only CPU time, not real time)
#ifndef _WIN32
#define SAFE_LINUX_TIMER
#endif

#define MIN(a,b) (((a) < (b)) ? (a) : (b))
#define MAX(a,b) (((a) > (b)) ? (a) : (b))
#define CEIL(a)  ((a - (int)a)==0 ? (int)a : (int)a+1)

#endif // _HGPU_CONSTANTS_H_


text:
<?php

namespace POData\Providers\Expression;

use POData\UriProcessor\QueryProcessor\ExpressionParser\Expressions\ExpressionType;
use POData\Providers\Metadata\Type\IType;
use POData\Common\ODataConstants;
use POData\Providers\Expression\IExpressionProvider;
use POData\Providers\Metadata\ResourceType;
use POData\UriProcessor\QueryProcessor\ExpressionParser\Expressions\PropertyAccessExpression;
use POData\UriProcessor\QueryProcessor\FunctionDescription;

class MySQLExpressionProvider implements IExpressionProvider
{
    const ADD                   = '+';
    const CLOSE_BRACKET         = ')';
    const COMMA                 = ',';
    const DIVIDE                = '/';
    const SUBTRACT              = '-';
    const EQUAL                 = '=';
    const GREATER_THAN          = '>';
    const GREATER_THAN_OR_EQUAL = '>=';
    const LESS_THAN             = '<';
    const LESS_THAN_OR_EQUAL    = '<=';
    const LOGICAL_AND           = '&&';
    const LOGICAL_NOT           = '!';
    const LOGICAL_OR            = '||';
    const MEMBER_ACCESS         = '';
    const MODULO                = '%';
    const MULTIPLY              = '*';
    const NEGATE                = '-';
    const NOT_EQUAL             = '!=';
    const OPEN_BRACKET           = '(';

    /**
     * The type of the resource pointed by the resource path segment
     *
     * @var ResourceType
     */
    private $resourceType;

    private $entityMapping;

    /**
     * Constructs new instance of MySQLExpressionProvider
     *
     */
    public function __construct()
    {
    	$this->entityMapping = array();
    }

    /**
     * Get the name of the iterator
     *
     * @return string
     */
    public function getIteratorName()
    {
        return null;
    }

    /**
     * call-back for setting the resource type.
     *
     * @param ResourceType $resourceType The resource type on which the filter is going to be applied.
     *
     */
    public function setResourceType(ResourceType $resourceType)
    {
    	$this->resourceType = $resourceType;
    }

    /**
     * Call-back for logical expression
     *
     * @param ExpressionType $expressionType The type of logical expression.
     * @param string         $left           The left expression.
     * @param string         $right          The left expression.
     *
     * @return string
     */
    public function onLogicalExpression($expressionType, $left, $right)
    {
        switch($expressionType) {
	        case ExpressionType::AND_LOGICAL:
	            return $this->_prepareBinaryExpression(self::LOGICAL_AND, $left, $right);

	        case ExpressionType::OR_LOGICAL:
	            return $this->_prepareBinaryExpression(self::LOGICAL_OR, $left, $right);

	        default:
	            throw new \InvalidArgumentException('onLogicalExpression');
        }
    }

    /**
     * Call-back for arithmetic expression
     *
     * @param ExpressionType $expressionType The type of arithmetic expression.
     * @param string         $left           The left expression.
     * @param string         $right          The left expression.
     *
     * @return string
     */
    public function onArithmeticExpression($expressionType, $left, $right)
    {
        switch($expressionType) {
	        case ExpressionType::MULTIPLY:
	            return $this->_prepareBinaryExpression(self::MULTIPLY, $left, $right);

	        case ExpressionType::DIVIDE:
	            return $this->_prepareBinaryExpression(self::DIVIDE, $left, $right);

	        case ExpressionType::MODULO:
	            return $this->_prepareBinaryExpression(self::MODULO, $left, $right);

	        case ExpressionType::ADD:
	            return $this->_prepareBinaryExpression(self::ADD, $left, $right);

	        case ExpressionType::SUBTRACT:
	            return $this->_prepareBinaryExpression(self::SUBTRACT, $left, $right);

	        default:
	            throw new \InvalidArgumentException('onArithmeticExpression');
        }
    }

    /**
     * Call-back for relational expression
     *
     * @param ExpressionType $expressionType The type of relation expression
     * @param string         $left           The left expression
     * @param string         $right          The left expression
     *
     * @return string
     */
    public function onRelationalExpression($expressionType, $left, $right)
    {
        switch($expressionType) {
	        case ExpressionType::GREATERTHAN:
	            return $this->_prepareBinaryExpression(self::GREATER_THAN, $left, $right);

	        case ExpressionType::GREATERTHAN_OR_EQUAL:
	            return $this->_prepareBinaryExpression(self::GREATER_THAN_OR_EQUAL, $left, $right);

	        case ExpressionType::LESSTHAN:
	            return $this->_prepareBinaryExpression(self::LESS_THAN, $left, $right);

	        case ExpressionType::LESSTHAN_OR_EQUAL:
	            return $this->_prepareBinaryExpression(self::LESS_THAN_OR_EQUAL, $left, $right);

	        case ExpressionType::EQUAL:
	            return $this->_prepareBinaryExpression(self::EQUAL, $left, $right);

	        case ExpressionType::NOTEQUAL:
	            return $this->_prepareBinaryExpression(self::NOT_EQUAL, $left, $right);

	        default:
	            throw new \InvalidArgumentException('onArithmeticExpression');
        }
    }

    /**
     * Call-back for unary expression
     *
     * @param ExpressionType $expressionType The type of unary expression
     * @param string         $child          The child expression
     *
     * @return string
     */
    public function onUnaryExpression($expressionType, $child)
    {
        switch($expressionType) {
	        case ExpressionType::NEGATE:
	            return $this->_prepareUnaryExpression(self::NEGATE, $child);

	        case ExpressionType::NOT_LOGICAL:
	            return $this->_prepareUnaryExpression(self::LOGICAL_NOT, $child);

	        default:
	            throw new \InvalidArgumentException('onUnaryExpression');
        }
    }

    /**
     * Call-back for constant expression
     *
     * @param IType  $type  The type of constant
     * @param mixed $value The value of the constant
     *
     * @return string
     */
    public function onConstantExpression(IType $type, $value)
    {
        if (is_bool($value)) {
            return var_export($value, true);
        } else if (is_null($value)) {
            return var_export(null, true);
        }

        return $value;
    }

    /**
     * Call-back for property access expression
     *
     * @param PropertyAccessExpression $expression The property access expression
     *
     * @return string
     */

    public function onPropertyAccessExpression($expression)
    {
        $parent = $expression;
        $variable = null;
        $entityTypeName = $this->resourceType->getName();
        $propertyName = $parent->getResourceProperty()->getName();
        if (is_array($this->entityMapping)) {
        	if (array_key_exists($entityTypeName, $this->entityMapping)) {
        		if (array_key_exists($propertyName, $this->entityMapping[$entityTypeName])) {
        			return $this->entityMapping[$entityTypeName][$propertyName];
        		}
        	}
        }

        return $propertyName;
    }

    /**
     * Call-back for function call expression
     *
     * @param FunctionDescription $functionDescription Description of the function.
     * @param array<string>       $params              Paameters to the function.
     *
     * @return string
     */
    public function onFunctionCallExpression($functionDescription, $params)
    {
        switch($functionDescription->name) {
	        case ODataConstants::STRFUN_COMPARE:
	            return "STRCMP($params[0], $params[1])";

	        case ODataConstants::STRFUN_ENDSWITH:
	            return "(STRCMP($params[1],RIGHT($params[0],LENGTH($params[1]))) = 0)";

	        case ODataConstants::STRFUN_INDEXOF:
	            return "INSTR($params[0], $params[1]) - 1";

	        case ODataConstants::STRFUN_REPLACE:
	            return "REPLACE($params[0],$params[1],$params[2])";

	        case ODataConstants::STRFUN_STARTSWITH:
	            return "(STRCMP($params[1],LEFT($params[0],LENGTH($params[1]))) = 0)";

	        case ODataConstants::STRFUN_TOLOWER:
	            return "LOWER($params[0])";

	        case ODataConstants::STRFUN_TOUPPER:
	            return "UPPER($params[0])";

	        case ODataConstants::STRFUN_TRIM:
	            return "TRIM($params[0])";

	        case ODataConstants::STRFUN_SUBSTRING:
	            return count($params) == 3 ?
	                "SUBSTRING($params[0], $params[1] + 1, $params[2])" :
	                "SUBSTRING($params[0], $params[1] + 1)";

	        case ODataConstants::STRFUN_SUBSTRINGOF:
	            return "(LOCATE($params[0], $params[1]) > 0)";

	        case ODataConstants::STRFUN_CONCAT:
	            return "CONCAT($params[0],$params[1])";

	        case ODataConstants::STRFUN_LENGTH:
	            return "LENGTH($params[0])";

	        case ODataConstants::GUIDFUN_EQUAL:
		        return "STRCMP($params[0], $params[1])";

	        case ODataConstants::DATETIME_COMPARE:
	            return "DATETIMECMP($params[0]; $params[1])";

	        case ODataConstants::DATETIME_YEAR:
	            return "EXTRACT(YEAR from ".$params[0].")";

	        case ODataConstants::DATETIME_MONTH:
	            return "EXTRACT(MONTH from ".$params[0].")";

	        case ODataConstants::DATETIME_DAY:
	            return "EXTRACT(DAY from ".$params[0].")";

	        case ODataConstants::DATETIME_HOUR:
	            return "EXTRACT(HOUR from ".$params[0].")";

	        case ODataConstants::DATETIME_MINUTE:
	            return "EXTRACT(MINUTE from ".$params[0].")";

	        case ODataConstants::DATETIME_SECOND:
	            return "EXTRACT(SECOND from ".$params[0].")";

	        case ODataConstants::MATHFUN_ROUND:
	            return "ROUND($params[0])";

	        case ODataConstants::MATHFUN_CEILING:
	            return "CEIL($params[0])";

	        case ODataConstants::MATHFUN_FLOOR:
	            return "FLOOR($params[0])";

	        case ODataConstants::BINFUL_EQUAL:
		        return "($params[0] = $params[1])";

	        case 'is_null':
	            return "is_null($params[0])";

	        default:
	            throw new \InvalidArgumentException('onFunctionCallExpression');
        }
    }

    /**
     * To format binary expression
     *
     * @param string $operator The binary operator.
     * @param string $left     The left operand.
     * @param string $right    The right operand.
     *
     * @return string
     */
    private function _prepareBinaryExpression($operator, $left, $right)
    {
    	//DATETIMECMP
    	if (!substr_compare($left, "DATETIMECMP", 0, 11)) {
    		$str = explode(';', $left, 2);
    		$str[0] = str_replace('DATETIMECMP', '', $str[0]);
    		return self::OPEN_BRACKET
    			. $str[0] . ' ' . $operator
    			. ' ' . $str[1] . self::CLOSE_BRACKET;
    	}

        return self::OPEN_BRACKET . $left . ' ' . $operator . ' ' . $right . self::CLOSE_BRACKET;
    }

    /**
     * To format unary expression
     *
     * @param string $operator The unary operator.
     * @param string $child    The operand.
     *
     * @return string
     */
    private function _prepareUnaryExpression($operator, $child)
    {
        return $operator . self::OPEN_BRACKET . $child . self::CLOSE_BRACKET;
    }
}