text:
import requests
import json
import re
import fileinput

from optparse import OptionParser
import subprocess
import os
import sys
import time

from couchbase.bucket import Bucket
import couchbase

"""

# An evolving thing - takes as input:
- a file which is the output from perfrunner - this file will contain some json which describes the perf results
- the perf keys and expected values

This program parses out the results from the files and compares them against the expected values

"""

test_workload_output = '''
[20/Oct/2015 15:01:26] INFO - Creating new database: iostatperfregression_410-4859-enterprise_27b10170106
[20/Oct/2015 15:01:29] INFO - Creating new database: ns_serverperfregression_410-4859-enterprise_27bbucket-110170107
[20/Oct/2015 15:02:08] INFO - Adding snapshot: perfregression_410-4859-enterprise_27b_access
[20/Oct/2015 15:02:15] INFO - http://cbmonitor.sc.couchbase.com/reports/html/?snapshot=perfregression_410-4859-enterprise_27b_access
[20/Oct/2015 15:03:04] INFO - http://cbmonitor.sc.couchbase.com/reports/get_corr_matrix/?snapshot=perfregression_410-4859-enterprise_27b_access
[20/Oct/2015 15:03:31] INFO - Dry run stats: {
    "build": "4.1.0-4859-enterprise",
    "build_url": null,
    "metric": "perf_sanity_kv_latency_mixed_2M_short_get_95th_perf_sanity_base_test",
    "snapshots": [
        "perfregression_410-4859-enterprise_27b_access"
    ],
    "value": 0.56
}
[20/Oct/2015 15:03:31] INFO - Dry run stats: {
    "build": "4.1.0-4859-enterprise",
    "build_url": null,
    "metric": "perf_sanity_kv_latency_mixed_2M_short_set_95th_perf_sanity_base_test",
    "snapshots": [
        "perfregression_410-4859-enterprise_27b_access"
    ],
    "value": 0.95
}
[20/Oct/2015 15:03:31] INFO - Terminating local Celery workers
'''

def main():
    print 'Starting the perf regression runner'

    usage = '%prog -f conf-file'
    parser = OptionParser(usage)

    parser.add_option('-f', '--filename', dest='filename')
    parser.add_option('-v', '--version', dest='version')
    parser.add_option('-s', '--summaryFile', dest='summaryFile')

    options, args = parser.parse_args()
    summary = []

    for line in fileinput.input(options.filename):

        time.sleep(10)

        if line[0] == '#' or len(line.strip()) == 0:
            continue

        test, spec, params = line.split()
        print '\n\n', time.asctime( time.localtime(time.time()) ), 'Now running', test
        current_summary = {'test': test, 'status':'run', 'results':[]}

        test = 'perfSanity/tests/' + test
        spec = 'perfSanity/clusters/' + spec

        my_env = os.environ
        my_env['cluster'] = spec
        my_env['test_config'] = test
        my_env['version'] = options.version
        # proc = subprocess.Popen('ls', env=my_env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

        #"""
        proc = subprocess.Popen('./scripts/setup.sh', env=my_env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                                shell=True)

        for line in iter(proc.stdout.readline, ''):
            print 'Setup output', line
            sys.stdout.flush()

        (stdoutdata, stderrdata) = proc.communicate()

        if proc.returncode == 1:
            print '\n\nHave an error during setup'
            print stderrdata
            print stdoutdata
            current_summary['output'] = '  Have an error during setup'
            current_summary['status'] = 'not run'
            summary.append(current_summary)
            continue

        print 'Setup complete, starting workload'
        sys.stdout.flush()
        proc = subprocess.Popen('./perfSanity/scripts/workload_dev.sh', env=my_env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        workload_output = ''
        for line in iter(proc.stdout.readline, ''):
            print line
            workload_output += line

        (stdoutdata, stderrdata) = proc.communicate()

        print 'stderrdata', stderrdata

        if proc.returncode == 1:
            print '  Have an error during workload generation'
            current_summary['output'] = '  Have an error during workload generation'
            sys.stdout.flush()
            current_summary['status'] = 'not run'
            print stderrdata
            summary.append(current_summary)
            continue

        print '\n\nWorkload complete, analyzing results'
        #"""
        # parse the line for actual values
        #workload_output = test_workload_output
        p = re.compile(r'Dry run stats: {(.*?)}', re.MULTILINE)
        matches = p.findall(workload_output.replace('\n', ''))

        actual_values = {}
        for m in matches:
            actual = json.loads('{' + m + '}')
            actual_values[actual['metric']] = actual  # ( json.loads('{' + m + '}') )
        print '\n\nWorkload gen output:', workload_output, '\n\n'

        expected_keys = json.loads(params)
        for k in expected_keys.keys():
            if k in actual_values:

                current_summary['results'].append( {'metric':k, 'expected':expected_keys[k], 'actual':actual_values[k][ 'value']})
                if actual_values[k]['value'] > 1.05 * expected_keys[k]:
                    print '  ', k, ' is greater than expected. Expected', expected_keys[k], 'Actual', actual_values[k][
                        'value']

                elif actual_values[k]['value'] < 0.95 * expected_keys[k]:
                    # sort of want to yellow flag this but for now all we have is a red flag so use that
                    print '  ', k, ' is less than expected. Expected', expected_keys[k], 'Actual', actual_values[k][
                        'value']

                del actual_values[k]
            else:
                current_summary['results'].append( {'metric':k, 'expected':'Not found' , 'actual':k})
                print '  Expected key', k, ' is not found'
                #current_summary['output'] += '\n    Expected key {0} is not found'.format(k)

        if len(actual_values) > 0:
            print '  The following key(s) were present but not expected:'
            for i in actual_values:
                print '    ', i
                current_summary['results'].append( {'metric':k, 'expected':i , 'actual':'Not found'})

        summary.append(current_summary)
        print '\nCompleted analysis for', test
        time.sleep(10)
    # end the for loop - print the results

    all_success = True
    fo = open(options.summaryFile, "wb")

    print '\n\nTest\t\t\t\t\t\t\tMetric\t\t\t\t\t\t\tActual\t\t\tExpected'
    for i in summary:
        #fo.write( '\n' + i['test'])
        if i['status'] == 'not run':
           print i['test'], 'not run:', i['output']
           all_success = False
        else:
            for j in i['results']:
               print i['test'], '\t', j['metric'], '\t', j['actual'], '\t', j['expected'],
               if j['actual'] == 'Not found' or j['expected'] == 'Not found':
                  all_success = False
               else:
                  # do the compares
                  if j['actual']  > 1.1 * j['expected']:
                      print '\tactual is too large',
                      all_success = False
                  elif j['actual']  < 0.9 * j['expected']:
                      print '\tactual is too small',
                      all_success = False
               print
        print # blank line at end of test

    #endfor all tests
    fo.close()
    return all_success

if __name__ == "__main__":
    if not main():
        sys.exit(1)


text:
require "helper"
require "thor/base"

class Amazing
  desc "hello", "say hello"
  def hello
    puts "Hello"
  end
end

describe Thor::Base do
  describe "#initialize" do
    it "sets arguments array" do
      base = MyCounter.new [1, 2]
      expect(base.first).to eq(1)
      expect(base.second).to eq(2)
    end

    it "sets arguments default values" do
      base = MyCounter.new [1]
      expect(base.second).to eq(2)
    end

    it "sets options default values" do
      base = MyCounter.new [1, 2]
      expect(base.options[:third]).to eq(3)
    end

    it "allows options to be given as symbols or strings" do
      base = MyCounter.new [1, 2], :third => 4
      expect(base.options[:third]).to eq(4)

      base = MyCounter.new [1, 2], "third" => 4
      expect(base.options[:third]).to eq(4)
    end

    it "creates options with indifferent access" do
      base = MyCounter.new [1, 2], :third => 3
      expect(base.options["third"]).to eq(3)
    end

    it "creates options with magic predicates" do
      base = MyCounter.new [1, 2], :third => 3
      expect(base.options.third).to eq(3)
    end
  end

  describe "#no_commands" do
    it "avoids methods being added as commands" do
      expect(MyScript.commands.keys).to include("animal")
      expect(MyScript.commands.keys).not_to include("this_is_not_a_command")
    end
  end

  describe "#argument" do
    it "sets a value as required and creates an accessor for it" do
      expect(MyCounter.start(%w(1 2 --third 3))[0]).to eq(1)
      expect(Scripts::MyScript.start(%w(zoo my_special_param --param=normal_param))).to eq("my_special_param")
    end

    it "does not set a value in the options hash" do
      expect(BrokenCounter.start(%w(1 2 --third 3))[0]).to be nil
    end
  end

  describe "#arguments" do
    it "returns the arguments for the class" do
      expect(MyCounter.arguments.size).to be(2)
    end
  end

  describe ":aliases" do
    it "supports string aliases without a dash prefix" do
      expect(MyCounter.start(%w(1 2 -z 3))[4]).to eq(3)
    end

    it "supports symbol aliases" do
      expect(MyCounter.start(%w(1 2 -y 3))[5]).to eq(3)
      expect(MyCounter.start(%w(1 2 -r 3))[5]).to eq(3)
    end
  end

  describe "#class_option" do
    it "sets options class wise" do
      expect(MyCounter.start(%w(1 2 --third 3))[2]).to eq(3)
    end

    it "does not create an accessor for it" do
      expect(BrokenCounter.start(%w(1 2 --third 3))[3]).to be false
    end
  end

  describe "#class_options" do
    it "sets default options overwriting superclass definitions" do
      options = Scripts::MyScript.class_options
      expect(options[:force]).not_to be_required
    end
  end

  describe "#remove_argument" do
    it "removes previously defined arguments from class" do
      expect(ClearCounter.arguments).to be_empty
    end

    it "undefine accessors if required" do
      expect(ClearCounter.new).not_to respond_to(:first)
      expect(ClearCounter.new).not_to respond_to(:second)
    end
  end

  describe "#remove_class_option" do
    it "removes previous defined class option" do
      expect(ClearCounter.class_options[:third]).to be nil
    end
  end

  describe "#class_options_help" do
    before do
      @content = capture(:stdout) { MyCounter.help(Thor::Base.shell.new) }
    end

    it "shows option's description" do
      expect(@content).to match(/# The third argument/)
    end

    it "shows usage with banner content" do
      expect(@content).to match(/\[\-\-third=THREE\]/)
    end

    it "shows default values below descriptions" do
      expect(@content).to match(/# Default: 3/)
    end

    it "shows options in different groups" do
      expect(@content).to match(/Options\:/)
      expect(@content).to match(/Runtime options\:/)
      expect(@content).to match(/\-p, \[\-\-pretend\]/)
    end

    it "use padding in options that do not have aliases" do
      expect(@content).to match(/^  -t, \[--third/)
      expect(@content).to match(/^          \[--fourth/)
    end

    it "allows extra options to be given" do
      hash = {"Foo" => B.class_options.values}

      content = capture(:stdout) { MyCounter.send(:class_options_help, Thor::Base.shell.new, hash) }
      expect(content).to match(/Foo options\:/)
      expect(content).to match(/--last-name=LAST_NAME/)
    end

    it "displays choices for enums" do
      content = capture(:stdout) { Enum.help(Thor::Base.shell.new) }
      expect(content).to match(/Possible values\: apple, banana/)
    end
  end

  describe "#namespace" do
    it "returns the default class namespace" do
      expect(Scripts::MyScript.namespace).to eq("scripts:my_script")
    end

    it "sets a namespace to the class" do
      expect(Scripts::MyDefaults.namespace).to eq("default")
    end
  end

  describe "#group" do
    it "sets a group" do
      expect(MyScript.group).to eq("script")
    end

    it "inherits the group from parent" do
      expect(MyChildScript.group).to eq("script")
    end

    it "defaults to standard if no group is given" do
      expect(Amazing.group).to eq("standard")
    end
  end

  describe "#subclasses" do
    it "tracks its subclasses in an Array" do
      expect(Thor::Base.subclasses).to include(MyScript)
      expect(Thor::Base.subclasses).to include(MyChildScript)
      expect(Thor::Base.subclasses).to include(Scripts::MyScript)
    end
  end

  describe "#subclass_files" do
    it "returns tracked subclasses, grouped by the files they come from" do
      thorfile = File.join(File.dirname(__FILE__), "fixtures", "script.thor")
      expect(Thor::Base.subclass_files[File.expand_path(thorfile)]).to eq([
        MyScript, MyScript::AnotherScript, MyChildScript, Barn,
        PackageNameScript, Scripts::MyScript, Scripts::MyDefaults,
        Scripts::ChildDefault, Scripts::Arities
      ])
    end

    it "tracks a single subclass across multiple files" do
      thorfile = File.join(File.dirname(__FILE__), "fixtures", "command.thor")
      expect(Thor::Base.subclass_files[File.expand_path(thorfile)]).to include(Amazing)
      expect(Thor::Base.subclass_files[File.expand_path(__FILE__)]).to include(Amazing)
    end
  end

  describe "#commands" do
    it "returns a list with all commands defined in this class" do
      expect(MyChildScript.new).to respond_to("animal")
      expect(MyChildScript.commands.keys).to include("animal")
    end

    it "raises an error if a command with reserved word is defined" do
      expect do
        klass = Class.new(Thor::Group)
        klass.class_eval "def shell; end"
      end.to raise_error(RuntimeError, /"shell" is a Thor reserved word and cannot be defined as command/)
    end
  end

  describe "#all_commands" do
    it "returns a list with all commands defined in this class plus superclasses" do
      expect(MyChildScript.new).to respond_to("foo")
      expect(MyChildScript.all_commands.keys).to include("foo")
    end
  end

  describe "#remove_command" do
    it "removes the command from its commands hash" do
      expect(MyChildScript.all_commands.keys).not_to include("name_with_dashes")
      expect(MyChildScript.commands.keys).not_to include("boom")
    end

    it "undefines the method if desired" do
      expect(MyChildScript.new).not_to respond_to("boom")
    end
  end

  describe "#from_superclass" do
    it "does not send a method to the superclass if the superclass does not respond to it" do
      expect(MyCounter.get_from_super).to eq(13)
    end
  end

  describe "#start" do
    it "raises an error instead of rescuing if THOR_DEBUG=1 is given" do
      begin
        ENV["THOR_DEBUG"] = "1"

        expect do
          MyScript.start %w(what --debug)
        end.to raise_error(Thor::UndefinedCommandError, 'Could not find command "what" in "my_script" namespace.')
      ensure
        ENV["THOR_DEBUG"] = nil
      end
    end

    it "raises an error instead of rescuing if :debug option is given" do
      expect do
        MyScript.start %w(what), :debug => true
      end.to raise_error(Thor::UndefinedCommandError, 'Could not find command "what" in "my_script" namespace.')
    end

    it "does not steal args" do
      args = %w(foo bar --force true)
      MyScript.start(args)
      expect(args).to eq(%w(foo bar --force true))
    end

    it "checks unknown options" do
      expect(capture(:stderr) do
        MyScript.start(%w(foo bar --force true --unknown baz))
      end.strip).to eq("Unknown switches '--unknown'")
    end

    it "checks unknown options except specified" do
      expect(capture(:stderr) do
        expect(MyScript.start(%w(with_optional NAME --omg --invalid))).to eq(["NAME", {}, %w(--omg --invalid)])
      end.strip).to be_empty
    end
  end

  describe "attr_*" do
    it "does not add attr_reader as a command" do
      expect(capture(:stderr) { MyScript.start(%w(another_attribute)) }).to match(/Could not find/)
    end

    it "does not add attr_writer as a command" do
      expect(capture(:stderr) { MyScript.start(%w(another_attribute= foo)) }).to match(/Could not find/)
    end

    it "does not add attr_accessor as a command" do
      expect(capture(:stderr) { MyScript.start(["some_attribute"]) }).to match(/Could not find/)
      expect(capture(:stderr) { MyScript.start(["some_attribute=", "foo"]) }).to match(/Could not find/)
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
/*
A valid parentheses string is either empty (""), "(" + A + ")", or A + B, where A and B are valid parentheses strings, and + represents string concatenation.  For example, "", "()", "(())()", and "(()(()))" are all valid parentheses strings.

A valid parentheses string S is primitive if it is nonempty, and there does not exist a way to split it into S = A+B, with A and B nonempty valid parentheses strings.

Given a valid parentheses string S, consider its primitive decomposition: S = P_1 + P_2 + ... + P_k, where P_i are primitive valid parentheses strings.

Return S after removing the outermost parentheses of every primitive string in the primitive decomposition of S.

Example 1:

Input: "(()())(())"
Output: "()()()"
Explanation:
The input string is "(()())(())", with primitive decomposition "(()())" + "(())".
After removing outer parentheses of each part, this is "()()" + "()" = "()()()".
Example 2:

Input: "(()())(())(()(()))"
Output: "()()()()(())"
Explanation:
The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))".
After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())".
Example 3:

Input: "()()"
Output: ""
Explanation:
The input string is "()()", with primitive decomposition "()" + "()".
After removing outer parentheses of each part, this is "" + "" = "".

*/

package main

import (
	"log"
	"strings"
)

func main() {
	tests := [][]string{{"(()())(())", "()()()"}, {"(()())(())(()(()))", "()()()()(())"}, {"()()", ""}}

	for _, test := range tests {
		// log.Printf(" removeOuterParentheses(%s) = %s\n", test[0],  removeOuterParentheses(test))

		if removeOuterParentheses(test[0]) != test[1] {
			log.Printf("FAIL: expected %s for removeOuterParentheses(%s)\n", test[0], test[1])
		} else {
			log.Println("PASS")
		}
	}
}

func removeOuterParentheses(pStr string) string {
	var res strings.Builder

	// convert pStr into rune slice for per-character analysis
	pStrRunes := []rune(pStr)

	openCount := 0  // open parenths in current primitive
	closeCount := 0 // close parenths in current primitive
	startIndex := 0 // start index of current primitive
	closeIndex := 0 // close index of current primitive

	for i := 0; i < len(pStrRunes); i++ {
		ch := pStrRunes[i]

		if ch == '(' {
			openCount++
		}

		if ch == ')' {
			closeCount++
		}

		if openCount == closeCount {
			// end of primitive
			openCount = 0
			closeCount = 0

			closeIndex = i
			res.WriteString(pStr[startIndex+1 : closeIndex])

			startIndex = closeIndex + 1
		}
	}

	return res.String()
}


text:
<?php

namespace Spatie\ResponseCache\Test;

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Routing\Router;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
use Orchestra\Testbench\TestCase as Orchestra;
use Spatie\ResponseCache\Facades\ResponseCache;
use Spatie\ResponseCache\Middlewares\CacheResponse;
use Spatie\ResponseCache\Middlewares\DoNotCacheResponse;
use Spatie\ResponseCache\ResponseCacheServiceProvider;

abstract class TestCase extends Orchestra
{
    protected function setUp(): void
    {
        parent::setUp();

        $this->app['responsecache']->clear();

        $this->initializeDirectory($this->getTempDirectory());

        $this->setUpDatabase($this->app);

        $this->setUpRoutes($this->app);

        $this->setUpMiddleware();
    }

    /**
     * @param \Illuminate\Foundation\Application $app
     *
     * @return array
     */
    protected function getPackageProviders($app)
    {
        return [
            ResponseCacheServiceProvider::class,
        ];
    }

    protected function getPackageAliases($app)
    {
        return [
            'ResponseCache' => ResponseCache::class,
        ];
    }

    /**
     * @param \Illuminate\Foundation\Application $app
     */
    protected function getEnvironmentSetUp($app)
    {
        config()->set('database.default', 'sqlite');
        config()->set('database.connections.sqlite', [
            'driver' => 'sqlite',
            'database' => $this->getTempDirectory().'/database.sqlite',
            'prefix' => '',
        ]);

        config()->set('app.key', '6rE9Nz59bGRbeMATftriyQjrpF7DcOQm');
    }

    /**
     * @param \Illuminate\Foundation\Application $app
     */
    protected function setUpDatabase($app)
    {
        file_put_contents($this->getTempDirectory().'/database.sqlite', null);

        $app['db']->connection()->getSchemaBuilder()->create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password', 60);
            $table->rememberToken();
            $table->timestamps();
        });

        foreach (range(1, 10) as $index) {
            User::create(
                [
                    'name' => "user{$index}",
                    'email' => "user{$index}@spatie.be",
                    'password' => "password{$index}",
                ]
            );
        }
    }

    /**
     * @param \Illuminate\Foundation\Application $app
     */
    protected function setUpRoutes($app)
    {
        Route::middleware(CacheResponse::class)->group(function () {
            Route::any('/', function () {
                return 'home of '.(auth()->check() ? auth()->user()->id : 'anonymous');
            });

            Route::any('login/{id}', function ($id) {
                auth()->login(User::find($id));

                return redirect('/');
            });

            Route::any('logout', function () {
                auth()->logout();

                return redirect('/');
            });

            Route::any('/random/{id?}', function () {
                return Str::random();
            });

            Route::any('/csrf_token', ['middleware' => 'web', function () {
                return csrf_token();
            }]);

            Route::any('/redirect', function () {
                return redirect('/');
            });

            Route::any('/uncacheable', ['middleware' => 'doNotCacheResponse', function () {
                return 'uncacheable '.Str::random();
            }]);

            Route::any('/image', function () {
                return response()->file(__DIR__.'/User.php');
            });

            Route::any('/tagged/1', function () {
                return Str::random();
            })->middleware('cacheResponse:,foo');

            Route::any('/tagged/2', function () {
                return Str::random();
            })->middleware('cacheResponse:,foo,bar');
        });

        Route::any('/cache-for-given-lifetime', function () {
            return 'dummy response';
        })->middleware('cacheResponse:300');
    }

    public function getTempDirectory($suffix = '')
    {
        return __DIR__.DIRECTORY_SEPARATOR.'temp'.($suffix == '' ? '' : DIRECTORY_SEPARATOR.$suffix);
    }

    protected function initializeDirectory($directory)
    {
        if (File::isDirectory($directory)) {
            File::deleteDirectory($directory);
        }
        File::makeDirectory($directory);
    }

    protected function setUpMiddleware()
    {
        $this->app[Router::class]->aliasMiddleware('doNotCacheResponse', DoNotCacheResponse::class);
        $this->app[Router::class]->aliasMiddleware('cacheResponse', CacheResponse::class);
    }
}


text:
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

      <link rel="stylesheet" href="./../../helpwin.css">
      <title>MATLAB File Help: prtFeatSelSfs/set</title>

            MATLAB File Help: prtFeatSelSfs/set

prtFeatSelSfs/set

  set - set the object properties

  OBJ = OBJ.set(PARAM, VALUE) sets the parameter PARAM of OBJ
  to the value VALUE. PARAM must be a string indicating the
  parameter to be set.

  OBJ = OBJ.set(PARAM1, VALUE1, PARAM2, VALUE2....) sets all
  the desired parameters to the specified values.

Help for prtFeatSelSfs/set is inherited from superclass prtAction

Method Details

            Defining Class
            prtAction

            Access
            public

            Sealed
            false

            Static
            false


text:
[![CI Status](http://img.shields.io/travis/José Manuel Sánchez/JMSCollectionModel.svg?style=flat)](https://travis-ci.org/José Manuel Sánchez/JMSCollectionModel)
[![Version](https://img.shields.io/cocoapods/v/JMSCollectionModel.svg?style=flat)](http://cocoapods.org/pods/JMSCollectionModel)
[![License](https://img.shields.io/cocoapods/l/JMSCollectionModel.svg?style=flat)](http://cocoapods.org/pods/JMSCollectionModel)
[![Platform](https://img.shields.io/cocoapods/p/JMSCollectionModel.svg?style=flat)](http://cocoapods.org/pods/JMSCollectionModel)

## Usage

To run the example project, clone the repo, and run `pod install` from the Example directory first.

## Requirements

## Installation

JMSCollectionModel is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:

```ruby
pod "JMSCollectionModel"
```

## Author

José Manuel Sánchez, buscarini@gmail.com

## License

JMSCollectionModel is available under the MIT license. See the LICENSE file for more info.


text:
<?xml version="1.0" encoding="utf-8"?>
<COLLADA xmlns="http://www.collada.org/2005/11/COLLADASchema" version="1.4.1">
  <library_materials>
    <material id="lambert1" name="lambert1">
      <instance_effect url="#lambert1-fx"/>
    </material>
  </library_materials>
  <library_effects>
    <effect id="lambert1-fx">
      <profile_COMMON>
        <technique sid="common">
          <lambert>
            <emission>
              <color>0 0 0 1</color>
            </emission>
            <ambient>
              <color>0 0 0 1</color>
            </ambient>
            <diffuse>
              <color>0.4 0.4 0.4 1</color>
            </diffuse>
            <transparent opaque="RGB_ZERO">
              <color>0 0 0 1</color>
            </transparent>
            <transparency>
              <float>1</float>
            </transparency>
          </lambert>
        </technique>
      </profile_COMMON>
    </effect>
  </library_effects>
  <library_geometries>
    <geometry id="pPlaneShape1" name="pPlaneShape1">
      <mesh>
        <source id="pPlaneShape1-positions" name="pPlaneShape1-positions">
          <float_array id="pPlaneShape1-positions-array" count="9">0.5 0 0.5 -0.5 0 -0.5 0.5 0 -0.5</float_array>
          <technique_common>
            <accessor source="#pPlaneShape1-positions-array" count="3" stride="3">
              <param name="X" type="float"/>
              <param name="Y" type="float"/>
              <param name="Z" type="float"/>
            </accessor>
          </technique_common>
        </source>
        <source id="pPlaneShape1-normals" name="pPlaneShape1-normals">
          <float_array id="pPlaneShape1-normals-array" count="9">0 0.9999999 0 0 0.9999999 0 0 0.9999999 0</float_array>
          <technique_common>
            <accessor source="#pPlaneShape1-normals-array" count="3" stride="3">
              <param name="X" type="float"/>
              <param name="Y" type="float"/>
              <param name="Z" type="float"/>
            </accessor>
          </technique_common>
        </source>
        <source id="pPlaneShape1-tangents" name="pPlaneShape1-tangents">
          <float_array id="pPlaneShape1-tangents-array" count="9">0.7071068 0 -0.7071068 0 0 1 -1 0 0</float_array>
          <technique_common>
            <accessor source="#pPlaneShape1-tangents-array" count="3" stride="3">
              <param name="X" type="float"/>
              <param name="Y" type="float"/>
              <param name="Z" type="float"/>
            </accessor>
          </technique_common>
        </source>
        <source id="pPlaneShape1-binormals" name="pPlaneShape1-binormals">
          <float_array id="pPlaneShape1-binormals-array" count="9">-0.7071068 0 -0.7071068 1 0 0 0 0 1</float_array>
          <technique_common>
            <accessor source="#pPlaneShape1-binormals-array" count="3" stride="3">
              <param name="X" type="float"/>
              <param name="Y" type="float"/>
              <param name="Z" type="float"/>
            </accessor>
          </technique_common>
        </source>
        <source id="pPlaneShape1-map1" name="pPlaneShape1-map1">
          <float_array id="pPlaneShape1-map1-array" count="6">1 0 0 1 1 1</float_array>
          <technique_common>
            <accessor source="#pPlaneShape1-map1-array" count="3" stride="2">
              <param name="S" type="float"/>
              <param name="T" type="float"/>
            </accessor>
          </technique_common>
        </source>
        <vertices id="pPlaneShape1-vertices" name="pPlaneShape1-vertices">
          <input semantic="POSITION" source="#pPlaneShape1-positions"/>
          <input semantic="NORMAL" source="#pPlaneShape1-normals"/>
          <input semantic="TANGENT" source="#pPlaneShape1-tangents"/>
          <input semantic="BINORMAL" source="#pPlaneShape1-binormals"/>
        </vertices>
        <triangles material="initialShadingGroup" count="1">
          <input semantic="VERTEX" source="#pPlaneShape1-vertices" offset="0"/>
          <input semantic="TEXCOORD" source="#pPlaneShape1-map1" offset="1" set="0"/>

1 1 0 0 2 2

        </triangles>
      </mesh>
    </geometry>
  </library_geometries>
  <library_visual_scenes>
    <visual_scene id="VisualSceneNode" name="untitled">
      <node id="pPlane1" name="pPlane1" type="NODE">
        <matrix sid="transform">1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1</matrix>
        <instance_geometry url="#pPlaneShape1">
          <bind_material>
            <technique_common>
              <instance_material symbol="initialShadingGroup" target="#lambert1"/>
            </technique_common>
          </bind_material>
        </instance_geometry>
      </node>
    </visual_scene>
  </library_visual_scenes>
</COLLADA>


text:
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Three.js - postprocessing - 3DLUT w/loader</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
    <style>
    html, body {
        margin: 0;
        height: 100%;
    }
    #c {
        width: 100%;
        height: 100%;
        display: block;
    }
  </style>
  </head>
  <body>
    <canvas id="c"></canvas>
  </body>
<script type="importmap">
{
  "imports": {
    "three": "../../build/three.module.js",
    "three/addons/": "../../examples/jsm/"
  }
}
</script>

<script type="module">
import * as THREE from 'three';
import * as lutParser from './resources/lut-reader.js';
import * as dragAndDrop from './resources/drag-and-drop.js';
import {OrbitControls} from 'three/addons/controls/OrbitControls.js';
import {GLTFLoader} from 'three/addons/loaders/GLTFLoader.js';
import {EffectComposer} from 'three/addons/postprocessing/EffectComposer.js';
import {RenderPass} from 'three/addons/postprocessing/RenderPass.js';
import {ShaderPass} from 'three/addons/postprocessing/ShaderPass.js';
import {GammaCorrectionShader} from 'three/addons/shaders/GammaCorrectionShader.js';
import {GUI} from 'three/addons/libs/lil-gui.module.min.js';

function main() {
  const canvas = document.querySelector('#c');
  const renderer = new THREE.WebGLRenderer({canvas});

  const fov = 45;
  const aspect = 2;  // the canvas default
  const near = 0.1;
  const far = 100;
  const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  camera.position.set(0, 10, 20);

  const controls = new OrbitControls(camera, canvas);
  controls.target.set(0, 5, 0);
  controls.update();

  const lutTextures = [
    { name: 'identity',           size: 2, filter: true , },
    { name: 'identity no filter', size: 2, filter: false, },
    { name: 'custom',          url: 'resources/images/lut/3dlut-red-only-s16.png' },
    { name: 'monochrome',      url: 'resources/images/lut/monochrome-s8.png' },
    { name: 'sepia',           url: 'resources/images/lut/sepia-s8.png' },
    { name: 'saturated',       url: 'resources/images/lut/saturated-s8.png', },
    { name: 'posterize',       url: 'resources/images/lut/posterize-s8n.png', },
    { name: 'posterize-3-rgb', url: 'resources/images/lut/posterize-3-rgb-s8n.png', },
    { name: 'posterize-3-lab', url: 'resources/images/lut/posterize-3-lab-s8n.png', },
    { name: 'posterize-4-lab', url: 'resources/images/lut/posterize-4-lab-s8n.png', },
    { name: 'posterize-more',  url: 'resources/images/lut/posterize-more-s8n.png', },
    { name: 'inverse',         url: 'resources/images/lut/inverse-s8.png', },
    { name: 'color negative',  url: 'resources/images/lut/color-negative-s8.png', },
    { name: 'high contrast',   url: 'resources/images/lut/high-contrast-bw-s8.png', },
    { name: 'funky contrast',  url: 'resources/images/lut/funky-contrast-s8.png', },
    { name: 'nightvision',     url: 'resources/images/lut/nightvision-s8.png', },
    { name: 'thermal',         url: 'resources/images/lut/thermal-s8.png', },
    { name: 'b/w',             url: 'resources/images/lut/black-white-s8n.png', },
    { name: 'hue +60',         url: 'resources/images/lut/hue-plus-60-s8.png', },
    { name: 'hue +180',        url: 'resources/images/lut/hue-plus-180-s8.png', },
    { name: 'hue -60',         url: 'resources/images/lut/hue-minus-60-s8.png', },
    { name: 'red to cyan',     url: 'resources/images/lut/red-to-cyan-s8.png' },
    { name: 'blues',           url: 'resources/images/lut/blues-s8.png' },
    { name: 'infrared',        url: 'resources/images/lut/infrared-s8.png' },
    { name: 'radioactive',     url: 'resources/images/lut/radioactive-s8.png' },
    { name: 'goolgey',         url: 'resources/images/lut/googley-s8.png' },
    { name: 'bgy',             url: 'resources/images/lut/bgy-s8.png' },
  ];

  const makeIdentityLutTexture = function() {
    const identityLUT = new Uint8Array([
        0,   0,   0, 255,  // black
      255,   0,   0, 255,  // red
        0,   0, 255, 255,  // blue
      255,   0, 255, 255,  // magenta
        0, 255,   0, 255,  // green
      255, 255,   0, 255,  // yellow
        0, 255, 255, 255,  // cyan
      255, 255, 255, 255,  // white
    ]);

    return function(filter) {
      const texture = new THREE.DataTexture(identityLUT, 4, 2);
      texture.minFilter = texture.magFilter = filter ? THREE.LinearFilter : THREE.NearestFilter;
      texture.needsUpdate = true;
      texture.flipY = false;
      return texture;
    };
  }();

  const makeLUTTexture = function() {
    const imgLoader = new THREE.ImageLoader();
    const ctx = document.createElement('canvas').getContext('2d');

    return function(info) {
      const lutSize = info.size;
      const width = lutSize * lutSize;
      const height = lutSize;
      const texture = new THREE.DataTexture(new Uint8Array(width * height), width, height);
      texture.minFilter = texture.magFilter = info.filter ? THREE.LinearFilter : THREE.NearestFilter;
      texture.flipY = false;

      if (info.url) {

        imgLoader.load(info.url, function(image) {
          ctx.canvas.width = width;
          ctx.canvas.height = height;
          ctx.drawImage(image, 0, 0);
          const imageData = ctx.getImageData(0, 0, width, height);

          texture.image.data = new Uint8Array(imageData.data.buffer);
          texture.image.width = width;
          texture.image.height = height;
          texture.needsUpdate = true;
        });
      }

      return texture;
    };
  }();

  lutTextures.forEach((info) => {
    // if not size set get it from the filename
    if (!info.size) {
      // assumes filename ends in '-s<num>[n]'
      // where <num> is the size of the 3DLUT cube
      // and [n] means 'no filtering' or 'nearest'
      //
      // examples:
      //    'foo-s16.png' = size:16, filter: true
      //    'bar-s8n.png' = size:8, filter: false
      const m = /-s(\d+)(n*)\.[^.]+$/.exec(info.url);
      if (m) {
        info.size = parseInt(m[1]);
        info.filter = info.filter === undefined ? m[2] !== 'n' : info.filter;
      }
      info.texture = makeLUTTexture(info);
    } else {
      info.texture = makeIdentityLutTexture(info.filter);
    }
  });

  const lutNameIndexMap = {};
  lutTextures.forEach((info, ndx) => {
    lutNameIndexMap[info.name] = ndx;
  });

  const lutSettings = {
    lut: lutNameIndexMap.custom,
  };
  const gui = new GUI({ width: 300 });
  gui.add(lutSettings, 'lut', lutNameIndexMap);

  const scene = new THREE.Scene();

  const sceneBG = new THREE.Scene();
  const cameraBG = new THREE.OrthographicCamera(-1, 1, 1, -1, -1, 1);

  let bgMesh;
  let bgTexture;
  {
    const loader = new THREE.TextureLoader();
    bgTexture = loader.load('resources/images/beach.jpg');
    bgTexture.encoding = THREE.sRGBEncoding;
    const planeGeo = new THREE.PlaneGeometry(2, 2);
    const planeMat = new THREE.MeshBasicMaterial({
      map: bgTexture,
      depthTest: false,
    });
    bgMesh = new THREE.Mesh(planeGeo, planeMat);
    sceneBG.add(bgMesh);
  }

  function frameArea(sizeToFitOnScreen, boxSize, boxCenter, camera) {
    const halfSizeToFitOnScreen = sizeToFitOnScreen * 0.5;
    const halfFovY = THREE.MathUtils.degToRad(camera.fov * .5);
    const distance = halfSizeToFitOnScreen / Math.tan(halfFovY);
    // compute a unit vector that points in the direction the camera is now
    // in the xz plane from the center of the box
    const direction = (new THREE.Vector3())
        .subVectors(camera.position, boxCenter)
        .multiply(new THREE.Vector3(1, 0, 1))
        .normalize();

    // move the camera to a position distance units way from the center
    // in whatever direction the camera was from the center already
    camera.position.copy(direction.multiplyScalar(distance).add(boxCenter));

    // pick some near and far values for the frustum that
    // will contain the box.
    camera.near = boxSize / 100;
    camera.far = boxSize * 100;

    camera.updateProjectionMatrix();

    // point the camera to look at the center of the box
    camera.lookAt(boxCenter.x, boxCenter.y, boxCenter.z);
  }

  {
    const gltfLoader = new GLTFLoader();
    gltfLoader.load('resources/models/3dbustchallange_submission/scene.gltf', (gltf) => {
      const root = gltf.scene;
      scene.add(root);

      // fix materials from r114
      root.traverse(({material}) => {
        if (material) {
          material.depthWrite = true;
        }
      });

      root.updateMatrixWorld();
      // compute the box that contains all the stuff
      // from root and below
      const box = new THREE.Box3().setFromObject(root);

      const boxSize = box.getSize(new THREE.Vector3()).length();
      const boxCenter = box.getCenter(new THREE.Vector3());
      frameArea(boxSize * 0.4, boxSize, boxCenter, camera);

      // update the Trackball controls to handle the new size
      controls.maxDistance = boxSize * 10;
      controls.target.copy(boxCenter);
      controls.update();
    });
  }

  const lutShader = {
    uniforms: {
      tDiffuse: { value: null },
      lutMap:  { value: null },
      lutMapSize: { value: 1, },
    },
    vertexShader: `
      varying vec2 vUv;
      void main() {
        vUv = uv;
        gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
      }
    `,
    fragmentShader: `
      #include <common>

      #define FILTER_LUT true

      uniform sampler2D tDiffuse;
      uniform sampler2D lutMap;
      uniform float lutMapSize;

      varying vec2 vUv;

      vec4 sampleAs3DTexture(sampler2D tex, vec3 texCoord, float size) {
        float sliceSize = 1.0 / size;                  // space of 1 slice
        float slicePixelSize = sliceSize / size;       // space of 1 pixel
        float width = size - 1.0;
        float sliceInnerSize = slicePixelSize * width; // space of size pixels
        float zSlice0 = floor( texCoord.z * width);
        float zSlice1 = min( zSlice0 + 1.0, width);
        float xOffset = slicePixelSize * 0.5 + texCoord.x * sliceInnerSize;
        float yRange = (texCoord.y * width + 0.5) / size;
        float s0 = xOffset + (zSlice0 * sliceSize);

        #ifdef FILTER_LUT

          float s1 = xOffset + (zSlice1 * sliceSize);
          vec4 slice0Color = texture2D(tex, vec2(s0, yRange));
          vec4 slice1Color = texture2D(tex, vec2(s1, yRange));
          float zOffset = mod(texCoord.z * width, 1.0);
          return mix(slice0Color, slice1Color, zOffset);

        #else

          return texture2D(tex, vec2( s0, yRange));

        #endif
      }

      void main() {
        vec4 originalColor = texture2D(tDiffuse, vUv);
        gl_FragColor = sampleAs3DTexture(lutMap, originalColor.xyz, lutMapSize);
      }
    `,
  };

  const lutNearestShader = {
    uniforms: {...lutShader.uniforms},
    vertexShader: lutShader.vertexShader,
    fragmentShader: lutShader.fragmentShader.replace('#define FILTER_LUT', '//'),
  };

  const effectLUT = new ShaderPass(lutShader);
  const effectLUTNearest = new ShaderPass(lutNearestShader);

  const renderModel = new RenderPass(scene, camera);
  renderModel.clear = false;  // so we don't clear out the background
  const renderBG = new RenderPass(sceneBG, cameraBG);
  const gammaPass = new ShaderPass(GammaCorrectionShader);

  const composer = new EffectComposer(renderer);

  composer.addPass(renderBG);
  composer.addPass(renderModel);
  composer.addPass(effectLUT);
  composer.addPass(effectLUTNearest);
  composer.addPass(gammaPass);

  function resizeRendererToDisplaySize(renderer) {
    const canvas = renderer.domElement;
    const width = canvas.clientWidth * window.devicePixelRatio | 0;
    const height = canvas.clientHeight * window.devicePixelRatio | 0;

    const needResize = canvas.width !== width || canvas.height !== height;
    if (needResize) {
      renderer.setSize(width, height, false);
    }
    return needResize;
  }

  let then = 0;
  function render(now) {
    now *= 0.001;  // convert to seconds
    const delta = now - then;
    then = now;

    if (resizeRendererToDisplaySize(renderer)) {
      const canvas = renderer.domElement;
      const canvasAspect = canvas.clientWidth / canvas.clientHeight;
      camera.aspect = canvasAspect;
      camera.updateProjectionMatrix();
      composer.setSize(canvas.width, canvas.height);

      // scale the background plane to keep the image's
      // aspect correct.
      // Note the image may not have loaded yet.
      const imageAspect = bgTexture.image ? bgTexture.image.width / bgTexture.image.height : 1;
      const aspect = imageAspect / canvasAspect;
      bgMesh.scale.x = aspect > 1 ? aspect : 1;
      bgMesh.scale.y = aspect > 1 ? 1 : 1 / aspect;
    }

    const lutInfo = lutTextures[ lutSettings.lut ];

    const effect = lutInfo.filter ? effectLUT : effectLUTNearest;
    effectLUT.enabled = lutInfo.filter;
    effectLUTNearest.enabled = !lutInfo.filter;

    const lutTexture = lutInfo.texture;
    effect.uniforms.lutMap.value = lutTexture;
    effect.uniforms.lutMapSize.value = lutInfo.size;

    composer.render(delta);

    requestAnimationFrame(render);
  }

  requestAnimationFrame(render);

  dragAndDrop.setup({msg: 'Drop LUT File here'});
  dragAndDrop.onDropFile(readLUTFile);

  function ext(s) {
    const period = s.lastIndexOf('.');
    return s.slice(period + 1);
  }

  function readLUTFile(file) {
    const reader = new FileReader();
    reader.onload = (e) => {
      const type = ext(file.name);
      const lut = lutParser.lutTo2D3Drgba8(lutParser.parse(e.target.result, type));
      const {size, data, name} = lut;
      const texture = new THREE.DataTexture(data, size * size, size);
      texture.magFilter = THREE.LinearFilter;
      texture.minFilter = THREE.LinearFilter;
      texture.needsUpdate = true;
      texture.flipY = false;
      const lutTexture = {
        name: (name && name.toLowerCase().trim() !== 'untitled')
          ? name
          : file.name,
        size: size,
        filter: true,
        texture,
      };
      lutTextures.push(lutTexture);
      lutSettings.lut = lutTextures.length - 1;

    };

    reader.readAsText(file);
  }
}

main();
</script>
</html>


text:
import * as deepEqual from 'deep-equal';
import * as React from 'react';
import { Component } from 'react';
import uuid from 'uuid';
import validate from 'validate-promise';
import { IFieldConfig, IFormActionsConfig, IFormConfig, IFormErrors, IFormProps, IListRow, IUser } from '../interfaces';
import * as libs from '../libs';

let lib;
let fields;
let FormControl;
let layouts;
let Button;

interface IState {
  data: IListRow;
  errors: IFormErrors;
  form: IFormConfig;
  initialState: any;
  state: any;
  visibility: {
    [key: string]: boolean;
  };
}

/**
 * Create a form
 */
class UiForm extends Component<IFormProps, IState> {

  private fields: { [key: string]: IFieldConfig };
  private actions: IFormActionsConfig;
  private onSubmit: (e: MouseEvent, data: any) => void;

  public static defaultProps: Partial<IFormProps> = {
    data: {},
    errors: {},
    layout: 'reactstrap',
  };

  /**
   * Constructor
   * @param {Object} props props
   */
  constructor(props: IFormProps) {
    super(props);
    const { config, library, onSubmit } = this.props;
    this.fields = config.form.fields;
    const formState = {};

    Object.keys(props.errors).forEach((key) => formState[key] = 'error');
    const values = {};
    Object.keys(this.fields).forEach((key) => {
      const field = this.fields[key];
      field.pristine = true;
      values[key] = field.value || '';
    });

    // Merge config field.values into props.data
    const data = this.makeState({ ...values, ...props.data });
    const state = {
      data,
      errors: props.errors,
      form: config.form,
      initialState: { ...data },
      state: formState,
      visibility: this.makeVisiblity(),
    };
    this.setLib(props);
    this.actions = config.form.actions;
    this.handleChange = this.handleChange.bind(this);
    this.handleBlur = this.handleBlur.bind(this);
    this.onSubmit = onSubmit.bind(this);
    state.form = this.createFormData(state.form, state.data);
    this.state = state;
  }

  /**
   * Will receive new props componentDidUpdate
   * @param {Object} prevProps Props
   */
  public componentDidUpdate(prevProps: IFormProps) {
    if (!deepEqual(this.props, prevProps)) {
      const { config, data, errors } = this.props;
      this.fields = config.form.fields;
      const state = {};
      const visibility = this.makeVisiblity();
      const newState: any = {};
      Object.keys(errors).forEach((key) => state[key] = 'error');
      let { form } = this.state;
      newState.data = this.makeState(data);
      form = this.createFormData(form, data);
      this.setLib(this.props);
      this.setState({ ...newState, state, initialState: { ...newState.data }, errors, form, visibility });
    }
  }

  /**
   * Make field visiblity state from props
   * @return {Object} field visibility
   */
  private makeVisiblity() {
    const { visibility = {} } = this.props;
    Object.keys(this.fields).forEach((key) => {
      if (!visibility.hasOwnProperty(key)) {
        visibility[key] = true;
      }
    });
    return visibility;
  }

  /**
   * Set component names based on the supplied library name
   * @param {Object} newProps props
   */
  private setLib(newProps) {
    const { config, library } = newProps;
    const libType = config.lib || library || 'reactstrap';
    lib = libs[libType];
    fields = lib.fields;
    layouts = lib.layouts;
    FormControl = lib.FormControl;
    Button = lib.Button;
  }

  /**
   * Build the form state, using this.props.data, then field default value
   * for data.
   * @param {Object} data Props
   * @return {Object} list row
   */
  private makeState(data: IListRow): IListRow {
    const state = {};
    Object.keys(this.fields).forEach((name) => {
      const field = this.fields[name];
      const def = field.default;
      if (data && data[name]) {
        state[name] = data[name];
      } else if (def === undefined) {
        state[name] = '';
      } else {
        state[name] = typeof def === 'function'
          ? def(data, field)
          : def;
      }
    });

    return state;
  }

  /**
   * Update the form's properties so that any config value that is a function is
   * run and the current record's data applied.
   * @param {Object} row Form state
   * @return {Object} New form state
   */
  private createFormData(form, row: IListRow) {
    let name;
    const { title } = this.props;
    if (title) {
      form.title = typeof (title) === 'function' ? title(row) : title;
    }

    for (name in form.actions) {
      if (typeof (form.actions[name].label) === 'function') {
        form.actions[name].label = form.actions[name].label(row);
      }
    }
    return form;
  }

  /**
   * Validate a single field
   * @param {Object} field Field
   * @param {String} value Field value
   * @param {Object} data Form data
   * @return {Promise}
   */
  private validateOne(field: IFieldConfig, value: string, data: IListRow = {}): Promise<string> {
    if (field.validate === undefined || field.validate.promises === undefined) {
      return Promise.resolve('');
    }
    const validate = (p) => {
      const msg = p.msg || field.validate.msg;
      return p.rule(value, data, msg, p.arg);
    };

    const promises = field.validate.promises
      .map(validate);

    return new Promise((resolve: Function, reject: Function) => {
      return Promise.all(promises)
        .then(() => resolve('success'))
        .catch((e) => reject(e));
    });
  }

  /**
   * Get validation state
   * @param {string} name column name
   * @return {Object} validation state
   */
  private getValidationState(name: string): Object {
    const field = this.fields[name];
    const { errors } = this.state;
    const state = { ...this.state.state };
    const i = 0;
    const value = this.state.data[name];
    const res = [];
    const serverError = (errors[name] && errors[name].length > 0);
    const serverSuccess = (errors[name] && errors[name].length === 0);

    if (!field.pristine) {
      this.validateOne(field, value, this.state.data)
        .then((ok) => {
          state[name] = 'success';
          errors[name] = [];
          this.setState({ state, errors });
        })
        .catch((err: string) => {
          errors[name] = [err];
          state[name] = 'error';
          this.setState({ state, errors });
        });
    } else {
      if (serverError) {
        state[name] = [serverError];
        state[name] = 'error';
      }
      if (serverSuccess) {
        state[name] = [];
        state[name] = 'success';
      }
    }

    this.setState({ state, errors });
    return state;
  }

  /**
   * Check field access, if no access property then return true
   * Otherwise it should be an object with functions keyed on edit or new
   * @param {string} name Field name to render
   * @return {Bool} Can access field
   */
  private access(name: string): boolean {
    const field = this.fields[name];
    const mode = this.state.data.id === '' ? 'new' : 'edit';

    if (!field.access) {
      return true;
    }

    if (field.access[mode]) {
      return field.access[mode](field, this.state.data);
    }

    return true;
  }

  /**
   * Update the form's state
   * @param {String} name Field name
   * @param {String|number} value Field value
   */
  private handleChange(name: string, value: string | number) {
    const { formUpdate, config } = this.props;
    const field = this.fields[name];
    this.fields[name].pristine = false;
    if (typeof formUpdate === 'function') {
      formUpdate(config.view, field, name, value);
    }
    const data = this.state.data;
    data[name] = value;
    this.setState({ data });

    // Trigger any on change specified in config file.
    if (field.onChange) {
      field.onChange(this);
    }
  }

  /**
   * Get the form's layout
   * @return {Dom} Dom node
   */
  private formLayout() {
    const { layout } = this.props;
    if (typeof layout === 'function') {
      return layout;
    }
    const layoutName = layout && layout[0].toUpperCase() + layout.slice(1);
    return layouts[layoutName] ? layouts[layoutName] : layouts.Default;
  }

  /**
   * Handle field blur - check validation state
   */
  private handleBlur(name: string) {
    this.fields[name].pristine = false;
    const state = this.getValidationState(name);
  }

  /**
   * Buid the react class for the field
   * @param {Object} field Field
   * @return {Element}
   */
  private getReactField(field: IFieldConfig): JSX.Element | null {
    let FieldComponent = null;
    let type;
    if (typeof field === 'function') {
      FieldComponent = field;
    } else {
      switch (typeof field.type) {
        case 'string':
          // Ucase first the name
          type = field.type && field.type[0].toUpperCase()
            + field.type.slice(1);
          if (fields[type]) {
            FieldComponent = fields[type];
          }
          break;
        case 'function':
          FieldComponent = field.type;
          break;
      }
    }

    return FieldComponent;
  }
  /**
   * Build a field
   * @param {String} name Field name
   * @param {Object} field Field
   * @return {Node} FormGroup - field, help and label
   */
  private makeField(name: string, field: IFieldConfig): JSX.Element | null {
    const { errors } = this.state;
    const error = errors[name] || [];
    const FormGroup = lib.FormGroup;
    const FieldComponent = this.getReactField(field);
    if (FieldComponent === null) {
      return null;
    }
    return <FormGroup
      key={name}
      errors={error}
      FieldComponent={FieldComponent}
      field={field}
      name={name}
      row={this.state.data}
      onBlur={this.handleBlur}
      onChange={(fieldName, value) => this.handleChange(fieldName, value)}
      value={this.state.data[name] || field.value || ''}
      validationState={this.state.state[name]} />;
  }

  /**
   * Convert fields to validate-promise contract
   * @return {Array} validation contract
   */
  private toContract(): any[] {
    return Object.keys(this.fields)
      .filter((name) => this.fields[name].validate !== undefined)
      .map((name) => {
        const field = this.fields[name].validate;
        field.key = name;
        return field;
      });
  }

  /**
   * Fail form submission due to validation errors
   * Update state
   * @param {Object} errors Valdiate-promise errors
   */
  private failFormSubmission(errors) {
    const state = {};
    Object.keys(errors).forEach((name) => state[name] = 'error');
    this.setState({ state, errors });
  }

  /**
   * Is a field visible
   * @param {string} name Field key
   * @return {boolean}
   */
  private isVisible(name: string) {
    return this.state.visibility[name];
  }

  /**
   * Show a field
   * @param {string} name Field key
   */
  private showField(name: string) {
    const visibility = this.state.visibility;
    visibility[name] = true;
    this.setState({ visibility });
  }

  /**
   * Hide a field
   * @param {string} name Field key
   */
  private hideField(name: string) {
    const visibility = this.state.visibility;
    visibility[name] = false;
    this.setState({ visibility });
  }

  /**
   * Reset the form to its initial state and set fields
   * back to pristine
   */
  private reset() {
    const data = { ...this.state.initialState };
    this.setState({
      data,
    });
    Object.keys(this.fields).forEach((key) => {
      this.fields[key].pristine = true;
    });
    this.setState({
      form: this.createFormData(this.state.form, data),
    });
  }

  /**
   * Render
   * @return {Node} Dom node
   */
  public render(): JSX.Element {
    const { errors } = this.props;
    const FormActions = lib.FormActions;
    const buttons = <FormActions
      actions={this.actions}
      form={this}
      onSubmit={(e) => {
        e.preventDefault();
        validate(this.toContract(), this.state.data)
          .then(() => {
            this.onSubmit(e, this.state.data);
            this.reset();
          })
          .catch(this.failFormSubmission.bind(this));
      }
      } />;
    const FormLayout = this.formLayout();

    const madeFields = {};

    Object.keys(this.fields)
      .filter(this.access.bind(this))
      .filter(this.isVisible.bind(this))
      .forEach((name) => {
        const field = this.fields[name];
        const madeField = this.makeField(name, field);
        if (madeField !== null) {
          madeFields[name] = madeField;
        }
      });

    return (<FormLayout
      actions={buttons}
      errors={errors}
      fields={madeFields}
      form={this.state.form}
      onSubmit={this.onSubmit} />);
  }
}

export default UiForm;


text:
require File.expand_path("../../spec_helper", __FILE__)

describe "ProductForm" do
  let(:product) do
    FactoryGirl.build :product
  end
  subject{ProductForm.load(product)}
  before {product.stub(:persisted? => false)}

  it "should delegate persisted?" do
    product.should_receive(:persisted?)
    subject.persisted?
  end

  describe "when loading from a new product" do
    let(:product) do
      FactoryGirl.build :product
    end
    subject{ProductForm.load(product)}
    before{subject.stub(data_model_attribute_names: [:price])}
    its(:name){should be_nil}
    its(:title){should be_nil}
    its(:description){should be_nil}
    its(:valid?){should be_false}
  end

  describe "when loading form with incorrect model type" do
    let(:user) {FactoryGirl.build(:user)}
    it "should raise Exception" do
      expect{ProductForm.load(user)}.to raise_error(FormModel::ModelMisMatchError)
    end
  end

  describe "when loading from a product with given attributes" do
    let(:product) do
      FactoryGirl.build :product, title: "testing title", description: "testing description", price: {cents: 10}
    end
    subject{ProductForm.load(product)}
    before{subject.stub(data_model_attribute_names: [:price])}
    its(:title){should eq("testing title")}
    its(:name){should be_nil}
    its(:description){should eq("testing description")}
    its(:valid?){should be_true}
  end

  describe "validation" do
    let(:product) do
      FactoryGirl.build :product, title: "testing title", description: "testing description"
    end
    subject{ProductForm.load(product)}
    before {subject.stub(data_model_attribute_names: [:price])}

    it "should not be valid as the data model is not valid" do
      product.stub(valid?: false, errors: {price: "not valid"})
      subject.should_not be_valid
    end

    it "should not be valid as price is not valid" do
      product.stub(valid?: true)
      subject.should_not be_valid
    end
  end

  describe "save" do
    let(:product) do
      FactoryGirl.build :product, title: "testing title", description: "testing description", price: {cents: 10}
    end
    subject{ProductForm.load(product)}
    before do
      subject.stub(data_model_attribute_names: [:title])
      product.stub(save: true)
    end

    it "should write_attributes to the model" do
      product.should_receive(:write_attributes)
      subject.save
    end

    it "should save to the model" do
      product.should_receive(:write_attributes)
      subject.save
    end

    it "should check validation" do
      subject.should_receive(:save)
      subject.save
    end
  end

  describe "when mapping a price of 50 GBP to the form model" do
    let(:product) {FactoryGirl.build(:product, price: {"currency" => "GBP", cents: 50})}
    subject{ProductForm.load(product)}
    its(:price){should eq(VMoney.new(currency: "GBP", cents: 50))}
  end

  describe "when setting money via amount" do
    let(:product) {FactoryGirl.build(:product, price: {"currency" => "GBP", cents: 50})}

    before do
      @form = ProductForm.load(product)
      @form.stub(data_model_attribute_names: [:price])
      @form.update(price: {"amount" => "20.0"})
      @form.update_data_model!
    end

    it "should set a price hash on the product" do
      product.price["cents"].should eq(2000)
    end
  end

  describe "when mapping a vmoney price from the form to the model" do
    let(:product) {FactoryGirl.build(:product, price: {"currency" => "GBP", cents: 50})}
    before do
      @form = ProductForm.load(product)
      @form.stub(data_model_attribute_names: [:price])
      @form.price = {"currency"  => "EUR"}
      @form.update_data_model!
    end
    it "should set a price hash on the product" do
      product.price["currency"].should eq("EUR")
    end
  end

  describe "when mapping a start_time with of now" do
    let(:now){Time.now}
    let(:split_time){now.strftime("%R").split(?:)}
    let(:product) {FactoryGirl.build(:product, start_at: now)}
    subject{ProductForm.load(product)}
    its(:start_at_date){ should eq(now.to_date.to_s)}
    its(:start_at_hr) {  should eq(split_time.first)}
    its(:start_at_min) { should eq(split_time.last)}
  end
end


text:
<!DOCTYPE html>

    <link rel="stylesheet" href="test.css">
    <link rel="stylesheet" href="test2.css">

Document Header

Some test Description


text:
import React from 'react'
import PropTypes from 'prop-types'
import {NavigationView, SplitViewCommand} from 'react-uwp'

export default class Navigator extends React.Component {
  static contextTypes = {
    router: PropTypes.object
  }
  constructor () {
    super()
    this.go = this.go.bind(this)
  }
  go (path) {
    const {route} = this.context.router
    const {push} = this.context.router.history
    return function () {
      path !== route.location.pathname && push(path)
    }
  }
  render () {
    const {props, go} = this
    const navigationTopNodes = [
      // <SplitViewCommand label="本周周报" onClick={go('/')} icon={"Home"} />,
      <SplitViewCommand label={'浏览周报'} onClick={go('/list')} icon={'CalendarWeek'} />,
      <SplitViewCommand label={'编辑周报'} onClick={go('/edit')} icon={'Edit'} />
    ]
    const navigationBottomNode = [
      <SplitViewCommand label={'设置'} onClick={go('/settings')} icon={'Settings'} />,
      <SplitViewCommand label={'帮助'} visited onClick={go('/help')} icon={'Help'} />
    ]
    return <NavigationView className='full-size'
      pageTitle='WEEPORT'
      displayMode='overlay'
      autoResize={false}
      initWidth={0}
      navigationTopNodes={navigationTopNodes}
      navigationBottomNodes={navigationBottomNode}
    >
      <div className='content-container'>
        {props.children}
      </div>
    </NavigationView>
  }
}


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

namespace SmashForge
{
    // Taken from SPICA by gdkchan
    // https://github.com/gdkchan/SPICA/blob/f76384f673a7206858fb3c766f891ec9cc9977ee/SPICA/Formats/CtrH3D/H3DPatriciaTree.cs

    public class PatriciaTree
    {
        public class PatriciaTreeNode
        {
            public string Name = "";
            public uint ReferenceBit;
            public ushort LeftNodeIndex = 0;
            public ushort RightNodeIndex = 0;
        }

        private const string DuplicateKeysEx = "Tree shouldn't contain duplicate keys!";

        public static void Insert(List<PatriciaTreeNode> Nodes, PatriciaTreeNode Value, int MaxLength)
        {
            uint Bit = (uint)((MaxLength << 3) - 1);
            PatriciaTreeNode Root = Nodes[0];

            int Index = Traverse(Value.Name, Nodes, out Root);

            while (GetBit(Nodes[Index].Name, Bit) == GetBit(Value.Name, Bit))
            {
                if (--Bit == uint.MaxValue) throw new InvalidOperationException(DuplicateKeysEx);
            }

            Value.ReferenceBit = Bit;

            if (GetBit(Value.Name, Bit))
            {
                Value.LeftNodeIndex = (ushort)Traverse(Value.Name, Nodes, out Root, Bit);
                Value.RightNodeIndex = (ushort)Nodes.Count;
            }
            else
            {
                Value.LeftNodeIndex = (ushort)Nodes.Count;
                Value.RightNodeIndex = (ushort)Traverse(Value.Name, Nodes, out Root, Bit);
            }

            int RootIndex = Nodes.IndexOf(Root);

            if (GetBit(Value.Name, Root.ReferenceBit))
                Root.RightNodeIndex = (ushort)Nodes.Count;
            else
                Root.LeftNodeIndex = (ushort)Nodes.Count;

            Nodes.Add(Value);

            Nodes[RootIndex] = Root;
        }

        public static int Traverse(string Name, List<PatriciaTreeNode> Nodes, out PatriciaTreeNode Root, uint Bit = 0)
        {
            Root = Nodes[0];

            int Output = Root.LeftNodeIndex;

            PatriciaTreeNode Left = Nodes[Output];

            while (Root.ReferenceBit > Left.ReferenceBit && Left.ReferenceBit > Bit)
            {
                if (GetBit(Name, Left.ReferenceBit))
                    Output = Left.RightNodeIndex;
                else
                    Output = Left.LeftNodeIndex;

                Root = Left;
                Left = Nodes[Output];
            }

            return Output;
        }

        private static bool GetBit(string Name, uint Bit)
        {
            int Position = (int)(Bit >> 3);
            int CharBit = (int)(Bit & 7);

            if (Name != null && Position < Name.Length)
                return ((Name[Position] >> CharBit) & 1) != 0;
            else
                return false;
        }
    }
}


text:
Facter.add("physicalcorecount") do
  setcode do
    cores = Facter.value("processorcorecount")
    socks = Facter.value("processorsocketcount")

    if cores and socks
      (cores.to_i * socks.to_i).to_s
    end
  end
end


text:
// ProcessTests.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

// Load DLL and handle reporting when it fails.
#include <windows.h>
#include <WinBase.h>
#include <Strsafe.h>
#include <string.h>
#include <assert.h>     /* assert */

#include <stdio.h>  /* defines FILENAME_MAX */

#include <direct.h>
#define GetCurrentDir _getcwd

#include "Public/FCore.h"

void LoadFlathead();
void UnloadFlathead();

HINSTANCE FHDLL;

using namespace Flathead;

void fnlog(int type, const char *str)
{
	printf("LOG: %s\n", str);
}

int _tmain(int argc, _TCHAR* argv[])
{
	char cCurrentPath[FILENAME_MAX];

	if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath)))
	{
		return errno;
	}

	cCurrentPath[sizeof(cCurrentPath) - 1] = '\0'; /* not really required */

	printf("The current working directory is %s", cCurrentPath);

	FCore* core = new FCore();
	core->SetLoggingFunction(fnlog);
	core->Initialize();

	delete core;

	return 0;
}


text:
class UsersController < ApplicationController
  def create
    @user = User.new(user_params)
    if @user.save
      session[:user_id] = @user.id
      redirect_to "/"
    else
      render :new_user
    end
  end

  def show
    @user = User.find_by(id: params[:id])
    @users_games = @user.games
  end

  def index
    @users = User.search(params[:search])
  end

  private
  def user_params
    params.require(:user).permit(:username, :email, :password)
  end
end


text:
import gql from 'graphql-tag'
import { operationFieldsFragment } from './fragments'

export const createOperationMutation = gql`
  mutation createOperation($operation: OperationInput!) {
    operation: createOperation(operation: $operation) {
      ...operationFields
    }
  }
  ${operationFieldsFragment}
`

export const updateOperationMutation = gql`
  mutation updateOperation($id: ID!, $operation: OperationInput!) {
    operation: updateOperation(id: $id, operation: $operation) {
      ...operationFields
    }
  }
  ${operationFieldsFragment}
`

export const addOperationProductMutation = gql`
  mutation addOperationProduct($id: ID!, $productId: ID!) {
    result: addOperationProduct(id: $id, productId: $productId)
  }
`

export const removeOperationProductMutation = gql`
  mutation removeOperationProduct($id: ID!, $productId: ID!) {
    result: removeOperationProduct(id: $id, productId: $productId)
  }
`


text:
//
//  ArticleCell.h
//  VMovie
//
//  Created by wyz on 16/3/18.
//  Copyright © 2016年 wyz. All rights reserved.
//

#import <UIKit/UIKit.h>

@class Movie;

@interface ArticleCell : UITableViewCell

/**movie */
@property (nonatomic, strong) Movie *movie;

@end


text:
package org.pentaho.runtime.test.i18n;

/**
 * Created by bryan on 8/21/15.
 */
public interface MessageGetterFactory {
  MessageGetter create( Class<?> PKG );
}


text:
bool
expr_tree_walker(C4Node *node, expr_callback fn, void *data)
{
    if (!node)
        return true;

    switch (node->kind)
    {
        case AST_OP_EXPR:
            {
                AstOpExpr *op_expr = (AstOpExpr *) node;

                if (expr_tree_walker(op_expr->lhs, fn, data) == false)
                    return false;

                if (expr_tree_walker(op_expr->rhs, fn, data) == false)
                    return false;
            }
            break;

        case AST_VAR_EXPR:
        case AST_CONST_EXPR:
            break;

        case AST_AGG_EXPR:
            {
                AstAggExpr *agg_expr = (AstAggExpr *) node;

                if (expr_tree_walker(agg_expr->expr, fn, data) == false)
                    return false;
            }
            break;

        case AST_QUALIFIER:
            {
                AstQualifier *ast_qual = (AstQualifier *) node;

                if (expr_tree_walker(ast_qual->expr, fn, data) == false)
                    return false;
            }
            break;

        case AST_TABLE_REF:
            {
                AstTableRef *tbl_ref = (AstTableRef *) node;
                ListCell *lc;

                foreach (lc, tbl_ref->cols)
                {
                    C4Node *col_expr = (C4Node *) lc_ptr(lc);

                    if (expr_tree_walker(col_expr, fn, data) == false)
                        return false;
                }
            }
            break;

        default:
            ERROR("Unrecognized expression node kind: %d",
                  (int) node->kind);
    }

    return fn(node, data);
}

typedef struct VarWalkerContext
{
    var_expr_callback fn;
    void *user_data;
} VarWalkerContext;

static bool
var_walker_callback(C4Node *node, void *data)
{
    VarWalkerContext *cxt = (VarWalkerContext *) data;

    if (node->kind == AST_VAR_EXPR)
        return cxt->fn((AstVarExpr *) node, cxt->user_data);

    return true;
}

bool
expr_tree_var_walker(C4Node *node, var_expr_callback fn, void *data)
{
    VarWalkerContext cxt;

    cxt.fn = fn;
    cxt.user_data = data;

    return expr_tree_walker(node, var_walker_callback, &cxt);
}


text:
package com.github.letsdrink.intellijplugin;

import com.google.common.collect.Iterables;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;

import java.util.List;

public class GoToViewAction extends AnAction {
    @Override
    public void actionPerformed(AnActionEvent anActionEvent) {
        final Editor editor = anActionEvent.getData(PlatformDataKeys.EDITOR);
        PsiFile psiFile = anActionEvent.getData(LangDataKeys.PSI_FILE);
        PsiElement psiElement = PsiUtils.getCurrentElement(editor, psiFile);

        List<PsiFile> viewPsiFiles = OuzoUtils.getViewPsiFiles(psiElement);
        if (!viewPsiFiles.isEmpty()) {
            FileEditorManager editorManager = FileEditorManager.getInstance(editor.getProject());
            editorManager.openFile(Iterables.getFirst(viewPsiFiles, null).getVirtualFile(), true);
        }
    }
}


text:
import subprocess
import os
import time

def makeSha256FromPem(inputFile, passphrase="TESTCHORDDHT"):
    #time.sleep(0.1)
    pipe = subprocess.Popen("openssl pkey -pubout  -passin pass:"+passphrase+"  -inform PEM -outform DER -in "+inputFile+" -out "+inputFile+"temp.der | openssl dgst -sha256 -hex  "+inputFile+"temp.der  | sed 's/^.* //'", shell=True, close_fds=True, stdout=subprocess.PIPE).stdout
    output = pipe.read().rstrip().decode("utf-8")

    #try:
    #    os.remove("temp.der")
    #except:
    #    pass

    if len(output) != 64:
        print("WARNING: OPENSSL OUTPUT IS: ", output)
        # echo the same without regex to get full error message
        pipe = subprocess.Popen("openssl pkey -pubout  -passin pass:"+passphrase+"  -inform PEM -outform DER -in "+inputFile+" -out  "+inputFile+"temp.der | openssl dgst -sha256 -hex  "+inputFile+"temp.der", shell=True, close_fds=True,  stdout=subprocess.PIPE).stdout
        output = pipe.read().rstrip().decode("utf-8")
        print(output)

        return None
    else:
        return  int(str(output), 16)  # convert to int


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/conversation_message_spacing"
    android:gravity="center">

    <ImageView
        android:id="@+id/conversation_message_sender_image_view"
        android:layout_width="@dimen/conversation_message_sender_image_size"
        android:layout_height="@dimen/conversation_message_sender_image_size"
        app:layout_constraintBottom_toBottomOf="@+id/conversation_message_other_linear_layout"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="@+id/conversation_message_other_linear_layout"/>

    <ImageView
        android:id="@+id/conversation_message_other_bubble_triangle_view"
        android:layout_width="10dp"
        android:layout_height="15dp"
        android:layout_marginLeft="@dimen/conversation_message_sender_image_spacing_with_bubble"
        android:layout_marginStart="@dimen/conversation_message_sender_image_spacing_with_bubble"
        android:tint="@color/message_other_background_color"
        app:layout_constraintBottom_toBottomOf="@+id/conversation_message_other_linear_layout"
        app:layout_constraintLeft_toRightOf="@+id/conversation_message_sender_image_view"
        app:layout_constraintTop_toTopOf="@+id/conversation_message_other_linear_layout"
        app:layout_constraintVertical_bias="0.5"
        app:srcCompat="@drawable/conversation_bubble_triangle"/>

    <LinearLayout
        android:id="@+id/conversation_message_other_linear_layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/message_other_background_color"
        android:orientation="vertical"
        android:padding="@dimen/message_inside_spacing"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toRightOf="@+id/conversation_message_other_bubble_triangle_view"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@+id/message_other_sender_name_text_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:maxLines="1"
            android:textColor="@color/message_other_text_color"
            android:textSize="@dimen/conversation_message_sender_name_text_size"
            tools:text="Sender"/>

        <TextView
            android:id="@+id/message_other_text_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/message_other_text_color"
            tools:text="Message from other"/>

    </LinearLayout>

</android.support.constraint.ConstraintLayout>


text:
using System.IO;
using System.Xml;
using Xunit;

namespace System.Data.Tests
{
    public class DataTableReadWriteXmlTest
    {
        public static readonly string EOL = Environment.NewLine;

        private void StandardizeXmlFormat(ref string xml)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            StringWriter sw = new StringWriter();
            doc.Save(sw);
            xml = sw.ToString();
        }

        private void GenerateTestData(out DataSet ds,
                              out DataTable dtMainInDS,
                              out DataTable dtChildInDS,
                              out DataTable dtMain)
        {
            ds = new DataSet("MyDataSet");

            // Create a primary table and populate it with some data.  Make a
            // copy of the primary table and put it into the dataset.
            dtMain = new DataTable("Main");
            dtMain.Columns.Add(new DataColumn("ID", typeof(int)));
            dtMain.Columns.Add(new DataColumn("Data", typeof(string)));

            DataRow row = dtMain.NewRow();
            row["ID"] = 1;
            row["Data"] = "One";
            dtMain.Rows.Add(row);

            row = dtMain.NewRow();
            row["ID"] = 2;
            row["Data"] = "Two";
            dtMain.Rows.Add(row);

            row = dtMain.NewRow();
            row["ID"] = 3;
            row["Data"] = "Three";
            dtMain.Rows.Add(row);

            dtMainInDS = dtMain.Copy();
            ds.Tables.Add(dtMainInDS);

            // Create a child table.  Make a copy of the child table and put
            // it into the dataset.
            dtChildInDS = new DataTable("Child");
            dtChildInDS.Columns.Add(new DataColumn("ID", typeof(int)));
            dtChildInDS.Columns.Add(new DataColumn("PID", typeof(int)));
            dtChildInDS.Columns.Add(new DataColumn("ChildData", typeof(string)));

            row = dtChildInDS.NewRow();
            row["ID"] = 1;
            row["PID"] = 1;
            row["ChildData"] = "Parent1Child1";
            dtChildInDS.Rows.Add(row);

            row = dtChildInDS.NewRow();
            row["ID"] = 2;
            row["PID"] = 1;
            row["ChildData"] = "Parent1Child2";
            dtChildInDS.Rows.Add(row);

            row = dtChildInDS.NewRow();
            row["ID"] = 3;
            row["PID"] = 2;
            row["ChildData"] = "Parent2Child3";
            dtChildInDS.Rows.Add(row);

            ds.Tables.Add(dtChildInDS);

            // Set up the relation in the dataset.
            ds.Relations.Add(new DataRelation("MainToChild",
                                              dtMainInDS.Columns["ID"],
                                              dtChildInDS.Columns["PID"]));
        }

        [Fact]
        public void TestWriteXml()
        {
            DataSet ds;
            DataTable dtMainInDS, dtChildInDS, dtMain;

            GenerateTestData(out ds,
                             out dtMainInDS,
                             out dtChildInDS,
                             out dtMain);

            StringWriter sw = new StringWriter();

            // Get XML for DataSet writes.
            sw.GetStringBuilder().Length = 0;
            ds.WriteXml(sw);
            string xmlDSNone = sw.ToString().Replace("\n", EOL).Replace("\r\r\n", EOL);

            sw.GetStringBuilder().Length = 0;
            ds.WriteXml(sw, XmlWriteMode.DiffGram);
            string xmlDSDiffGram = sw.ToString().Replace("\n", EOL).Replace("\r\r\n", EOL);

            sw.GetStringBuilder().Length = 0;
            ds.WriteXml(sw, XmlWriteMode.WriteSchema);
            string xmlDSWriteSchema = sw.ToString();

            // Get XML for recursive DataTable writes of the same data as in
            // the DataSet.
            sw.GetStringBuilder().Length = 0;
            dtMainInDS.WriteXml(sw, true);
            string xmlDTNone = sw.ToString();

            sw.GetStringBuilder().Length = 0;
            dtMainInDS.WriteXml(sw, XmlWriteMode.DiffGram, true);
            string xmlDTDiffGram = sw.ToString();

            sw.GetStringBuilder().Length = 0;
            dtMainInDS.WriteXml(sw, XmlWriteMode.WriteSchema, true);
            string xmlDTWriteSchema = sw.ToString();

            // The schema XML written by the DataTable call has an extra element
            // in the element for the dataset schema definition.  We remove that
            // extra attribute and then check to see if the rest of the xml is
            // identical.
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xmlDTWriteSchema);
            XmlNode node = doc.DocumentElement.FirstChild.FirstChild;
            XmlAttribute a = (XmlAttribute)node.Attributes.GetNamedItem("msdata:MainDataTable");
            Assert.NotNull(a);
            Assert.Equal("Main", a.Value);

            node.Attributes.Remove(a);
            sw.GetStringBuilder().Length = 0;
            doc.Save(sw);
            xmlDTWriteSchema = sw.ToString();

            StandardizeXmlFormat(ref xmlDSWriteSchema);

            Assert.Equal(xmlDSNone, xmlDTNone);
            Assert.Equal(xmlDSDiffGram, xmlDTDiffGram);
            Assert.True(xmlDSWriteSchema.IndexOf("UseCurrentLocale") > 0);
            Assert.Equal(xmlDSWriteSchema, xmlDTWriteSchema);

            // Now that we've tested writing tables (including children),
            // we will go on to test the cases where the hierarchy flag
            // is false.  For this, we will test one table inside the
            // dataset and one table outside the dataset.

            // First, we fix our test DataSet to only have a single table
            // with no relations.  Then, we go about comparing the XML.
            // Get XML for DataSet writes.
            ds.Tables[1].Constraints.Remove(ds.Tables[1].Constraints[0]);
            ds.Tables[0].Constraints.Remove(ds.Tables[0].Constraints[0]);
            ds.Tables[0].ChildRelations.Remove("MainToChild");
            ds.Tables.Remove("Child");

            sw.GetStringBuilder().Length = 0;
            ds.WriteXml(sw);
            xmlDSNone = sw.ToString().Replace("\n", EOL).Replace("\r\r\n", EOL);

            sw.GetStringBuilder().Length = 0;
            ds.WriteXml(sw, XmlWriteMode.DiffGram);
            xmlDSDiffGram = sw.ToString().Replace("\n", EOL).Replace("\r\r\n", EOL);

            sw.GetStringBuilder().Length = 0;
            ds.WriteXml(sw, XmlWriteMode.WriteSchema);
            xmlDSWriteSchema = sw.ToString();

            // Get all the DataTable.WriteXml results.
            sw.GetStringBuilder().Length = 0;
            dtMainInDS.WriteXml(sw);
            string xmlDTNoneInDS = sw.ToString();

            sw.GetStringBuilder().Length = 0;
            dtMainInDS.WriteXml(sw, XmlWriteMode.DiffGram);
            string xmlDTDiffGramInDS = sw.ToString();

            sw.GetStringBuilder().Length = 0;
            dtMainInDS.WriteXml(sw, XmlWriteMode.WriteSchema);
            string xmlDTWriteSchemaInDS = sw.ToString();

            sw.GetStringBuilder().Length = 0;
            dtMain.WriteXml(sw);
            string xmlDTNoneNoDS = sw.ToString();

            sw.GetStringBuilder().Length = 0;
            dtMain.WriteXml(sw, XmlWriteMode.DiffGram);
            string xmlDTDiffGramNoDS = sw.ToString();

            sw.GetStringBuilder().Length = 0;
            dtMain.WriteXml(sw, XmlWriteMode.WriteSchema);
            string xmlDTWriteSchemaNoDS = sw.ToString();

            Assert.Equal(xmlDSNone, xmlDTNoneInDS);

            // The only difference between the xml output from inside the
            // dataset and the xml output from outside the dataset is that
            // there's a fake <DocumentElement> tag surrounding tbe table
            // in the second case.  We replace it with the name of the
            // dataset for testing purposes.
            doc.LoadXml(xmlDTNoneNoDS);
            Assert.Equal("DocumentElement", doc.DocumentElement.Name);
            sw.GetStringBuilder().Length = 0;
            doc.Save(sw);
            xmlDTNoneNoDS = sw.ToString();
            xmlDTNoneNoDS = xmlDTNoneNoDS.Replace("<DocumentElement>", "<MyDataSet>");
            xmlDTNoneNoDS = xmlDTNoneNoDS.Replace("</DocumentElement>", "</MyDataSet>");

            StandardizeXmlFormat(ref xmlDSNone);

            Assert.Equal(xmlDSNone, xmlDTNoneNoDS);

            // Now check the DiffGram.
            Assert.Equal(xmlDSDiffGram, xmlDTDiffGramInDS);

            doc.LoadXml(xmlDTDiffGramNoDS);
            Assert.Equal("DocumentElement", doc.DocumentElement.FirstChild.Name);
            xmlDTDiffGramNoDS = xmlDTDiffGramNoDS.Replace("<DocumentElement>", "<MyDataSet>");
            xmlDTDiffGramNoDS = xmlDTDiffGramNoDS.Replace("</DocumentElement>", "</MyDataSet>");

            Assert.Equal(xmlDSDiffGram, xmlDTDiffGramNoDS);

            // Finally we check the WriteSchema version of the data.  First
            // we remove the extra "msdata:MainDataTable" attribute from
            // the schema declaration part of the DataTable xml.
            doc = new XmlDocument();
            doc.LoadXml(xmlDTWriteSchemaInDS);
            node = doc.DocumentElement.FirstChild.FirstChild;
            a = (XmlAttribute)node.Attributes.GetNamedItem("msdata:MainDataTable");
            Assert.NotNull(a);
            Assert.Equal("Main", a.Value);
            node.Attributes.Remove(a);
            sw.GetStringBuilder().Length = 0;
            doc.Save(sw);
            xmlDTWriteSchemaInDS = sw.ToString();

            StandardizeXmlFormat(ref xmlDSWriteSchema);

            Assert.Equal(xmlDSWriteSchema, xmlDTWriteSchemaInDS);

            // Remove the extra "msdata:MainDataTable" for the other test case.
            // Also make sure we have "NewDataSet" in the appropriate locations.
            doc = new XmlDocument();
            doc.LoadXml(xmlDTWriteSchemaNoDS);
            node = doc.DocumentElement.FirstChild.FirstChild;
            a = (XmlAttribute)node.Attributes.GetNamedItem("msdata:MainDataTable");
            Assert.NotNull(a);
            Assert.Equal("Main", a.Value);
            node.Attributes.Remove(a);
            sw.GetStringBuilder().Length = 0;
            doc.Save(sw);

            Assert.Equal("NewDataSet", doc.DocumentElement.Name);
            Assert.Equal("NewDataSet", doc.DocumentElement.FirstChild.Attributes["id"].Value);
            Assert.Equal("NewDataSet", doc.DocumentElement.FirstChild.FirstChild.Attributes["name"].Value);

            xmlDTWriteSchemaNoDS = sw.ToString();

            xmlDTWriteSchemaNoDS = xmlDTWriteSchemaNoDS.Replace("<NewDataSet>", "<MyDataSet>");
            xmlDTWriteSchemaNoDS = xmlDTWriteSchemaNoDS.Replace("</NewDataSet>", "</MyDataSet>");
            xmlDTWriteSchemaNoDS = xmlDTWriteSchemaNoDS.Replace("\"NewDataSet\"", "\"MyDataSet\"");

            Assert.Equal(xmlDSWriteSchema, xmlDTWriteSchemaNoDS);
        }

        [Fact]
        public void TestReadXml()
        {
            // For reading, DataTable.ReadXml only supports reading in xml with
            // the schema included.  This means that we can only read in XML
            // that was generated with the WriteSchema flag.
            DataSet ds;
            DataTable dtMainInDS, dtChildInDS, dtMain;

            GenerateTestData(out ds,
                             out dtMainInDS,
                             out dtChildInDS,
                             out dtMain);

            StringWriter sw = new StringWriter();

            // Get XML for recursive DataTable writes of the same data as in
            // the DataSet.
            sw.GetStringBuilder().Length = 0;
            dtMainInDS.WriteXml(sw, true);
            string xmlDTNone = sw.ToString();

            sw.GetStringBuilder().Length = 0;
            dtMainInDS.WriteXml(sw, XmlWriteMode.DiffGram, true);
            string xmlDTDiffGram = sw.ToString();

            sw.GetStringBuilder().Length = 0;
            dtMainInDS.WriteXml(sw, XmlWriteMode.WriteSchema, true);
            string xmlMultiTable = sw.ToString();

            sw.GetStringBuilder().Length = 0;
            dtMain.WriteXml(sw, XmlWriteMode.WriteSchema);
            string xmlSingleTable = sw.ToString();

            DataTable newdt = new DataTable();

            // DataTable does not support schema inference from Xml.
            Assert.Throws<InvalidOperationException>(() => newdt.ReadXml(new StringReader(xmlDTNone)));

            // DataTable does not support schema inference from Xml.
            Assert.Throws<InvalidOperationException>(() => newdt.ReadXml(new StringReader(xmlDTDiffGram)));

            DataTable multiTable = new DataTable();
            multiTable.ReadXml(new StringReader(xmlMultiTable));
            // Do some simple checks to see if the main dataset was created
            // and if there are relationships present.
            Assert.Equal("MyDataSet", multiTable.DataSet.DataSetName);
            Assert.Equal(1, multiTable.ChildRelations.Count);
            Assert.Equal(1, multiTable.Constraints.Count);
            // Write the table back out and check to see that the XML is
            // the same as before.
            sw.GetStringBuilder().Length = 0;
            multiTable.WriteXml(sw, XmlWriteMode.WriteSchema, true);
            string xmlMultiTableCheck = sw.ToString();
            Assert.True(xmlMultiTable.IndexOf("UseCurrentLocale") > 0);
            Assert.True(xmlMultiTable.IndexOf("keyref") > 0);
            Assert.Equal(xmlMultiTable, xmlMultiTableCheck);

            DataTable singleTable = new DataTable();
            singleTable.ReadXml(new StringReader(xmlSingleTable));
            // Do some simple checks on the table.
            Assert.Null(singleTable.DataSet);
            Assert.Equal("Main", singleTable.TableName);
            // Write the table out and check if it's the same.
            sw.GetStringBuilder().Length = 0;
            singleTable.WriteXml(sw, XmlWriteMode.WriteSchema);
            string xmlSingleTableCheck = sw.ToString();
            Assert.Equal(xmlSingleTable, xmlSingleTableCheck);
        }
    }
}


text:
using MasterDevs.ChromeDevTools;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace MasterDevs.ChromeDevTools.Protocol.iOS.Page
{
	/// <summary>
	/// Returns present frame / resource tree structure.
	/// </summary>
	[CommandResponse(ProtocolName.Page.GetResourceTree)]
	[SupportedBy("iOS")]
	public class GetResourceTreeCommandResponse
	{
		/// <summary>
		/// Gets or sets Present frame / resource tree structure.
		/// </summary>
		public FrameResourceTree FrameTree { get; set; }
	}
}


text:
<?php
// Heading
$_['heading_title']    = 'Backup & Restauração';

// Text
$_['text_backup']      = 'Download do backup';
$_['text_success']     = 'Você importou com êxito o seu banco de dados!';
$_['text_list']        = 'Listando uploads';

// Entry
$_['entry_restore']    = 'Restaurar backup';
$_['entry_backup']     = 'Backup';

// Error
$_['error_permission'] = 'Atenção: Você não tem permissão para modificar os backups!';
$_['error_backup']     = 'Atenção: Você deve selecionar pelo menos uma tabela para fazer backup!';
$_['error_empty']      = 'Atenção: O arquivo que você enviou estava vazio!';


text:
function f() => 4;

//// [parserErrantEqualsGreaterThanAfterFunction1.js]
function f() { }
4;


text:
/*
 * This software is distributed under BSD 3-clause license (see LICENSE file).
 *
 * Authors: Sergey Lisitsyn, Yuyu Zhang, Bjoern Esser
 */

#ifndef TASKRELATION_H_
#define TASKRELATION_H_
#define IGNORE_IN_CLASSLIST

#include <shogun/lib/config.h>

#include <shogun/base/SGObject.h>

namespace shogun
{

#ifndef DOXYGEN_SHOULD_SKIP_THIS
IGNORE_IN_CLASSLIST enum ETaskRelationType
{
	TASK_TREE,
	TASK_GROUP
};
#endif

/** @brief used to represent tasks in multitask learning
 */
class TaskRelation : public SGObject
{
public:

	/** default constructor */
	TaskRelation()
	{
	}

	/** destructor */
	~TaskRelation() override
	{
	}

	/** get name
	 *
	 * @return name of the object
	 */
	const char* get_name() const override { return "TaskRelation"; };

	/** get relation type (not implemented)
	 *
	 * @return type of relation
	 */
	virtual ETaskRelationType get_relation_type() const = 0;

	/** get tasks indices (not implemented)
	 *
	 * @return array of vectors containing indices of each task
	 */
	virtual SGVector<index_t>* get_tasks_indices() const = 0;

	/** get number of tasks in the group (not implemented)
	 *
	 * @return number of tasks in the group
	 */
	virtual int32_t get_num_tasks() const = 0;
};

}
#endif


text:
package net.stickycode.configuration.source;

import net.stickycode.configuration.ConfigurationKey;
import net.stickycode.configuration.ConfigurationSource;
import net.stickycode.configuration.ResolvedConfiguration;
import net.stickycode.configuration.value.SystemValue;
import net.stickycode.stereotype.StickyPlugin;

@StickyPlugin
public class SystemPropertiesConfigurationSource
    implements ConfigurationSource {

  @Override
  public String toString() {
    return getClass().getSimpleName();
  }

  @Override
  public void apply(ConfigurationKey key, ResolvedConfiguration values) {
    for (String k : key.join(".")) {
      String value = System.getProperty(k);
      if (value != null)
        values.add(new SystemValue(value));
    }
  }

}


text:
<?php
/**
 * @Author: Marte
 * @Date:   2017-03-21 14:37:19
 * @Last Modified by:   Marte
 * @Last Modified time: 2017-03-21 14:39:21
 */
namespace app\index\model;
use think\Model;
class Shop_books extends Model
{
    protected $autoWriteTimestamp = true;
}


text:
FROM node:latest

RUN npm install -g gulp

ENTRYPOINT ["gulp"]


text:
class PollsController < ApplicationController

  before_filter :find_all_polls
  before_filter :find_page

  def index
    present(@page)
  end

  def show
    @poll = Poll.find(params[:id])
    present(@page)
  end

  def submit
    @poll = Poll.find(params[:id])
    poll_answer_id = params[:poll_answer_id]
    if poll_answer_id.nil?
      flash[:notice] = "No answer selected"
    else
      poll_answer = PollAnswer.find(poll_answer_id)
      poll_answer.vote += 1
      poll_answer.save
      UsersPoll.create(:user_identifier => request.ip, :poll_answer_id => poll_answer_id, :poll_id => params[:id])
      session[:recent_poll_id] = @poll.id
    end
    redirect_to :back
  end

  protected

  def find_all_polls
    @polls = Poll.find(:all, :order => "position ASC")
  end

  def find_page
    @page = Page.find_by_link_url("/polls")
  end

end