text:
require 'test/helper'

class Nanoc3::CodeSnippetTest < MiniTest::Unit::TestCase

  include Nanoc3::TestHelpers

  def test_load
    # Initialize
    $complete_insane_parrot = 'meow'

    # Create code and load it
    code_snippet = Nanoc3::CodeSnippet.new("$complete_insane_parrot = 'woof'", 'parrot.rb')
    code_snippet.load

    # Ensure code is loaded
    assert_equal('woof', $complete_insane_parrot)
  end

  def test_load_with_toplevel_binding
    # Initialize
    @foo = 'meow'

    # Create code and load it
    code_snippet = Nanoc3::CodeSnippet.new("@foo = 'woof'", 'dog.rb')
    code_snippet.load

    # Ensure binding is correct
    assert_equal('meow', @foo)
  end

end


text:
public class InfoBean {
	private String tId;//2939
	private String type;//"xit ent"
	private int xitTime;//11494456
	private int entTime;//11494489
	private int result;
	private String key;
	private String clsName;//PartInquiryListAdapter
	private String methodName;//PartInquiryListAdapter$1.onClick (Landroid/view/View;)V
	private String fullClassName;//trading.adapter.part.purchase.PartInquiryListAdapter

	public String getFullClassName() {
		return fullClassName;
	}
	public void setFullClassName(String fullClassName) {
		this.fullClassName = fullClassName;
	}
	public String getClsName() {
		return clsName;
	}
	public void setClsName(String clsName) {
		this.clsName = clsName;
	}
	public String getMethodName() {
		return methodName;
	}
	public void setMethodName(String methodName) {
		this.methodName = methodName;
	}
	public String getKey() {
		return key;
	}
	public void setKey(String key) {
		this.key = key;
	}
	public String gettId() {
		return tId;
	}
	public void settId(String tId) {
		this.tId = tId;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public int getXitTime() {
		return xitTime;
	}
	public void setXitTime(int xitTime) {
		this.xitTime = xitTime;
	}
	public int getEntTime() {
		return entTime;
	}
	public void setEntTime(int entTime) {
		this.entTime = entTime;
	}
	public int getResult() {
		return result;
	}
	public void setResult(int result) {
		this.result = result;
	}

}

redpajama_set_name: RedPajamaGithub


text:
<?php
include "../../koneksi.php";
$createdDate = date('Y-m-d H:i:s');
	mysql_query("INSERT INTO tstatus(	NamaStatus,
										CreatedDate,
										CreatedUser)
								VALUES(	'$_POST[nama_status]',
										'$createdDate',
										'$_SESSION[IdUser]')");

	header('location:tampilstatus.php');
?>


text:
= lex

A simple utility class for creating lexers with only a couple of lines
of code.

== Usage

Add the gem to your Gemfile or `gem install lex`

Create a new `Lex` instance and pass a list of arguments describing
tokens:

```ruby
lex = Lex.new(
  [:NUMBER, /\A([0-9]+)/],
  [:OPERATOR, /\A(\+|\*|-|\/)/],
  [:ignore, /\A( )/],
)
```

That will create a lexer that matches 3 different types of tokens,
namely numbers, operators and whitespace. If a token matcher has
`:ignore` as it's identifier, tokens matched with that regex will be
ignored in the final output.

==== Tokenizing

Let's run the lexer on a simple program

```ruby
lex.tokenize("5 + 3 *     2")
# the output will be
# [
#   [:NUMBER,"5"],
#   [:OPERATOR,"+"],
#   [:NUMBER,"3"],
#   [:OPERATOR,"*"],
#   [:NUMBER,"2"],
# ]
```

== Contributing to lex

* Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet.
* Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it.
* Fork the project.
* Start a feature/bugfix branch.
* Commit and push until you are happy with your contribution.
* Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
* Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.

== Copyright

Copyright (c) 2015 fhur. See LICENSE.txt for
further details.


text:
A minimum vertex cover is a vertex cover having the smallest possible number of vertices for a given graph.
http://en.wikipedia.org/wiki/Vertex_cover

## Input
n
a b  (n - 1 times)
...

n - number of vertices
a b - edge between "a" and "b"

## Sample input
3
1 2
1 3

## Output

This algorithm returns minimum number of vertices.


text:
FactoryGirl.define do
  factory :profile do
    user_id 1
    phone_number 'MyString'
    resume_url 'MyString'
    insurance_id 1
  end
end


text:
layout: piece
title: 2,640 Ounces
author: Taj Bourgeois
date: 2015-08-01 12:00:00
category: september2015
---


text:
import argparse
import logging
import os
import time
import numpy as np
import mxnet as mx
from mxnet import nd
from mxnet.contrib.quantization import *
from mxnet.contrib import amp

def download_dataset(dataset_url, dataset_dir, logger=None):
    if logger is not None:
        logger.info('Downloading dataset for inference from %s to %s' % (dataset_url, dataset_dir))
    mx.test_utils.download(dataset_url, dataset_dir)

def load_model(symbol_file, param_file, logger=None):
    cur_path = os.path.dirname(os.path.realpath(__file__))
    symbol_file_path = os.path.join(cur_path, symbol_file)
    if logger is not None:
        logger.info('Loading symbol from file %s' % symbol_file_path)
    symbol = mx.sym.load(symbol_file_path)

    param_file_path = os.path.join(cur_path, param_file)
    if logger is not None:
        logger.info('Loading params from file %s' % param_file_path)
    save_dict = nd.load(param_file_path)
    arg_params = {}
    aux_params = {}
    for k, v in save_dict.items():
        tp, name = k.split(':', 1)
        if tp == 'arg':
            arg_params[name] = v
        if tp == 'aux':
            aux_params[name] = v
    return symbol, arg_params, aux_params

def advance_data_iter(data_iter, n):
    assert n >= 0
    if n == 0:
        return data_iter
    has_next_batch = True
    while has_next_batch:
        try:
            data_iter.next()
            n -= 1
            if n == 0:
                return data_iter
        except StopIteration:
            has_next_batch = False

def score(sym, arg_params, aux_params, data, devs, label_name, max_num_examples, logger=None):
    metrics = [mx.metric.create('acc'),
               mx.metric.create('top_k_accuracy', top_k=5)]
    if not isinstance(metrics, list):
        metrics = [metrics, ]
    mod = mx.mod.Module(symbol=sym, context=devs, label_names=[label_name, ])
    mod.bind(for_training=False,
             data_shapes=data.provide_data,
             label_shapes=data.provide_label)
    mod.set_params(arg_params, aux_params)

    tic = time.time()
    num = 0
    for batch in data:
        mod.forward(batch, is_train=False)
        for m in metrics:
            mod.update_metric(m, batch.label)
        num += batch_size
        if max_num_examples is not None and num >= max_num_examples:
            break

    speed = num / (time.time() - tic)

    if logger is not None:
        logger.info('Finished inference with %d images' % num)
        logger.info('Finished with %f images per second', speed)
        logger.warn('Note: GPU performance is expected to be slower than CPU. Please refer quantization/README.md for details')
        for m in metrics:
            logger.info(m.get())

def low_precison_convert(model_name, low_precision, sym, arg_params, aux_params, excluded_sym_names=[]):
    if low_precision == 'bfloat16':
        if model_name.find('imagenet1k-resnet-152') != -1:
            excluded_sym_names += ['conv0']
        elif model_name.find('imagenet1k-inception-bn') != -1:
            excluded_sym_names += ['conv_1']
        elif model_name.find('resnet') != -1 and model_name.find('v1') != -1:
            excluded_sym_names += ['resnetv10_conv0_fwd']
        elif model_name.find('resnet') != -1 and model_name.find('v2') != -1:
            excluded_sym_names += ['resnetv20_conv0_fwd']
        elif model_name.find('vgg') != -1:
            excluded_sym_names += ['vgg0_conv0_fwd']
        elif model_name.find('squeezenet1') != -1:
            excluded_sym_names += ['squeezenet0_conv0_fwd']
        elif model_name.find('mobilenet') != -1 and model_name.find('v2') == -1:
            excluded_sym_names += ['mobilenet0_conv0_fwd']
        elif model_name.find('mobilenet') != -1 and model_name.find('v2') != -1:
            excluded_sym_names += ['mobilenetv20_conv0_fwd']
        elif model_name.find('inceptionv3') != -1:
            excluded_sym_names += ['inception30_conv0_fwd']
    return amp.convert_model(sym,
                             arg_params,
                             aux_params,
                             target_dtype=low_precision,
                             excluded_sym_names=excluded_sym_names,
                             cast_optional_params=True)

def benchmark_score(symbol_file, ctx, batch_size, num_batches, data_layer_type, low_precision, logger=None):
    # get mod
    cur_path = os.path.dirname(os.path.realpath(__file__))
    symbol_file_path = os.path.join(cur_path, symbol_file)
    if logger is not None:
        logger.info('Loading symbol from file %s' % symbol_file_path)
    sym = mx.sym.load(symbol_file_path)
    mod = mx.mod.Module(symbol=sym, context=ctx)
    if data_layer_type == "int8":
        dshape = mx.io.DataDesc(name='data', shape=(
            batch_size,) + data_shape, dtype=np.int8)
    elif data_layer_type == 'uint8':
        dshape = mx.io.DataDesc(name='data', shape=(
            batch_size,) + data_shape, dtype=np.uint8)
    else:  # float32
        dshape = mx.io.DataDesc(name='data', shape=(
            batch_size,) + data_shape, dtype=np.float32)
    mod.bind(for_training=False,
             inputs_need_grad=False,
             data_shapes=[dshape])
    mod.init_params(initializer=mx.init.Xavier(magnitude=2.))

    if low_precision:
        arg_params, aux_params = mod.get_params()
        sym, arg_params, aux_params = low_precison_convert(symbol_file,
                                                           low_precision,
                                                           sym, arg_params,
                                                           aux_params)
        mod = mx.mod.Module(symbol=sym, context=ctx)
        mod.bind(for_training=False,
                 inputs_need_grad=False,
                 data_shapes=[dshape],
                 label_shapes=[['softmax_label', (batch_size,)]])
        mod.set_params(arg_params, aux_params)

    # get data
    if data_layer_type == "float32":
        data = [mx.random.uniform(-1.0, 1.0, shape=shape, ctx=ctx, dtype=data_layer_type)
                for _, shape in mod.data_shapes]
    else:
        data = [mx.nd.full(shape=shape, val=127, ctx=ctx, dtype=data_layer_type)
                for _, shape in mod.data_shapes]
    batch = mx.io.DataBatch(data, [])  # empty label

    # run
    dry_run = 5                 # use 5 iterations to warm up
    for i in range(dry_run+num_batches):
        if i == dry_run:
            tic = time.time()
        mod.forward(batch, is_train=False)
        for output in mod.get_outputs():
            output.wait_to_read()

    # return num images per second
    return num_batches*batch_size/(time.time() - tic)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Score a model on a dataset')
    parser.add_argument('--ctx', type=str, default='gpu')
    parser.add_argument('--benchmark', type=bool, default=False, help='dummy data benchmark')
    parser.add_argument('--symbol-file', type=str, required=True, help='symbol file path')
    parser.add_argument('--param-file', type=str, required=False, help='param file path')
    parser.add_argument('--batch-size', type=int, default=32)
    parser.add_argument('--label-name', type=str, default='softmax_label')
    parser.add_argument('--dataset', type=str, required=False, help='dataset path')
    parser.add_argument('--rgb-mean', type=str, default='0,0,0')
    parser.add_argument('--rgb-std', type=str, default='1,1,1')
    parser.add_argument('--image-shape', type=str, default='3,224,224')
    parser.add_argument('--data-nthreads', type=int, default=60, help='number of threads for data decoding')
    parser.add_argument('--num-skipped-batches', type=int, default=0, help='skip the number of batches for inference')
    parser.add_argument('--num-inference-batches', type=int, required=True, help='number of images used for inference')
    parser.add_argument('--shuffle-dataset', action='store_true', default=True,
                        help='shuffle the calibration dataset')
    parser.add_argument('--shuffle-chunk-seed', type=int, default=3982304,
                        help='shuffling chunk seed, see'
                             ' https://mxnet.apache.org/api/python/io/io.html?highlight=imager#mxnet.io.ImageRecordIter'
                             ' for more details')
    parser.add_argument('--shuffle-seed', type=int, default=48564309,
                        help='shuffling seed, see'
                             ' https://mxnet.apache.org/api/python/io/io.html?highlight=imager#mxnet.io.ImageRecordIter'
                             ' for more details')
    parser.add_argument('--data-layer-type', type=str, default='float32',
                        choices=['float32', 'int8', 'uint8'],
                        help='data type for data layer')
    parser.add_argument('--low-precision', type=str, default='',
                        choices=['', 'float16', 'bfloat16'],
                        help='enable low precision')

    args = parser.parse_args()

    if args.ctx == 'gpu':
        ctx = mx.gpu(0)
    elif args.ctx == 'cpu':
        ctx = mx.cpu(0)
    else:
        raise ValueError('ctx %s is not supported in this script' % args.ctx)

    logging.basicConfig()
    logger = logging.getLogger('logger')
    logger.setLevel(logging.INFO)

    symbol_file = args.symbol_file
    param_file = args.param_file
    data_nthreads = args.data_nthreads

    batch_size = args.batch_size
    logger.info('batch size = %d for inference' % batch_size)

    rgb_mean = args.rgb_mean
    logger.info('rgb_mean = %s' % rgb_mean)
    rgb_mean = [float(i) for i in rgb_mean.split(',')]
    mean_args = {'mean_r': rgb_mean[0], 'mean_g': rgb_mean[1], 'mean_b': rgb_mean[2]}
    rgb_std = args.rgb_std
    logger.info('rgb_std = %s' % rgb_std)
    rgb_std = [float(i) for i in rgb_std.split(',')]
    std_args = {'std_r': rgb_std[0], 'std_g': rgb_std[1], 'std_b': rgb_std[2]}
    combine_mean_std = {}
    combine_mean_std.update(mean_args)
    combine_mean_std.update(std_args)

    label_name = args.label_name
    logger.info('label_name = %s' % label_name)

    image_shape = args.image_shape
    data_shape = tuple([int(i) for i in image_shape.split(',')])
    logger.info('Input data shape = %s' % str(data_shape))

    data_layer_type = args.data_layer_type

    if args.low_precision:
        if args.ctx == 'gpu':
            assert args.low_precision == 'float16', "Not supported low-precision options for GPU."
        elif args.ctx == 'cpu':
            assert args.low_precision == 'bfloat16', "Not supported low-precision options for CPU."

    if args.benchmark == False:
        dataset = args.dataset
        download_dataset('http://data.mxnet.io/data/val_256_q90.rec', dataset)
        logger.info('Dataset for inference: %s' % dataset)

        # creating data iterator
        data = mx.io.ImageRecordIter(
            path_imgrec=dataset,
            label_width=1,
            preprocess_threads=data_nthreads,
            batch_size=batch_size,
            data_shape=data_shape,
            label_name=label_name,
            rand_crop=False,
            rand_mirror=False,
            shuffle=args.shuffle_dataset,
            shuffle_chunk_seed=args.shuffle_chunk_seed,
            seed=args.shuffle_seed,
            dtype=data_layer_type,
            ctx=args.ctx,
            **combine_mean_std)

        # loading model
        sym, arg_params, aux_params = load_model(symbol_file, param_file, logger)

        if args.low_precision:
            sym, arg_params, aux_params = low_precison_convert(symbol_file,
                                                               args.low_precision,
                                                               sym, arg_params,
                                                               aux_params)
        # make sure that fp32 inference works on the same images as calibrated quantized model
        logger.info('Skipping the first %d batches' % args.num_skipped_batches)
        data = advance_data_iter(data, args.num_skipped_batches)

        num_inference_images = args.num_inference_batches * batch_size
        logger.info('Running model %s for inference' % symbol_file)
        score(sym, arg_params, aux_params, data, [ctx], label_name,
            max_num_examples=num_inference_images, logger=logger)
    else:
        logger.info('Running model %s for inference' % symbol_file)
        speed = benchmark_score(symbol_file, ctx, batch_size,
                                args.num_inference_batches, data_layer_type, args.low_precision, logger)
        logger.info('batch size %2d, image/sec: %f', batch_size, speed)


text:
package com.bueno.component.produto.service;

import java.util.List;

import com.bueno.component.pedido.model.Item;
import com.bueno.component.produto.model.Produto;

public interface ProdutoRepository {

	public List<Produto> getProdutosByItemsList(List<Item> itens) throws Exception;
	public Produto getProdutoByItem(Item item) throws Exception;

}


text:
using System;

namespace CSSLayout
{
	public enum CSSWrap
	{
		NOWRAP,
		WRAP,
	}
}


text:
import scala.reflect.runtime.universe._
import scala.reflect.runtime.{currentMirror => cm}
import scala.tools.reflect._

object Test extends App {
  val tb = cm.mkToolBox()
  val t1 = tb.parse("1 to 3 map (_+1)")
  println(tb.eval(t1))
  println(tb.eval(t1))
  println(tb.eval(t1))
}


text: Display full crash messages in ``short test summary info``, when runng in a CI environment.


text:
require 'echowrap/api/utils'

module Echowrap
  module API
    module Track
      include Echowrap::API::Utils

      # Get info about tracks given an id or md5. The md5 parameter is the file md5.
      #
      # @see http://developer.echonest.com/docs/v4/track.html
      # @authentication Requires api key
      # @raise [Echowrap::Error::Unauthorized] Error raised when supplied api key is not valid.      # @raise [Echowrap::Error::Unauthorized] Error raised when supplied user credentials are not valid.
      # @return [Echowrap::Track] The track.
      # @param options [Hash] A customizable set of options.
      # @option options [String] :id The ID of the track.  Required if md5 is not provided.  Example: 'TRTLKZV12E5AC92E11'.
      # @option options [String] :md5 The MD5 of the track. Required if ID is not provided.  Example: '881f4e47e88e8b570e34a3b49c8262ac'.
      # @option options [String] :bucket The type of track data that should be returned. Example: audio_summary.
      # @example Profile via id
      #   Echowrap.track_profile(:id => "TRTLKZV12E5AC92E11")
      def track_profile(options={})
        options.merge(:bucket => 'audio_summary') if options[:bucket].nil?
        object_from_response(Echowrap::Track, :get, '/api/v4/track/profile', :track, options)
      end

      # Upload a track to The Echo Nest's analyzer for analysis. The track will be analyzed. This method takes either a url parameter, or a local audio file, which should be the contents of the request body.
      #
      # @see http://developer.echonest.com/docs/v4/track.html
      # @authentication Requires api key
      # @raise [Echowrap::Error::Unauthorized] Error raised when supplied api key is not valid.
      # @raise [Echowrap::Error::Unauthorized] Error raised when supplied user credentials are not valid.
      # @return [Echowrap::Track] The track.
      # @param options [Hash] A customizable set of options.
      # @option options [String] :url A url to an audio file. Cannot be combined with uploading local audio file.  Example: http://example.com/audio.mp3.
      # @option options [File] :track The track data. Cannot be
      # combined with url option
      # @option options [String] :filetype The type of audio file to be analyzed. Optional if uploading a local file, will be determined from file if not explicitly passed. Must be one of ['wav', 'mp3', 'au', 'ogg', 'm4a', 'mp4'].
      # @example Upload
      #   Echowrap.track_upload(:url => "http://example.com/audio.mp3")
      #   Echowrap.track_upload(:track => File.new('audio.mp3'))
      def track_upload(options={})
        options.merge(filetype: File.extname(options[:track]).gsub('.', '')) if options[:track] && options[:filetype].nil?
        object_from_response(Echowrap::Track, :post, '/api/v4/track/upload', :track, options)
      end

      # Get analysis info on tracks given an analysis_url. This method is not explicitly described by the Echowrap API and is provided as a helper.
      #
      # @see http://developer.echonest.com/docs/v4/track.html
      # @authentication Requires analysis url
      # @raise [Echowrap::Error::Unauthorized] Error raised when supplied analysis url is not valid.
      # @raise [Echowrap::Error::Unauthorized] Error raised when supplied analysis url is expired.
      # @return [Echowrap::Track] The track.
      # @param options [Hash] A customizable set of options.
      # @option options [String] :url The analysis url.  Required.  Example: 'http://echonest-analysis.s3.amazonaws.com/TR/TREYOVK13C9786E66B/3/full.json?AWSAccessKeyId=AKIAJRDFEY23UEVW42BQ&Expires=1367708437&Signature=pPUyoKFvgwXj2FORgohKOA6pRPc%3D'.
      # @example Analysis
      #   Echowrap.track_analysis(:url => "http://echonest-analysis.s3.amazonaws.com/TR/TREYOVK13C9786E66B/3/full.json?AWSAccessKeyId=AKIAJRDFEY23UEVW42BQ&Expires=1367708437&Signature=pPUyoKFvgwXj2FORgohKOA6pRPc%3D")
      def track_analysis(options={})
        url = options.delete(:url)
        response = send(:get, url, options)
        Echowrap::Analysis.new(response[:body])
      end

    end
  end
end


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/drive/drive_sync_client.h"

#include <algorithm>
#include <vector>

#include "base/bind.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/files/scoped_temp_dir.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/prefs/pref_service.h"
#include "base/test/test_timeouts.h"
#include "base/threading/sequenced_worker_pool.h"
#include "chrome/browser/chromeos/drive/drive.pb.h"
#include "chrome/browser/chromeos/drive/drive_file_system_util.h"
#include "chrome/browser/chromeos/drive/drive_test_util.h"
#include "chrome/browser/chromeos/drive/mock_drive_file_system.h"
#include "chrome/browser/google_apis/test_util.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/testing_profile.h"
#include "content/public/test/test_browser_thread.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

using ::testing::AnyNumber;
using ::testing::DoAll;
using ::testing::Return;
using ::testing::StrictMock;
using ::testing::_;

namespace drive {

namespace {

// Action used to set mock expectations for GetFileByResourceId().
ACTION_P4(MockGetFileByResourceId, error, local_path, mime_type, file_type) {
  arg2.Run(error, local_path, mime_type, file_type);
}

// Action used to set mock expectations for UpdateFileByResourceId().
ACTION_P(MockUpdateFileByResourceId, error) {
  arg2.Run(error);
}

// Action used to set mock expectations for GetFileInfoByResourceId().
ACTION_P2(MockUpdateFileByResourceId, error, md5) {
  scoped_ptr<DriveEntryProto> entry_proto(new DriveEntryProto);
  entry_proto->mutable_file_specific_info()->set_file_md5(md5);
  arg1.Run(error, base::FilePath(), entry_proto.Pass());
}

class MockNetworkChangeNotifier : public net::NetworkChangeNotifier {
 public:
  MOCK_CONST_METHOD0(GetCurrentConnectionType,
                     net::NetworkChangeNotifier::ConnectionType());
};

}  // namespace

class DriveSyncClientTest : public testing::Test {
 public:
  DriveSyncClientTest()
      : ui_thread_(content::BrowserThread::UI, &message_loop_),
        profile_(new TestingProfile),
        mock_file_system_(new StrictMock<MockDriveFileSystem>) {
  }

  virtual void SetUp() OVERRIDE {
    mock_network_change_notifier_.reset(new MockNetworkChangeNotifier);

    // Create a temporary directory.
    ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());

    // Initialize the cache.
    scoped_refptr<base::SequencedWorkerPool> pool =
        content::BrowserThread::GetBlockingPool();
    cache_.reset(new DriveCache(
        temp_dir_.path(),
        pool->GetSequencedTaskRunner(pool->GetSequenceToken()),
        NULL /* free_disk_space_getter */));
    bool cache_initialization_success = false;
    cache_->RequestInitialize(
        base::Bind(&test_util::CopyResultFromInitializeCacheCallback,
                   &cache_initialization_success));
    google_apis::test_util::RunBlockingPoolTask();
    ASSERT_TRUE(cache_initialization_success);
    SetUpCache();

    // Initialize the sync client.
    sync_client_.reset(new DriveSyncClient(profile_.get(),
                                           mock_file_system_.get(),
                                           cache_.get()));

    EXPECT_CALL(*mock_file_system_, AddObserver(sync_client_.get())).Times(1);
    EXPECT_CALL(*mock_file_system_,
                RemoveObserver(sync_client_.get())).Times(1);

    // Disable delaying so that DoSyncLoop() starts immediately.
    sync_client_->set_delay_for_testing(base::TimeDelta::FromSeconds(0));
    sync_client_->Initialize();
  }

  virtual void TearDown() OVERRIDE {
    // The sync client should be deleted before NetworkLibrary, as the sync
    // client registers itself as observer of NetworkLibrary.
    sync_client_.reset();
    cache_.reset();
    mock_network_change_notifier_.reset();
  }

  // Sets up cache for tests.
  void SetUpCache() {
    // Prepare a temp file.
    base::FilePath temp_file;
    EXPECT_TRUE(file_util::CreateTemporaryFileInDir(temp_dir_.path(),
                                                    &temp_file));
    const std::string content = "hello";
    EXPECT_EQ(static_cast<int>(content.size()),
              file_util::WriteFile(temp_file, content.data(), content.size()));

    // Prepare 3 pinned-but-not-present files.
    DriveFileError error = DRIVE_FILE_OK;
    cache_->Pin("resource_id_not_fetched_foo", "",
                google_apis::test_util::CreateCopyResultCallback(&error));
    google_apis::test_util::RunBlockingPoolTask();
    EXPECT_EQ(DRIVE_FILE_OK, error);

    cache_->Pin("resource_id_not_fetched_bar", "",
                google_apis::test_util::CreateCopyResultCallback(&error));
    google_apis::test_util::RunBlockingPoolTask();
    EXPECT_EQ(DRIVE_FILE_OK, error);

    cache_->Pin("resource_id_not_fetched_baz", "",
                google_apis::test_util::CreateCopyResultCallback(&error));
    google_apis::test_util::RunBlockingPoolTask();
    EXPECT_EQ(DRIVE_FILE_OK, error);

    // Prepare a pinned-and-fetched file.
    const std::string resource_id_fetched = "resource_id_fetched";
    const std::string md5_fetched = "md5";
    base::FilePath cache_file_path;
    cache_->Store(resource_id_fetched, md5_fetched, temp_file,
                  DriveCache::FILE_OPERATION_COPY,
                  google_apis::test_util::CreateCopyResultCallback(&error));
    google_apis::test_util::RunBlockingPoolTask();
    EXPECT_EQ(DRIVE_FILE_OK, error);
    cache_->Pin(resource_id_fetched, md5_fetched,
                google_apis::test_util::CreateCopyResultCallback(&error));
    google_apis::test_util::RunBlockingPoolTask();
    EXPECT_EQ(DRIVE_FILE_OK, error);

    // Prepare a pinned-and-fetched-and-dirty file.
    const std::string resource_id_dirty = "resource_id_dirty";
    const std::string md5_dirty = "";  // Don't care.
    cache_->Store(resource_id_dirty, md5_dirty, temp_file,
                  DriveCache::FILE_OPERATION_COPY,
                  google_apis::test_util::CreateCopyResultCallback(&error));
    google_apis::test_util::RunBlockingPoolTask();
    EXPECT_EQ(DRIVE_FILE_OK, error);
    cache_->Pin(resource_id_dirty, md5_dirty,
                google_apis::test_util::CreateCopyResultCallback(&error));
    google_apis::test_util::RunBlockingPoolTask();
    EXPECT_EQ(DRIVE_FILE_OK, error);
    cache_->MarkDirty(
        resource_id_dirty, md5_dirty,
        google_apis::test_util::CreateCopyResultCallback(&error));
    google_apis::test_util::RunBlockingPoolTask();
    EXPECT_EQ(DRIVE_FILE_OK, error);
    cache_->CommitDirty(
        resource_id_dirty, md5_dirty,
        google_apis::test_util::CreateCopyResultCallback(&error));
    google_apis::test_util::RunBlockingPoolTask();
    EXPECT_EQ(DRIVE_FILE_OK, error);
  }

  // Sets the expectation for MockDriveFileSystem::GetFileByResourceId(),
  // that simulates successful retrieval of a file for the given resource ID.
  void SetExpectationForGetFileByResourceId(const std::string& resource_id) {
    EXPECT_CALL(*mock_file_system_,
                GetFileByResourceId(resource_id, _, _, _))
        .WillOnce(
            MockGetFileByResourceId(
                DRIVE_FILE_OK,
                base::FilePath::FromUTF8Unsafe("local_path_does_not_matter"),
                std::string("mime_type_does_not_matter"),
                REGULAR_FILE));
  }

  // Sets the expectation for MockDriveFileSystem::UpdateFileByResourceId(),
  // that simulates successful uploading of a file for the given resource ID.
  void SetExpectationForUpdateFileByResourceId(
      const std::string& resource_id) {
    EXPECT_CALL(*mock_file_system_,
                UpdateFileByResourceId(resource_id, _, _))
        .WillOnce(MockUpdateFileByResourceId(DRIVE_FILE_OK));
  }

  // Sets the expectation for MockDriveFileSystem::GetFileInfoByResourceId(),
  // that simulates successful retrieval of file info for the given resource
  // ID.
  //
  // This is used for testing StartCheckingExistingPinnedFiles(), hence we
  // are only interested in the MD5 value in DriveEntryProto.
  void SetExpectationForGetFileInfoByResourceId(
      const std::string& resource_id,
      const std::string& new_md5) {
    EXPECT_CALL(*mock_file_system_,
                GetEntryInfoByResourceId(resource_id, _))
        .WillOnce(MockUpdateFileByResourceId(
            DRIVE_FILE_OK,
            new_md5));
  }

  // Returns the resource IDs in the queue to be fetched.
  std::vector<std::string> GetResourceIdsToBeFetched() {
    return sync_client_->GetResourceIdsForTesting(
        DriveSyncClient::FETCH);
  }

  // Returns the resource IDs in the queue to be uploaded.
  std::vector<std::string> GetResourceIdsToBeUploaded() {
    return sync_client_->GetResourceIdsForTesting(
        DriveSyncClient::UPLOAD);
  }

  // Adds a resource ID of a file to fetch.
  void AddResourceIdToFetch(const std::string& resource_id) {
    sync_client_->AddResourceIdForTesting(DriveSyncClient::FETCH, resource_id);
  }

  // Adds a resource ID of a file to upload.
  void AddResourceIdToUpload(const std::string& resource_id) {
    sync_client_->AddResourceIdForTesting(DriveSyncClient::UPLOAD,
                                          resource_id);
  }

 protected:
  MessageLoopForUI message_loop_;
  content::TestBrowserThread ui_thread_;
  base::ScopedTempDir temp_dir_;
  scoped_ptr<TestingProfile> profile_;
  scoped_ptr<StrictMock<MockDriveFileSystem> > mock_file_system_;
  scoped_ptr<DriveCache, test_util::DestroyHelperForTests> cache_;
  scoped_ptr<DriveSyncClient> sync_client_;
  scoped_ptr<MockNetworkChangeNotifier> mock_network_change_notifier_;
};

TEST_F(DriveSyncClientTest, StartInitialScan) {
  // Start processing the files in the backlog. This will collect the
  // resource IDs of these files.
  sync_client_->StartProcessingBacklog();

  // Check the contents of the queue for fetching.
  SetExpectationForGetFileByResourceId("resource_id_not_fetched_bar");
  SetExpectationForGetFileByResourceId("resource_id_not_fetched_baz");
  SetExpectationForGetFileByResourceId("resource_id_not_fetched_foo");

  // Check the contents of the queue for uploading.
  SetExpectationForUpdateFileByResourceId("resource_id_dirty");

  google_apis::test_util::RunBlockingPoolTask();
}

TEST_F(DriveSyncClientTest, OnCachePinned) {
  // This file will be fetched by GetFileByResourceId() as OnCachePinned()
  // will kick off the sync loop.
  SetExpectationForGetFileByResourceId("resource_id_not_fetched_foo");

  sync_client_->OnCachePinned("resource_id_not_fetched_foo", "md5");

  google_apis::test_util::RunBlockingPoolTask();
}

TEST_F(DriveSyncClientTest, OnCacheUnpinned) {
  AddResourceIdToFetch("resource_id_not_fetched_foo");
  AddResourceIdToFetch("resource_id_not_fetched_bar");
  AddResourceIdToFetch("resource_id_not_fetched_baz");
  ASSERT_EQ(3U, GetResourceIdsToBeFetched().size());

  sync_client_->OnCacheUnpinned("resource_id_not_fetched_foo", "md5");
  sync_client_->OnCacheUnpinned("resource_id_not_fetched_baz", "md5");

  // Only resource_id_not_fetched_foo should be fetched.
  SetExpectationForGetFileByResourceId("resource_id_not_fetched_bar");

  google_apis::test_util::RunBlockingPoolTask();
}

TEST_F(DriveSyncClientTest, Deduplication) {
  AddResourceIdToFetch("resource_id_not_fetched_foo");

  // Set the delay so that DoSyncLoop() is delayed.
  sync_client_->set_delay_for_testing(TestTimeouts::action_max_timeout());
  // Raise OnCachePinned() event. This shouldn't result in adding the second
  // task, as tasks are de-duplicated.
  sync_client_->OnCachePinned("resource_id_not_fetched_foo", "md5");

  ASSERT_EQ(1U, GetResourceIdsToBeFetched().size());
}

TEST_F(DriveSyncClientTest, ExistingPinnedFiles) {
  // Set the expectation so that the MockDriveFileSystem returns "new_md5"
  // for "resource_id_fetched". This simulates that the file is updated on
  // the server side, and the new MD5 is obtained from the server (i.e. the
  // local cache file is stale).
  SetExpectationForGetFileInfoByResourceId("resource_id_fetched",
                                           "new_md5");
  // Set the expectation so that the MockDriveFileSystem returns "some_md5"
  // for "resource_id_dirty". The MD5 on the server is always different from
  // the MD5 of a dirty file, which is set to "local". We should not collect
  // this by StartCheckingExistingPinnedFiles().
  SetExpectationForGetFileInfoByResourceId("resource_id_dirty",
                                           "some_md5");

  // Start checking the existing pinned files. This will collect the resource
  // IDs of pinned files, with stale local cache files.
  sync_client_->StartCheckingExistingPinnedFiles();

  SetExpectationForGetFileByResourceId("resource_id_fetched");

  google_apis::test_util::RunBlockingPoolTask();
}

}  // namespace drive


text:
using ctci.Contracts;
using ctci.Library;
using System;

namespace Chapter04
{
    static partial class TreeNodeExtension
    {
        static public TreeNode Replace(this TreeNode node, int value)
        {
            if (node == null) return null;
            var newNode = new TreeNode(node);
            newNode.Data = value;
            var newRoot = newNode;
            while (node.Parent != null)
            {
                newRoot = new TreeNode(node.Parent);
                newNode.Parent = newRoot;
                if (newRoot.Left == node)
                    newRoot.Left = newNode;
                if (newRoot.Right == node)
                    newRoot.Right = newNode;
                node = node.Parent;
                newNode = newRoot;
            }
            return newRoot;
        }
    }
    public class ReplaceNodeInImmutableTree : Question
    {
        public override void Run()
        {
            var tree = Q4_02_CreateMinimalBSTfromSortedUniqueArray.Create(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
            var nodeToReplace = tree.Find(6);
            TreeNode newTree = nodeToReplace.Replace(11);
            BTreePrinter.Print(tree);
            BTreePrinter.Print(newTree);
        }
    }
}


text:
/* /////////////////////////////////////////////////////////////////////////
 * File:        examples/cpp/inserters/example.cpp.inserter.threadid/example.cpp.inserter.threadid.cpp
 *
 * Purpose:     C++ example program for Pantheios. Demonstrates:
 *
 *                - use of Pantheios inserter for thread ids
 *                - use of pantheios::logputs() in bail-out conditions
 *
 * Created:     17th October 2006
 * Updated:     6th December 2010
 *
 * www:         http://www.pantheios.org/
 *
 * License:     This source code is placed into the public domain 2006
 *              by Synesis Software Pty Ltd. There are no restrictions
 *              whatsoever to your use of the software.
 *
 *              This software is provided "as is", and any warranties,
 *              express or implied, of any kind and for any purpose, are
 *              disclaimed.
 *
 * ////////////////////////////////////////////////////////////////////// */

/* Pantheios Header Files */
#include <pantheios/pantheios.hpp>              // Pantheios C++ main header
#include <pantheios/inserters/threadid.hpp>     // for pantheios::threadId

/* Standard C/C++ Header Files */
#include <exception>                            // for std::exception
#include <new>                                  // for std::bad_alloc
#include <string>                               // for std::string
#include <stdlib.h>                             // for exit codes

#ifndef PANTHEIOS_DOCUMENTATION_SKIP_SECTION
# if defined(STLSOFT_COMPILER_IS_MSVC)
#  pragma warning(disable : 4702)
# endif /* compiler */
#endif /* !PANTHEIOS_DOCUMENTATION_SKIP_SECTION */

/* ////////////////////////////////////////////////////////////////////// */

/* Define the stock front-end process identity, so that it links when using
 * fe.N, fe.simple, etc. */
PANTHEIOS_EXTERN_C const PAN_CHAR_T PANTHEIOS_FE_PROCESS_IDENTITY[] = PANTHEIOS_LITERAL_STRING("example.cpp.inserter.threadid");

/* ////////////////////////////////////////////////////////////////////// */

#define PSTR(x)         PANTHEIOS_LITERAL_STRING(x)

/* ////////////////////////////////////////////////////////////////////// */

int main()
{
  try
  {
    // Log the thread Id; Output: "thread id: [3540]"

    pantheios::log_NOTICE(PSTR("thread id: ["), pantheios::threadId, PSTR("]"));

    return EXIT_SUCCESS;
  }
  catch(std::bad_alloc&)
  {
    pantheios::log(pantheios::alert, PSTR("out of memory"));
  }
  catch(std::exception& x)
  {
    pantheios::log_CRITICAL(PSTR("Exception: "), x);
  }
  catch(...)
  {
    pantheios::logputs(pantheios::emergency, PSTR("Unexpected unknown error"));
  }

  return EXIT_FAILURE;
}

/* ///////////////////////////// end of file //////////////////////////// */


text:
```sh
91.240.87.232  eastwood.public
```

### Развертывание
Есть 2 основных варианта развертывания:
 - При помощи Docker (рекомендуемый)
 - Вручную

#### Развертывание докером:
 - Клонируем репозиорий git@github.com:GhostSt/Eastwood.git в директорию /var/www/eastwood
 - Переходим в директорию /var/www/eastwood и выполняем команду
```sh
sudo docker-compose -f docker-compose.prod.yml up -d
```
 - Далее нужно узнать ip nginx контейнера, чтобы добавить запись в /etc/hosts
```sh
sudo docker inspect eastwood_nginx_1 | grep IPAddress
```
Нюанс - если проект разворачивается в другой директории, нужно посмотреть название контейнера(нужен nginx контейнер) через:
```sh
sudo docker ps
```
Будет выведена строка ```"IPAddress": "172.18.0.4"``` - вроде этой.
 - Берем этот ip и добавляем строку в /etc/hosts:
```sh
172.18.0.4 eastwood.test
```
Ваш ip, вероятно будет отличаться от приведенного здесь.
 - Тепер нужно накатить базу, и можно использовать. Для этого подключаемся в контейнеру, выполняем миграции, загружаем фикстуры и все.
```sh
sudo docker exec -it eastwood_php_1 /bin/bash
```
Нюанс - если проект разворачивается в другой директории, нужно посмотреть название контейнера(нужен php контейнер)
Далее выполняем 2 команды:
```sh
php bin/console doctrine:migration:migrate -n
```
```sh
php bin/console doctrine:fixtures:load -n
```

Проект готов к работе и доступен по адресу:
# http://eastwood.test/

P.S. Все манипуляции производились под Ubuntu 16.04
Под виндой алгоритм будет примерно тот же.

### Развертывание вручную
 - Создаем виртуальный домен
 - Клонируем репозиторий - git@github.com:GhostSt/Eastwood.git
 - Создаем базу данных
 - Выполняем composer install
 - Вбиваем настройки для базы в app/config/parameters.yml
 - Выполняем команды:
```sh
php bin/console assets:install web
```
```sh
php bin/console assetic:dump
```
```sh
php bin/console doctrine:migration:migrate -n
```
```sh
php bin/console doctrine:fixtures:load -n
```
```sh
php bin/console cache:clear --env=prod
```

После чего проект должен заработать на локалке. Но это не точно :)
Упор был сделан на развертывание докером, а этот вариант я привел на случай, если докера нет от слова совсем.


text:
<?php

/**
 * TableInfo test class
 *
 * @package    Test
 * @subpackage Database
 * @author     Pierre Feyssaguet <pfeyssaguet@gmail.com>
 * @since      5 avril 2013
 */

namespace DspLib\Test\Database;

use DspLib\Config;
use DspLib\Database\TableInfo;
use DspLib\Database\FieldInfo;
use DspLib\Database\Database;

/**
 * TableInfo test class
 *
 * @package    Test
 * @subpackage Database
 * @author     Pierre Feyssaguet <pfeyssaguet@gmail.com>
 * @since      5 avril 2013
 */

class TableInfoTest extends DatabaseTestCase
{
    public function setUp()
    {
        parent::setUp();
        $oConfig = Config::getInstance();
        $oConfig->setParam(
            'database',
            array(
                'driver' => 'MySQL',
                'host' => $GLOBALS['db_host'],
                'login' => $GLOBALS['db_login'],
                'password' => $GLOBALS['db_password'],
                'dbname' => $GLOBALS['db_name'],
            )
        );

        $oDb = Database::getInstance();
        $oDb->query(
            "CREATE TABLE IF NOT EXISTS test_table (
                idtest_table INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
                name VARCHAR(32) NOT NULL DEFAULT '' COMMENT 'test name',
                test_null VARCHAR(50) COMMENT 'test null',
                key1 VARCHAR(12) NOT NULL,
                key2 VARCHAR(12) NOT NULL,
                PRIMARY KEY (idtest_table),
                UNIQUE KEY key1_key2 (key1, key2)
            ) COMMENT 'Test comment'"
        );
    }

    public function tearDown()
    {
        $oDb = Database::getInstance();
        $oDb->query("DROP TABLE test_table");
    }

    public function testCreateTable()
    {
        $oDb = Database::getInstance();
        $oTableInfo = new TableInfo('test_table2');
        $oFieldInfo = new FieldInfo('test_field', 'varchar(32)');
        $oTableInfo->addField($oFieldInfo);
        $oTableInfo->setComment("Test comment");
        $oTableInfo->createTable($oDb);

        $oResult = $oDb->query("SHOW TABLE STATUS LIKE 'test_table2'");
        $oResult->rewind();
        $aRow = $oResult->current();
        $this->assertEquals('Test comment', $aRow['Comment']);

        $oResult = $oDb->query("SHOW FULL COLUMNS FROM test_table2");
        $oResult->rewind();
        $aRow = $oResult->current();
        $this->assertEquals('test_field', $aRow['Field']);
        $this->assertEquals('varchar(32)', $aRow['Type']);

        $oDb->query("DROP TABLE test_table2");
    }

    public function testCreateTableBis()
    {
        $oDb = Database::getInstance();
        $oTableInfo = new TableInfo('test_table2');
        $oTableInfo->setComment('Test comment');

        $oFieldInfo = new FieldInfo('idtest_table', 'INT(11) UNSIGNED', false, null, 'AUTO_INCREMENT');
        $oTableInfo->addField($oFieldInfo);
        $oTableInfo->addPrimaryKey('idtest_table');

        $oFieldInfo = new FieldInfo('name', 'VARCHAR(32)');
        $oFieldInfo->setComment('test name');
        $oFieldInfo->setDefault("''");
        $oTableInfo->addField($oFieldInfo);

        $oFieldInfo = new FieldInfo('test_null', 'VARCHAR(50)', true);
        $oFieldInfo->setComment('test null');
        $oTableInfo->addField($oFieldInfo);

        $oFieldInfo = new FieldInfo('key1', 'VARCHAR(12)');
        $oTableInfo->addField($oFieldInfo);

        $oFieldInfo = new FieldInfo('key2', 'VARCHAR(12)');
        $oTableInfo->addField($oFieldInfo);

        $oTableInfo->addKey('key1_key2', array('key1', 'key2'), true);

        $sActualCreateTableScript = $oTableInfo->generateCreate();
        $sExpectedCreateTableScript = "CREATE TABLE IF NOT EXISTS `test_table2` (
`idtest_table` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(32) NOT NULL DEFAULT '' COMMENT 'test name',
`test_null` VARCHAR(50) COMMENT 'test null',
`key1` VARCHAR(12) NOT NULL,
`key2` VARCHAR(12) NOT NULL,
PRIMARY KEY (`idtest_table`),
UNIQUE KEY `key1_key2` (`key1`, `key2`)
) COMMENT 'Test comment'";

        $this->assertEquals($sExpectedCreateTableScript, $sActualCreateTableScript);

        $oTableInfo->createTable($oDb);

        $oDb->query("DROP TABLE test_table2");
    }

    public function testGetComment()
    {
        $oDb = Database::getInstance();
        $oTableInfo = TableInfo::getTableInfoFromDb($oDb, 'test_table');
        $sActualComment = $oTableInfo->getComment();
        $sExpectedComment = "Test comment";
        $this->assertEquals($sExpectedComment, $sActualComment);
    }

    public function testGetPrimaryKeys()
    {
        $oDb = Database::getInstance();
        $oTableInfo = TableInfo::getTableInfoFromDb($oDb, 'test_table');
        $aActualKeys = $oTableInfo->getPrimaryKeys();

        $aExpectedKeys = array(
            'idtest_table',
        );

        $this->assertEquals($aExpectedKeys, $aActualKeys);
    }

    public function testGetUniqueKeys()
    {
        $oDb = Database::getInstance();
        $oTableInfo = TableInfo::getTableInfoFromDb($oDb, 'test_table');
        $aActualKeys = $oTableInfo->getUniqueKeys();

        $aExpectedKeys = array(
            'key1_key2' => array('key1', 'key2'),
        );

        $this->assertEquals($aExpectedKeys, $aActualKeys);
    }
}


text:
'use strict';
/* globals $, app, ajaxify */

(function () {
  /*
    This file shows how client-side javascript can be included via a plugin.
    If you check `plugin.json`, you"ll see that this file is listed under "scripts".
    That array tells NodeBB which files to bundle into the minified javascript
    that is served to the end user.
    Some events you can elect to listen for:
    $(document).ready(); Fired when the DOM is ready
    $(window).on("action:ajaxify.end", function(data) { ... }); "data" contains "url"
  */

  var root = document.createElement('div')
  root.setAttribute('id', 'moonlight-root')
  var link = document.createElement('link')
  link.setAttribute('rel', 'stylesheet')
  link.setAttribute('type', 'text/css')
  link.setAttribute('href', '/plugins/nodebb-plugin-moonlight/public/admin.css')
  document.head.appendChild(link)

  require(['/plugins/nodebb-plugin-moonlight/public/main.js'], function (App) {
    App.initSocket()

    App.renderAdmin(root)
  })

  $(window).on('action:ajaxify.contentLoaded', function (data) {
    require(['/plugins/nodebb-plugin-moonlight/public/main.js'], function (App) {
      if (ajaxify.data.url.startsWith('/admin/plugins/moonlight')) {
        document.getElementById('moonlight-content').appendChild(root)
        if (ajaxify.data.action) {
          App.store.dispatch(ajaxify.data.action)
        }
        const url = ajaxify.data.url.replace('loggedin', '')
        if (url.endsWith('?')) {
          url.slice(0, -1)
        }
        app.enterRoom('mnl.admin', function () { })
      }
    })
  })
}())


text:
<?xml version="1.0" encoding="utf-8"?><!--
  ~ Copyright 2020 Andrey Tolpeev
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~    http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<androidx.constraintlayout.widget.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"
    style="@style/RecyclerViewItem"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/dp_16"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:tint="@color/material_on_surface_emphasis_high_type"
        tools:srcCompat="@drawable/ic_check_circle_black_24dp" />

    <TextView
        android:id="@+id/userName"
        style="@style/ItemSubTitle"
        android:layout_width="@dimen/dp_0"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/dp_16"
        android:layout_marginTop="@dimen/dp_16"
        android:layout_marginEnd="@dimen/dp_16"
        app:layout_constrainedWidth="true"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/image"
        app:layout_constraintTop_toTopOf="parent"
        tools:text="user.name" />

    <TextView
        android:id="@+id/commitName"
        style="@style/ItemTitle"
        android:layout_width="@dimen/dp_0"
        android:layout_height="wrap_content"
        android:layout_marginEnd="@dimen/dp_16"
        app:layout_constrainedWidth="true"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="@id/userName"
        app:layout_constraintTop_toBottomOf="@id/userName"
        tools:text="Commit message" />

    <TextView
        android:id="@+id/commitHash"
        style="@style/ItemSubTitle"
        android:layout_width="@dimen/dp_0"
        android:layout_height="wrap_content"
        android:layout_marginEnd="@dimen/dp_16"
        app:layout_constrainedWidth="true"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="@id/commitName"
        app:layout_constraintTop_toBottomOf="@id/commitName"
        tools:text="6d1080507eea" />

    <TextView
        android:id="@+id/commitDate"
        style="@style/ItemSubTitle"
        android:layout_width="@dimen/dp_0"
        android:layout_height="wrap_content"
        android:layout_marginEnd="@dimen/dp_16"
        app:layout_constrainedWidth="true"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="@id/commitHash"
        app:layout_constraintTop_toBottomOf="@id/commitHash"
        tools:text="26.06.14" />

    <include
        layout="@layout/layout_divider"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dp_1"
        android:layout_marginTop="@dimen/dp_16"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/commitDate" />

</androidx.constraintlayout.widget.ConstraintLayout>


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
	<title>3D Matrix</title>

  	<link type="text/css" rel="stylesheet" href="css/materialize.css"  media="screen,projection"/>
  	<link rel="stylesheet" href="css/font-awesome.min.css">
  	<link type="text/css" rel="stylesheet" href="css/estilo.css"  media="screen,projection"/>
  	<link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="css/estilo.css">

	        3D Matrix

Listado de matrices

Crear Matrix


text:
#pragma once

#include <nstd/Variant.hpp>

class Json
{
public:
  class Parser
  {
  public:
    Parser();
    ~Parser();

    int getErrorLine() const;
    int getErrorColumn() const;
    String getErrorString() const;

    bool parse(const tchar* data, Variant& result);
    bool parse(const String& data, Variant& result);

  private:
    class Private;
    Private* p;
  };

public:
  /**
   * Strips C/C++ style comments from JSON data without affecting the line in which data is declared.
   *
   * @param [in] data The JSON data.
   * @return  The JSON data with stripped comments.
   */
  static String stripComments(const String& data);

  static bool parse(const tchar* data, Variant& result);
  static bool parse(const String& data, Variant& result);

  static String toString(const Variant& data);

private:
  class Private;
};


text:
import port_for
import port_for.api
import pytest
import requests
import sys

from mountepy import Mountebank, HttpService, ServiceGroup

# starting Python 3 (current Python) HTTP server on a port, that will be set by HttpService
TEST_SERVICE_COMMAND = [sys.executable, '-m', 'http.server', '{port}']
TEST_SERVICE_URL_PATTERN = 'http://localhost:{}'

def test_service_start_and_cleanup():
    service_port = port_for.select_random()
    service_url = TEST_SERVICE_URL_PATTERN.format(service_port)

    with HttpService(TEST_SERVICE_COMMAND, service_port):
        assert requests.get(service_url).status_code == 200

    with pytest.raises(requests.exceptions.ConnectionError):
        requests.get(service_url)

def test_service_single_string_command():
    single_string_command = 'mb'
    service = HttpService(single_string_command, 12345)
    assert service._process_command == single_string_command

def test_service_timeout_and_cleanup():
    test_service = HttpService(TEST_SERVICE_COMMAND)

    with pytest.raises(TimeoutError):
        test_service.start(timeout=0.001)
    test_service._service_proc.wait(timeout=3.0)

def test_mountebank_set_impostor_and_cleanup():
    test_response = 333
    stub_port = 4545
    imposter_config = {
        "port": stub_port,
        "protocol": "http",
        "stubs": [
            {
                "responses": [
                    {
                        "is": {
                            "statusCode": 200,
                            "headers": {
                                "Content-Type": "application/json"
                            },
                            "body": test_response
                        }
                    }
                ],
                "predicates": [
                    {
                        "and": [
                            {
                                "equals": {
                                    "path": "/",
                                    "method": "GET",
                                }
                            },
                        ]
                    }
                ]
            }
        ]
    }

    with Mountebank() as mb:
        mb.add_imposter(imposter_config)
        stub_address = 'http://localhost:{}'.format(stub_port)
        assert requests.get(stub_address).json() == test_response

    # process should be closed now
    with pytest.raises(requests.exceptions.ConnectionError):
        mb.add_imposter(imposter_config)

def test_mountebank_simple_impostor_add():
    test_port = port_for.select_random()
    test_response = 'Just some reponse body (that I used to know)'

    with Mountebank() as mb:
        mb.add_imposter_simple(
            port=test_port,
            method='POST',
            path='/some-path',
            status_code=201,
            response=test_response
        )
        response = requests.post('http://localhost:{}/some-path'.format(test_port))
        assert response.status_code == 201
        assert response.text == test_response

def test_mountebank_impostor_reset():
    test_port = port_for.select_random()
    with Mountebank() as mb:
        imposters_url = 'http://localhost:{}/imposters'.format(mb.port)
        mb.add_imposter_simple(
            port=test_port,
            method='GET',
            path='/',
            status_code=200,
            response=''
        )
        assert requests.get(imposters_url).json()['imposters'] != []
        mb.reset()
        assert requests.get(imposters_url).json()['imposters'] == []

def test_service_group_start():
    test_service_1 = HttpService(TEST_SERVICE_COMMAND)
    test_service_2 = HttpService(TEST_SERVICE_COMMAND)
    test_service_1_url = TEST_SERVICE_URL_PATTERN.format(test_service_1.port)
    test_service_2_url = TEST_SERVICE_URL_PATTERN.format(test_service_2.port)

    with ServiceGroup(test_service_1, test_service_2):
        assert requests.get(test_service_1_url).status_code == 200
        assert requests.get(test_service_2_url).status_code == 200

def test_service_group_start_timeout():
    services = ServiceGroup(HttpService(TEST_SERVICE_COMMAND), HttpService(TEST_SERVICE_COMMAND))
    with pytest.raises(TimeoutError):
        services.start(timeout=0.001)

def test_service_group_stop_timeout():
    services = ServiceGroup(HttpService(TEST_SERVICE_COMMAND), HttpService(TEST_SERVICE_COMMAND))
    services.start()
    with pytest.raises(TimeoutError):
        services.stop(timeout=0.00000001)


text:
import itertools
import re
from pathlib import Path

import numpy as np

data = Path('input.txt').read_text().strip()

players, last_marble = map(int, re.findall('\d+', data))

def calculate(players, last_marble):
    result = np.array([0, 2, 1])
    last_placed_index = 1
    scores = np.zeros(players)

    for player, marble_num in zip(itertools.cycle(np.roll(np.array(range(players)), -len(result))),
                                  range(max(result) + 1, last_marble + 1)):
        if marble_num % 23 != 0:
            new_index = last_placed_index + 2
            if new_index == len(result):
                result = np.append(result, marble_num)
            else:
                new_index = new_index % len(result)
                result = np.insert(result, new_index, marble_num)

            last_placed_index = int(np.where(result == marble_num)[0][0])

        else:
            new_index = (len(result) + last_placed_index - 7) % len(result)
            scores[player] += marble_num
            scores[player] += result[new_index]
            result = np.delete(result, new_index)
            last_placed_index = new_index

    print(int(max(scores)))  # Part 1

calculate(players, last_marble)
# TODO: identify the pattern here
calculate(players, last_marble * 100)


text:
namespace Shuttle.Esb
{
    public interface IQueueService
    {
        IQueue Get(string uri);
        bool Contains(string uri);
    }
}


text:
yum install -y python-pip numpy scipy libvirt-python
pip install --upgrade pyqcy PyContracts SQLAlchemy bottle requests Sphinx python-novaclient
pip install mocktest


text:
/** @file
    @brief Header

    @date 2015

    @author
    Sensics, Inc.
    <http://sensics.com/osvr>
*/

// Copyright 2015 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef INCLUDED_NetworkClassOfService_h_GUID_5B1253E0_C690_4891_5C84_3F713099B8BE
#define INCLUDED_NetworkClassOfService_h_GUID_5B1253E0_C690_4891_5C84_3F713099B8BE

// Internal Includes
#include <osvr/Util/StdInt.h>

// Library/third-party includes
// - none

// Standard includes
#include <type_traits>
#include <stddef.h>

namespace osvr {
namespace common {
    /// @brief Contains tag types for requesting different classes of service
    /// from the networking-based underlying transport (VRPN)
    namespace class_of_service {
        /// @brief Reliable: mandatory in-order, acknowledged delivery, with a
        /// larger message size limit.
        ///
        /// When using networking, this maps to TCP as the underlying transport.
        /// Note that the TCP connection is optimized to minimize overhead
        /// despite being TCP.
        ///
        /// Corresponds to vrpn_CONNECTION_FIXED_LATENCY
        struct Reliable;

        /// @brief Fixed latency service: this class/flag is likely ignored.
        ///
        /// Corresponds to vrpn_CONNECTION_FIXED_LATENCY
        struct FixedLatency;

        /// @brief Low latency, with the caveats of smaller capacity per message
        /// and the possibility of dropped or out of order messages.
        ///
        /// When a UDP connection is available, this maps to UDP as the
        /// underlying transport. Note that it doesn't necessarily guarantee UDP
        /// transport and lower latency, depending on the environment.
        ///
        /// Corresponds to vrpn_CONNECTION_LOW_LATENCY
        struct LowLatency;

        /// @brief Fixed throughput service: this class/flag is likely ignored.
        ///
        /// Corresponds to vrpn_CONNECTION_FIXED_THROUGHPUT
        struct FixedThroughput;

        /// @brief High throughput service: this class/flag is likely ignored.
        ///
        /// Corresponds to vrpn_CONNECTION_HIGH_THROUGHPUT
        struct HighThroughput;

        /// @brief CRTP base for classes of service, useful for accepting
        /// classes of service for an argument without letting just any old type
        /// through.
        template <typename ClassOfService> struct ClassOfServiceBase;

        /// @brief Type trait like std::is_base_of indicating whether the given
        /// type is a recognized class of service.
        template <typename T> struct IsClassOfService;

        /// @brief Given a class of service, returns a m
        template <typename ClassOfService>
        size_t getMessageSizeLimit(ClassOfServiceBase<ClassOfService> const &);

        /// @brief Association of class of service types with integral
        /// constants.
        ///
        /// Values from vrpn_Connection.h
        template <typename ClassOfService> struct VRPNConnectionValue;

        template <>
        struct VRPNConnectionValue<Reliable>
            : std::integral_constant<uint32_t, (1 << 0)> {};
        template <>
        struct VRPNConnectionValue<FixedLatency>
            : std::integral_constant<uint32_t, (1 << 1)> {};
        template <>
        struct VRPNConnectionValue<LowLatency>
            : std::integral_constant<uint32_t, (1 << 2)> {};
        template <>
        struct VRPNConnectionValue<FixedThroughput>
            : std::integral_constant<uint32_t, (1 << 3)> {};
        template <>
        struct VRPNConnectionValue<HighThroughput>
            : std::integral_constant<uint32_t, (1 << 4)> {};

        /* -----implementation follows----- */

        /// @brief Implementation details
        namespace detail {
            /// @brief Base class, do not use directly
            struct ClassOfServiceRoot {
              protected:
                ClassOfServiceRoot() = default;
            };

            template <typename SpecificClass> struct GetMessageSizeLimit {
                static size_t get();
            };
        } // namespace detail

        template <typename ClassOfService>
        struct ClassOfServiceBase : detail::ClassOfServiceRoot {
            typedef ClassOfService type;
            typedef ClassOfServiceBase<ClassOfService> base_type;
            ClassOfServiceBase();
        };
        struct Reliable : ClassOfServiceBase<Reliable> {};

        struct FixedLatency : ClassOfServiceBase<FixedLatency> {};

        struct LowLatency : ClassOfServiceBase<LowLatency> {};

        struct FixedThroughput : ClassOfServiceBase<FixedThroughput> {};

        struct HighThroughput : ClassOfServiceBase<HighThroughput> {};

        template <typename T>
        struct IsClassOfService
            : std::is_base_of<detail::ClassOfServiceRoot, T> {};

        template <typename ClassOfService>
        inline size_t
        getMessageSizeLimit(ClassOfServiceBase<ClassOfService> const &) {
            return detail::GetMessageSizeLimit<ClassOfService>::get();
        }

        /// This inline implementation MUST remain at the bottom of this
        /// file. It consists entirely of compile time checks, so it is
        /// effectively removed from the code once the conditions are
        /// verified.
        template <typename ClassOfService>
        inline ClassOfServiceBase<ClassOfService>::ClassOfServiceBase() {
            /// Partially enforce the Curiously-Recurring Template Pattern.
            /// The assertion here is that for some `ClassOfServiceBase<X>`,
            /// there exists a `class X : public ClassOfServiceBase<X> {};`
            /// Doesn't prevent inheriting from the wrong base (`class X :
            /// public ClassOfServiceBase<Y> {};` where there is already a
            /// `class Y : public ClassOfServiceBase<Y> {};`)
            static_assert(std::is_base_of<base_type, type>::value,
                          "ClassOfServiceBase<T> must be the base of a class "
                          "of service type T (the CRTP)!");
        }

    } // namespace class_of_service
} // namespace common
} // namespace osvr
#endif // INCLUDED_NetworkClassOfService_h_GUID_5B1253E0_C690_4891_5C84_3F713099B8BE


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using HtmlAgilityPack;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Picker.Core.Extensions;

namespace ConsoleDBApp {

  /// <summary>
  /// http://www.sac.gov.cn
  /// </summary>
  public static class SAC {
    const int CountPerPage20 = 20;

    /// <summary>
    /// 0: page(1,)
    /// </summary>
    const string UriTemplate_ActiveStandards = "http://www.sac.gov.cn/SACSearch/search?page={0}&channelid=97779&searchword=%25+and+EXECUTE_STATUS%21%3D%271%27&keyword=%25+and+EXECUTE_STATUS%21%3D%271%27&perpage=20&outlinepage=10&templet=gjcxjg.jsp&keyword=%%20and%20EXECUTE_STATUS!=%271%27&templet=gjcxjg.jsp";
    /// <summary>
    /// 0: page(1,)
    /// </summary>
    const string UriTemplate_RevocativeStandards = "http://www.sac.gov.cn/SACSearch/search?page={0}&channelid=97779&searchword=%25+and+EXECUTE_STATUS%3D%271%27&keyword=%25+and+EXECUTE_STATUS%3D%271%27&perpage=20&outlinepage=10&templet=gjcxjg.jsp&keyword=%%20and%20EXECUTE_STATUS=%271%27&templet=gjcxjg.jsp";
    /// <summary>
    /// 0: GB/T%205121.10-1996;1:Q(GB),Z(GB/Z),T(GB/T)
    /// </summary>
    const string UriTemplate_Standard = "http://www.sac.gov.cn/SACSearch/search?channelid=97779&templet=gjcxjg_detail.jsp&searchword=STANDARD_CODE=%27{0}%27&XZ={1}";

    static ConsoleDBApp.Biz.SacBiz biz = null;

    static JObject createConfig() {
      JObject joConfig = new JObject();
      joConfig.Add( "id", "ID" );
      joConfig.Add( "standard_code", "标准号" );
      joConfig.Add( "chinese_title", "标准名称(中文)" );
      joConfig.Add( "english_title", "Standard Title in English" );
      joConfig.Add( "category", "标准类别" );
      joConfig.Add( "ics", "国际标准分类号" );
      joConfig.Add( "ccs", "中国标准分类号" );
      joConfig.Add( "application_degree", "采用程度" );
      joConfig.Add( "adopted_international_standard", "采用国际标准" );
      joConfig.Add( "adopted_international_standard_number", "采用国际标准号" );
      joConfig.Add( "adopted_international_standard_name", "采标名称" );
      joConfig.Add( "governor", "主管部门" );
      joConfig.Add( "technical_committees", "归口单位" );
      joConfig.Add( "drafting_committee", "起草单位" );
      joConfig.Add( "number_of_pages", "标准页码" );
      joConfig.Add( "price", "标准价格(元)" );
      joConfig.Add( "state", "状态:现行/废止" );
      joConfig.Add( "plan_number", "计划编号" );
      joConfig.Add( "issuance_date", "发布日期" );
      joConfig.Add( "execute_date", "实施日期" );
      joConfig.Add( "first_issuance_date", "首次发布日期" );
      joConfig.Add( "review_affirmance_date", "复审确认日期" );
      joConfig.Add( "replaces", "代替国标号" );
      joConfig.Add( "replaced_by", "被代替国标号" );
      joConfig.Add( "revocatory_date", "废止时间" );
      joConfig.Add( "remark", "备注" );
      return joConfig;
    }

    public static void Run( string conn ) {
      biz = new ConsoleDBApp.Biz.SacBiz( conn );
    }

    /// <summary>
    /// 获取现行标准的列表
    /// </summary>
    /// <returns></returns>
    public static async Task PickList_Active( int millisecondsDelay = 2000 ) {
      Console.WriteLine( "ready..." );

      HtmlDocument doc = new HtmlDocument();
      WebClient client = Picker.Core.Helpers.NetHelper.GetWebClient_UTF8();

      int page = biz.GetPageLastProcessed( UriTemplate_ActiveStandards );
      while ( true ) {
        page++;
        Console.WriteLine( "get page: " + page + "..." );
        string uri = string.Format( UriTemplate_ActiveStandards, page );
        string html = await client.DownloadStringTaskAsync( uri );
        doc.LoadHtml( html );
        // process
        int count = processList( doc.DocumentNode, false, false );
        // query state
        biz.UpdateQueryState( UriTemplate_ActiveStandards, page, false );
        // save
        biz.SaveChanges();
        // continue?
        if ( count < CountPerPage20 )
          break;
        // delay
        await Task.Delay( millisecondsDelay );
      }
      // reset state
      biz.UpdateQueryState( UriTemplate_ActiveStandards, -1, true );
      Console.WriteLine( "over..." );
    }

    /// <summary>
    /// 获取已经废止的标准列表
    /// </summary>
    /// <returns></returns>
    public static async Task PickList_Revocatory( int millisecondsDelay = 2000 ) {
      Console.WriteLine( "ready..." );

      HtmlDocument doc = new HtmlDocument();
      WebClient client = Picker.Core.Helpers.NetHelper.GetWebClient_UTF8();

      int page = biz.GetPageLastProcessed( UriTemplate_RevocativeStandards );
      while ( true ) {
        page++;
        Console.WriteLine( "get page: " + page + "..." );
        string uri = string.Format( UriTemplate_RevocativeStandards, page );
        string html = await client.DownloadStringTaskAsync( uri );
        doc.LoadHtml( html );
        // process
        int count = await processList2( client, doc.DocumentNode, true, false );
        Console.WriteLine( "  save page tag, submit all changes..." );
        // query state
        biz.UpdateQueryState( UriTemplate_RevocativeStandards, page, false );
        // save
        biz.SaveChanges();
        // continue?
        if ( count < CountPerPage20 )
          break;
        Console.WriteLine( "  wait some seconds and continue..." );
        // delay
        await Task.Delay( millisecondsDelay );
      }
      // reset state
      biz.UpdateQueryState( UriTemplate_RevocativeStandards, -1, true );
      Console.WriteLine( "over..." );
    }

    public static async Task PickDetail( int millisecondsDelay = 3000 ) {
      Console.WriteLine( "ready..." );

      HtmlDocument doc = new HtmlDocument();
      WebClient client = Picker.Core.Helpers.NetHelper.GetWebClient_UTF8();

      while ( true ) {
        string code = biz.GetStandardTask();
        if ( string.IsNullOrWhiteSpace( code ) )
          break;
        try {
          await pickDetail( client, code );
          // wait and continue
          await Task.Delay( millisecondsDelay );
        }
        catch ( System.Net.WebException ) {
          Console.WriteLine( "got WebException. wait 30 seconds to retry..." );
          await Task.Delay( 30 * 1000 );
          Console.WriteLine( "retry..." );
          continue;
        }

      }

      Console.WriteLine( "over..." );
    }

    public static async Task Update201605( int millisecondsDelay = 500 ) {
      Console.WriteLine( "ready..." );
      DateTime dt = DateTime.Parse( "2016-6-25 23:59:59" );
      int countPerPage = 50;
      int page = 0;
      int count = 0;
      while ( true ) {
        int tmpCount = biz.UpdateStandards( page, countPerPage, dt );
        count = count + tmpCount;
        Console.WriteLine( "  " + count.ToString() + " items processed." );
        if ( tmpCount == 0 )
          break;
        Console.WriteLine( "wait and continue..." );
        await Task.Delay( millisecondsDelay );
        // 不需要page++
      }

      Console.WriteLine( "over..." );
    }

    /// <summary>
    /// 有些废止的标准,没有RevocatoryDate数据,其中一部分可以从Remark中解析,如:"2004-09-15废止,被GB/T 9846.6-2004代替"
    /// </summary>
    /// <param name="millisecondsDelay"></param>
    /// <returns></returns>
    public static async Task Update201606( int millisecondsDelay = 500 ) {
      Console.WriteLine( "ready..." );
      int countPerPage = 50;
      int page = 0;
      int count = 0;
      while ( true ) {
        int tmpCount = biz.UpdateStandards201606( page, countPerPage );
        count = count + tmpCount;
        Console.WriteLine( "  " + count.ToString() + " items processed." );
        if ( tmpCount == 0 )
          break;
        Console.WriteLine( "wait and continue..." );
        await Task.Delay( millisecondsDelay );
        // 不需要page++
      }

      Console.WriteLine( "over..." );
    }

    static async Task<string> getDetailHtml( WebClient client, string code ) {
      string param1 = code.Replace( " ", "%20" );
      string param2 = null;
      if ( code.StartsWith( "GB/Z" ) )
        param2 = "Z";
      else if ( code.StartsWith( "GB/T" ) )
        param2 = "T";
      else if ( code.StartsWith( "GB " ) )
        param2 = "Q";

      string uri = string.Format( UriTemplate_Standard, param1, param2 );
      string html = await client.DownloadStringTaskAsync( uri );
      return html;
    }

    static async Task pickDetail( WebClient client, string code ) {
      if ( string.IsNullOrWhiteSpace( code ) )
        return;

      HtmlDocument doc = new HtmlDocument();

      Console.Write( "get standard: " + code );
      string html = await getDetailHtml( client, code );
      doc.LoadHtml( html );
      Console.WriteLine( "..." );

      processDetail( code, doc.DocumentNode, true );
    }

    static int processList( HtmlNode root, bool isRevocative, bool saveChanges ) {
      var table = root.SelectSingleNode( "//table[@id='Tbinput']" );
      var rows = table.SelectNodes( "./tr" );
      bool isHeader = true;
      int count = 0;
      foreach ( var row in rows ) {
        if ( isHeader ) {
          isHeader = false;
          continue;
        }
        string code = null,
          remark = null;
        int c = 0;
        var cols = row.SelectNodes( "./td" );
        foreach ( var col in cols ) {
          c++;
          if ( c == 2 ) {
            var a = col.SelectSingleNode( "./a" );
            code = a.InnerText.Trim( '\t', '\r', '\n' );
          }
          else if ( c == 6 ) {
            remark = col.InnerText.Trim( '\t', '\r', '\n' );
          }
        }
        biz.SaveKey_ChinaStandard( code, remark, isRevocative, saveChanges );
        count++;
      }
      return count;
    }

    static async Task<int> processList2( WebClient client, HtmlNode root, bool isRevocative, bool saveChanges ) {
      var table = root.SelectSingleNode( "//table[@id='Tbinput']" );
      var rows = table.SelectNodes( "./tr" );
      bool isHeader = true;
      int count = 0;
      foreach ( var row in rows ) {
        if ( isHeader ) {
          isHeader = false;
          continue;
        }
        string code = null,
          remark = null;
        int c = 0;
        var cols = row.SelectNodes( "./td" );
        foreach ( var col in cols ) {
          c++;
          if ( c == 2 ) {
            var a = col.SelectSingleNode( "./a" );
            code = a.InnerText.Trim( '\t', '\r', '\n' );
          }
          else if ( c == 6 ) {
            remark = col.InnerText.Trim( '\t', '\r', '\n' );
          }
        }
        Console.Write( "  --> " + code );
        string detailHtml = await getDetailHtml( client, code );
        HtmlDocument doc = new HtmlDocument();
        doc.LoadHtml( detailHtml );
        Console.Write( " --> DB" );
        // save
        JObject json = getDetailJson( doc.DocumentNode );
        biz.UpdateStandard( code, json, remark, true, saveChanges );

        Console.WriteLine( " √" );

        count++;
      }
      return count;
    }

    static JObject getDetailJson( HtmlNode root ) {
      var table = root.SelectSingleNode( "//table" );
      var rows = table.SelectNodes( "./tr" );
      int rowNumber = 0;
      JObject item = new JObject();

      foreach ( var row in rows ) {
        rowNumber++;
        // 14 rows
        if ( rowNumber == 1 ) { // 标准号
          var td = row.SelectSingleNode( "./td[@colspan='5']" );
          item["standard_code"] = td == null ? null : td.InnerText
            .Trim( '\r', '\n', '\t' )
            .Trim();
        }
        else if ( rowNumber == 2 ) { // 中文标准名称
          var td = row.SelectSingleNode( "./td[@colspan='5']" );
          item["chinese_title"] = td == null ? null : td.InnerText
            .Trim( '\r', '\n', '\t' )
            .Trim();
        }
        else if ( rowNumber == 3 ) { // 英文标准名称
          var td = row.SelectSingleNode( "./td[@colspan='5']" );
          item["english_title"] = td == null ? null : td.InnerText
            .Trim( '\r', '\n', '\t' )
            .Trim();
        }
        else if ( rowNumber == 4 ) { // 发布日期, 实施日期, 首次发布日期
          var tds = row.SelectNodes( "./td" );
          var td = tds.Skip( 1 ).FirstOrDefault();
          string v = td == null ? null : td.InnerText
            .Trim( '\r', '\n', '\t' )
            .Trim();
          item["issuance_date"] = string.IsNullOrWhiteSpace( v ) ? DateTime.MaxValue : DateTime.Parse( v );

          td = tds.Skip( 3 ).FirstOrDefault();
          v = td == null ? null : td.InnerText
            .Trim( '\r', '\n', '\t' )
            .Trim();
          item["execute_date"] = string.IsNullOrWhiteSpace( v ) ? DateTime.MaxValue : DateTime.Parse( v );

          td = tds.Skip( 5 ).FirstOrDefault();
          v = td == null ? null : td.InnerText
            .Trim( '\r', '\n', '\t' )
            .Trim();
          item["first_issuance_date"] = string.IsNullOrWhiteSpace( v ) ? DateTime.MaxValue : DateTime.Parse( v );
        }
        else if ( rowNumber == 5 ) { // 标准状态, 复审确认日期, 计划编号
          var tds = row.SelectNodes( "./td" );
          var td = tds.Skip( 1 ).FirstOrDefault();
          item["state"] = td == null ? null : td.InnerText
            .Trim( '\r', '\n', '\t' )
            .Trim();

          td = tds.Skip( 3 ).FirstOrDefault();
          string v = td == null ? null : td.InnerText
            .Trim( '\r', '\n', '\t' )
            .Trim();
          item["review_affirmance_date"] = string.IsNullOrWhiteSpace( v ) ? DateTime.MaxValue : DateTime.Parse( v );

          td = tds.Skip( 5 ).FirstOrDefault();
          item["plan_number"] = td == null ? null : td.InnerText
            .Trim( '\r', '\n', '\t' )
            .Trim();
        }
        else if ( rowNumber == 6 ) { // 代替国标号, 被代替国标号, 废止时间
          var tds = row.SelectNodes( "./td" );
          var td = tds.Skip( 1 ).FirstOrDefault();
          item["replaces"] = td == null ? null : td.InnerText
            .Trim( '\r', '\n', '\t' )
            .Trim();

          td = tds.Skip( 3 ).FirstOrDefault();
          item["replaced_by"] = td == null ? null : td.InnerText
            .Trim( '\r', '\n', '\t' )
            .Trim();

          td = tds.Skip( 5 ).FirstOrDefault();
          string v = td == null ? null : td.InnerText
            .Trim( '\r', '\n', '\t' )
            .Trim();
          item["revocatory_date"] = string.IsNullOrWhiteSpace( v ) ? DateTime.MaxValue : DateTime.Parse( v );
        }
        else if ( rowNumber == 7 ) { // 采用国际标准号
          var td = row.SelectSingleNode( "./td[@colspan='5']" );
          item["adopted_international_standard_number"] = td == null ? null : td.InnerText
            .Trim( '\r', '\n', '\t' )
            .Trim();
        }
        else if ( rowNumber == 8 ) { // 采标名称
          var td = row.SelectSingleNode( "./td[@colspan='5']" );
          item["adopted_international_standard_name"] = td == null ? null : td.InnerText
            .Trim( '\r', '\n', '\t' )
            .Trim();
        }
        else if ( rowNumber == 9 ) { // 采用程度, 采用国际标准
          var td = row.SelectSingleNode( "./td[@colspan='3']" );
          item["application_degree"] = td == null ? null : td.InnerText
            .Trim( '\r', '\n', '\t' )
            .Trim();

          var tdLast = row.SelectNodes( "./td" ).Last();
          item["adopted_international_standard"] = tdLast == null ? null : tdLast.InnerText
            .Trim( '\r', '\n', '\t' )
            .Trim();
        }
        else if ( rowNumber == 10 ) { // 国际标准分类号, 中国标准分类号
          var td = row.SelectSingleNode( "./td[@colspan='3']" );
          item["ics"] = td == null ? null : td.InnerText
            .Trim( '\r', '\n', '\t' )
            .Trim();

          var tdLast = row.SelectNodes( "./td" ).Last();
          item["ccs"] = tdLast == null ? null : tdLast.InnerText
            .Trim( '\r', '\n', '\t' )
            .Trim();
        }
        else if ( rowNumber == 11 ) { // 标准类别, 标准页码, 标准价格(元)
          var tds = row.SelectNodes( "./td" );
          var td = tds.Skip( 1 ).FirstOrDefault();
          item["category"] = td == null ? null : td.InnerText
            .Trim( '\r', '\n', '\t' )
            .Trim();

          td = tds.Skip( 3 ).FirstOrDefault();
          item["number_of_pages"] = td == null ? null : td.InnerText
            .Trim( '\r', '\n', '\t' )
            .Trim();

          td = tds.Skip( 5 ).FirstOrDefault();
          item["price"] = td == null ? null : td.InnerText
            .Trim( '\r', '\n', '\t' )
            .Trim();
        }
        else if ( rowNumber == 12 ) { // 主管部门
          var td = row.SelectSingleNode( "./td[@colspan='5']" );
          item["governor"] = td == null ? null : td.InnerText
            .Trim( '\r', '\n', '\t' )
            .Trim();
        }
        else if ( rowNumber == 13 ) { // 归口单位
          var td = row.SelectSingleNode( "./td[@colspan='5']" );
          item["technical_committees"] = td == null ? null : td.InnerText
            .Trim( '\r', '\n', '\t' )
            .Trim();
        }
        else if ( rowNumber == 14 ) { // 起草单位
          var td = row.SelectSingleNode( "./td[@colspan='5']" );
          item["drafting_committee"] = td == null ? null : td.InnerText
            .Trim( '\r', '\n', '\t' )
            .Trim();
        }
      }
      return item;
    }

    static void processDetail( string code, HtmlNode root, bool saveChanges ) {
      JObject item = getDetailJson( root );
      // save
      biz.UpdateStandard( code, item );
    }

  }

}


text:
ALTER TABLE workflow_run ADD COLUMN last_sub_num BIGINT NOT NULL DEFAULT 0;
UPDATE workflow_run SET last_sub_num = 0;

ALTER TABLE workflow_run ADD COLUMN last_execution TIMESTAMP WITH TIME ZONE DEFAULT LOCALTIMESTAMP;
UPDATE workflow_run SET last_execution = now();

-- +migrate Down
ALTER TABLE workflow_run DROP COLUMN last_sub_num;


text:
// This file is automatically generated.

package adila.db;

/*
 * Huawei
 *
 * DEVICE: hwu8180
 * MODEL: U8180
 */
final class hwu8180_u8180 {
    public static final String DATA = "Huawei||";
}


text:
const { base64 } = require('../utils')
const {
  GraphQLSchema,
  GraphQLInt,
  GraphQLString,
  GraphQLObjectType,
  GraphQLNonNull,
  GraphQLList,
  GraphQLEnumType,
  GraphQLBoolean,
  GraphQLFloat,
  GraphQLID,
  GraphQLInputObjectType,
  GraphQLInterfaceType,
  GraphQLScalarType,
  GraphQLUnionType
} = require('graphql')
const GraphQLJSON = require('graphql-type-json')
const {
  GraphQLDate,
  GraphQLTime,
  GraphQLDateTime
} = require('graphql-iso-date')

function genTypeFunc (type) {
  return config => Object.assign({ type }, config)
}

const types = {
  Schema: GraphQLSchema,
  Int: GraphQLInt,
  String: GraphQLString,
  Object: GraphQLObjectType,
  Enum: GraphQLEnumType,
  List: GraphQLList,
  NonNull: GraphQLNonNull,
  Boolean: GraphQLBoolean,
  Float: GraphQLFloat,
  ID: GraphQLID,
  Input: GraphQLInputObjectType,
  Interface: GraphQLInterfaceType,
  Scalar: GraphQLScalarType,
  Union: GraphQLUnionType,
  JSON: GraphQLJSON,
  Date: GraphQLDate,
  Time: GraphQLTime,
  DateTime: GraphQLDateTime,
  PageInfo: new GraphQLObjectType({
    name: 'PageInfo',
    fields: _ => ({
      startCursor: types.string({
        resolve: info => base64.encode(info.startCursor)
      }),
      endCursor: types.string({
        resolve: info => base64.encode(info.endCursor)
      }),
      hasNextPage: { type: GraphQLBoolean }
    })
  }),
  type: (type, config) => Object.assign({type}, config),
  list: (type, config) => Object.assign({
    type: new types.List(type)
  }, config),
  nonNull: (type, config) => Object.assign({
    type: new types.NonNull(type)
  }, config),
  object: (type, config) => Object.assign({
    type: new types.Object(type)
  }, config),
  json: genTypeFunc(GraphQLJSON),
  id: genTypeFunc(GraphQLID),
  date: genTypeFunc(GraphQLDate),
  time: genTypeFunc(GraphQLTime),
  datetime: genTypeFunc(GraphQLDateTime),
  float: genTypeFunc(GraphQLFloat),
  string: genTypeFunc(GraphQLString),
  int: genTypeFunc(GraphQLInt),
  boolean: genTypeFunc(GraphQLBoolean),
  bool: genTypeFunc(GraphQLBoolean)
}

module.exports = types


text:
See [json patch specification](http://tools.ietf.org/html/draft-pbryan-json-patch-04) and [json pointer specification](http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-03)

## Installation

Add this line to your application's Gemfile:

    gem 'json-patch', :git => 'https://github.com/tent/json-patch.git'

And then execute:

    $ bundle

## Tests

    $ bundle exec rspec

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
describe Spree::Admin::LegacyReturnAuthorizationsController, type: :controller do
  stub_authorization!

  # Regression test for #1370 #3
  let!(:legacy_return_authorization) { create(:legacy_return_authorization, reason: 'old reason') }

  context "#update" do
    let(:new_reason) { 'new reason' }

    subject do
      spree_put :update, {
        id: legacy_return_authorization.to_param,
        order_id: legacy_return_authorization.order.to_param,
        legacy_return_authorization: {
          reason: new_reason,
        }
      }
    end

    before { subject }

    it "redirects to legacy return authorizations index" do
      expect(response).to redirect_to(spree.admin_order_legacy_return_authorizations_path(legacy_return_authorization.order))
    end

    it "updates the reason" do
      expect(legacy_return_authorization.reload.reason).to eq new_reason
    end
  end
end


text:
package compressutil

import (
	"bytes"
	"compress/gzip"
	"encoding/json"
	"testing"
)

func TestCompressUtil_CompressSnappy(t *testing.T) {
	input := map[string]interface{}{
		"sample":       "data",
		"verification": "process",
	}

	// Encode input into JSON
	var buf bytes.Buffer
	enc := json.NewEncoder(&buf)
	if err := enc.Encode(input); err != nil {
		t.Fatal(err)
	}
	inputJSONBytes := buf.Bytes()

	// Set Snappy compression in the configuration
	compressionConfig := &CompressionConfig{
		Type: CompressionTypeSnappy,
	}

	// Compress the input
	compressedJSONBytes, err := Compress(inputJSONBytes, compressionConfig)
	if err != nil {
		t.Fatal(err)
	}

	decompressedJSONBytes, wasNotCompressed, err := Decompress(compressedJSONBytes)
	if err != nil {
		t.Fatal(err)
	}

	// Check if the input for decompress was not compressed in the first place
	if wasNotCompressed {
		t.Fatalf("bad: expected compressed bytes")
	}

	// Compare the value after decompression
	if string(inputJSONBytes) != string(decompressedJSONBytes) {
		t.Fatalf("bad: decompressed value;\nexpected: %q\nactual: %q", string(inputJSONBytes), string(decompressedJSONBytes))
	}
}

func TestCompressUtil_CompressDecompress(t *testing.T) {
	input := map[string]interface{}{
		"sample":       "data",
		"verification": "process",
	}

	// Encode input into JSON
	var buf bytes.Buffer
	enc := json.NewEncoder(&buf)
	if err := enc.Encode(input); err != nil {
		t.Fatal(err)
	}

	inputJSONBytes := buf.Bytes()
	// Test nil configuration
	if _, err := Compress(inputJSONBytes, nil); err == nil {
		t.Fatal("expected an error")
	}

	// Test invalid configuration
	if _, err := Compress(inputJSONBytes, &CompressionConfig{}); err == nil {
		t.Fatal("expected an error")
	}

	// Compress input using lzw format
	compressedJSONBytes, err := Compress(inputJSONBytes, &CompressionConfig{
		Type: CompressionTypeLzw,
	})
	if err != nil {
		t.Fatal("expected an error")
	}
	if len(compressedJSONBytes) == 0 {
		t.Fatal("failed to compress data in lzw format")
	}
	// Check the presense of the canary
	if compressedJSONBytes[0] != CompressionCanaryLzw {
		t.Fatalf("bad: compression canary: expected: %d actual: %d", CompressionCanaryLzw, compressedJSONBytes[0])
	}

	// Decompress the input and check the output
	decompressedJSONBytes, uncompressed, err := Decompress(compressedJSONBytes)
	if err != nil {
		t.Fatal(err)
	}
	if uncompressed {
		t.Fatal("failed to recognize compressed data")
	}
	if len(decompressedJSONBytes) == 0 {
		t.Fatal("failed to decompress lzw formatted data")
	}

	if string(inputJSONBytes) != string(decompressedJSONBytes) {
		t.Fatalf("bad: mismatch: inputJSONBytes: %s\n decompressedJSONBytes: %s", string(inputJSONBytes), string(decompressedJSONBytes))
	}

	// Compress input using Gzip format, assume DefaultCompression
	compressedJSONBytes, err = Compress(inputJSONBytes, &CompressionConfig{
		Type: CompressionTypeGzip,
	})
	if err != nil {
		t.Fatal("expected an error")
	}
	if len(compressedJSONBytes) == 0 {
		t.Fatal("failed to compress data in lzw format")
	}
	// Check the presense of the canary
	if compressedJSONBytes[0] != CompressionCanaryGzip {
		t.Fatalf("bad: compression canary: expected: %d actual: %d", CompressionCanaryGzip, compressedJSONBytes[0])
	}

	// Decompress the input and check the output
	decompressedJSONBytes, uncompressed, err = Decompress(compressedJSONBytes)
	if err != nil {
		t.Fatal(err)
	}
	if uncompressed {
		t.Fatal("failed to recognize compressed data")
	}
	if len(decompressedJSONBytes) == 0 {
		t.Fatal("failed to decompress lzw formatted data")
	}

	if string(inputJSONBytes) != string(decompressedJSONBytes) {
		t.Fatalf("bad: mismatch: inputJSONBytes: %s\n decompressedJSONBytes: %s", string(inputJSONBytes), string(decompressedJSONBytes))
	}

	// Compress input using Gzip format: DefaultCompression
	compressedJSONBytes, err = Compress(inputJSONBytes, &CompressionConfig{
		Type:                 CompressionTypeGzip,
		GzipCompressionLevel: gzip.DefaultCompression,
	})
	if err != nil {
		t.Fatal("expected an error")
	}
	if len(compressedJSONBytes) == 0 {
		t.Fatal("failed to compress data in lzw format")
	}
	// Check the presense of the canary
	if compressedJSONBytes[0] != CompressionCanaryGzip {
		t.Fatalf("bad: compression canary: expected: %d actual: %d", CompressionCanaryGzip, compressedJSONBytes[0])
	}

	// Decompress the input and check the output
	decompressedJSONBytes, uncompressed, err = Decompress(compressedJSONBytes)
	if err != nil {
		t.Fatal(err)
	}
	if uncompressed {
		t.Fatal("failed to recognize compressed data")
	}
	if len(decompressedJSONBytes) == 0 {
		t.Fatal("failed to decompress lzw formatted data")
	}

	if string(inputJSONBytes) != string(decompressedJSONBytes) {
		t.Fatalf("bad: mismatch: inputJSONBytes: %s\n decompressedJSONBytes: %s", string(inputJSONBytes), string(decompressedJSONBytes))
	}

	// Compress input using Gzip format, BestCompression
	compressedJSONBytes, err = Compress(inputJSONBytes, &CompressionConfig{
		Type:                 CompressionTypeGzip,
		GzipCompressionLevel: gzip.BestCompression,
	})
	if err != nil {
		t.Fatal("expected an error")
	}
	if len(compressedJSONBytes) == 0 {
		t.Fatal("failed to compress data in lzw format")
	}
	// Check the presense of the canary
	if compressedJSONBytes[0] != CompressionCanaryGzip {
		t.Fatalf("bad: compression canary: expected: %d actual: %d", CompressionCanaryGzip, compressedJSONBytes[0])
	}

	// Decompress the input and check the output
	decompressedJSONBytes, uncompressed, err = Decompress(compressedJSONBytes)
	if err != nil {
		t.Fatal(err)
	}
	if uncompressed {
		t.Fatal("failed to recognize compressed data")
	}
	if len(decompressedJSONBytes) == 0 {
		t.Fatal("failed to decompress lzw formatted data")
	}

	if string(inputJSONBytes) != string(decompressedJSONBytes) {
		t.Fatalf("bad: mismatch: inputJSONBytes: %s\n decompressedJSONBytes: %s", string(inputJSONBytes), string(decompressedJSONBytes))
	}

	// Compress input using Gzip format, BestSpeed
	compressedJSONBytes, err = Compress(inputJSONBytes, &CompressionConfig{
		Type:                 CompressionTypeGzip,
		GzipCompressionLevel: gzip.BestSpeed,
	})
	if err != nil {
		t.Fatal("expected an error")
	}
	if len(compressedJSONBytes) == 0 {
		t.Fatal("failed to compress data in lzw format")
	}
	// Check the presense of the canary
	if compressedJSONBytes[0] != CompressionCanaryGzip {
		t.Fatalf("bad: compression canary: expected: %d actual: %d",
			CompressionCanaryGzip, compressedJSONBytes[0])
	}

	// Decompress the input and check the output
	decompressedJSONBytes, uncompressed, err = Decompress(compressedJSONBytes)
	if err != nil {
		t.Fatal(err)
	}
	if uncompressed {
		t.Fatal("failed to recognize compressed data")
	}
	if len(decompressedJSONBytes) == 0 {
		t.Fatal("failed to decompress lzw formatted data")
	}

	if string(inputJSONBytes) != string(decompressedJSONBytes) {
		t.Fatalf("bad: mismatch: inputJSONBytes: %s\n decompressedJSONBytes: %s", string(inputJSONBytes), string(decompressedJSONBytes))
	}
}


text:
/**
 * Attempts to find a sizing container based on the provided HTMLElement. By
 * default, the sizing element will just be the provided element unless:
 * - the item has a known role within react-md that can target known classes
 * - the item has a `data-sizing-selector` attribute that is a valid query
 *   selector for the nested item.
 *
 * NOTE: The `data-sizing-selector` will be run from the current element instead
 * of the `document`.
 *
 * @param el - The element to find a sizing container for.
 * @returns the sizing container relative to the provided element, or `null` if
 * none could be found.
 * @throws This error will be thrown if using the `data-query-selector` and the
 * query selector does not return an element on the page.
 */
export function findSizingContainer(
  el: HTMLElement | null
): HTMLElement | null {
  if (!el) {
    return null;
  }

  if (/(tree|list)item/.test(el.getAttribute("role") || "")) {
    const content = el.querySelector(
      ".rmd-tree-item__content, .rmd-item-text"
    ) as HTMLElement;
    if (content) {
      return content;
    }
  } else if (el.getAttribute("type") === "file") {
    const label = document.querySelector<HTMLLabelElement>(`[for="${el.id}"]`);
    if (label) {
      return label;
    }
  }

  const data = el.getAttribute("data-sizing-selector");
  if (data) {
    const content = el.querySelector(data) as HTMLElement;
    if (content) {
      return content;
    }

    if (process.env.NODE_ENV !== "production") {
      throw new Error(
        "Unable to find a child element using the `data-sizing-selector`"
      );
    }
  }

  return el;
}


text:
<?php
namespace Module\Model;

use Kecik\Model;

class Table extends Model {
    protected static $table = 'table';

    public function __construct($id='') {
        parent::__construct($id);
    }
}


text:
package vdisk

import (
	"gopkg.in/validator.v2"
)

type Vdisk struct {
	Blocksize     int                `yaml:"blocksize" json:"blocksize" validate:"nonzero"`
	ID            string             `yaml:"id" json:"id" validate:"nonzero"`
	ReadOnly      bool               `yaml:"readOnly" json:"readOnly,omitempty"`
	Size          int                `yaml:"size" json:"size" validate:"nonzero"`
	Status        EnumVdiskStatus    `yaml:"status" json:"status" validate:"nonzero"`
	TemplateVdisk string             `yaml:"templatevdisk,omitempty" json:"templatevdisk,omitempty"`
	Vdiskstorage  string             `yaml:"vdiskstorage" json:"vdiskstorage" validate:"nonzero"`
	Vdisktype     EnumVdiskVdisktype `yaml:"type" json:"type" validate:"nonzero"`
}

func (s Vdisk) Validate() error {

	return validator.Validate(s)
}


text:
module ReactLite
  module Rails
    # A renderer class suitable for `ActionController::Renderers`.
    # It is associated to `:component` in the Railtie.
    #
    # It is prerendered with {ReactLite::ServerRendering}.
    #
    # @example Rendering a component from a controller
    #   class TodosController < ApplicationController
    #     def index
    #       @todos = Todo.all
    #       render component: 'TodoList', props: { todos: @todos }, tag: 'span', class: 'todo'
    #     end
    #   end
    class ControllerRenderer
      include ReactLite::Rails::ViewHelper
      include ActionView::Helpers::TagHelper
      include ActionView::Helpers::TextHelper

      attr_accessor :output_buffer

      def initialize(options={})
        controller = options[:controller]
        @__react_component_helper = controller.__react_component_helper
      end

      # @return [String] Prerendered HTML for `component_name` with `options[:props]`
      def call(component_name, options, &block)
        props = options.fetch(:props, {})
        options = options.slice(:data, :aria, :tag, :class, :id).merge(prerender: true)
        react_component(component_name, props, options, &block)
      end
    end
  end
end