text:
'use strict';

var _ = require('lodash');
var async = require('async');
var path = require('path');
var gulp = require('gulp');
var gutil = require('gulp-util');
var transform = require('vinyl-transform');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var map = require('vinyl-map');
var plumber = require('gulp-plumber');
var browserify = require('browserify');
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var watch = require('gulp-watch');
var fs = require('fs-extra');
var pkgInfo = require('./package');

var contentHash = require('./content-hash');
var optionsParser = require('./options-parser');
var Manifest = require('./manifest');

function __hookAddAsset(peckerObj, file, assetOptions) {
  var val = path.join(peckerObj.options.baseUrl, path.basename(file.path));
  peckerObj._manifest.addAsset(assetOptions.type, assetOptions.name, val, file.path);
}

/**
 * Built-in transforms
 */
var TRANSFORMS_MAP = {
  'debug': require('./transforms/debug'),
  'concat': require('./transforms/concat'),
  'uglify': require('./transforms/uglify'),
  'less': require('./transforms/less'),
  'sass': require('./transforms/sass'),
  'clean-css': require('./transforms/clean-css'),
  'autoprefixer': require('./transforms/autoprefixer'),
  'imagemin': require('./transforms/imagemin')
};

/**
 * Pecker.Builder class
 * @param options
 * @constructor
 */
function Builder(options) {
  this.options = null;
  this._manifest = null;

  this.setOptions(options);
}

/**
 * Builder methods
 */

Builder.prototype.buildBrowserifyAsset = function (_assetOptions, done) {
  var assetOptions = optionsParser.parseAssetOptions(this.options.baseDir, this._manifest.getAssetNames(), _assetOptions);

  var called = false;
  var self = this;

  // skip bundles
  if (_.indexOf(this.options.skip, assetOptions.name) > -1) {
    return done();
  }

  var outputName = assetOptions.name;

  var doBundle = function doBundle(filename) {
    // Note: filename allowed to be `null`
    var b = browserify(filename, {
      debug: (this.options.env !== 'production')
    });

    assetOptions.transform.forEach(function (t) {
      b.transform(t.options, t.fn, t.args);
    });

    assetOptions.require.forEach(function (req) {
      b.require(req.location, { expose: req.expose });
    });

    // resolve externals
    var assetNames = _.map(this.options.assets, 'name');
    var external = [];
    assetOptions.external.forEach(function (ext) {
      if (ext.type === 'bundle' && assetNames.indexOf(ext.name) > -1) {
        _.forEach(this.options.assets[assetNames.indexOf(ext.name)].require, function (req) {
          external.push(req.expose);
        });
      } else if (ext.type === 'module') {
        external.push(ext.name);
      }
    }.bind(this));
    external.forEach(function (name) {
      b.external(name);
    });

    return b.bundle()
      .on('error', function (err, e, f) {
        self.log('error bundle', err, err.message, e, f);
        if (!called) {
          called = true;
          done();
        }
        // end this stream
        this.end();
      });
  }.bind(this);

  if (assetOptions.entries && assetOptions.entries.length > 0) {

    var browserified = transform(function (filename) {
      return doBundle(filename);
    });

    gulp.src(assetOptions.entries)
      .pipe(plumber())
      .pipe(browserified)
      .pipe(concat(outputName))
      .pipe(contentHash.vinylFileHash(this, __hookAddAsset, assetOptions))
      .pipe(gulp.dest(this.options.destDir))
      .on('end', function () {
        if (!called) {
          called = true;
          done();
        }
      });

  } else {

    doBundle(null)
      .pipe(plumber())
      .pipe(source(outputName))
      .pipe(buffer())
      .pipe(concat(outputName))
      .pipe(contentHash.vinylFileHash(this, __hookAddAsset, assetOptions))
      .pipe(gulp.dest(this.options.destDir))
      .on('end', function () {
        if (!called) {
          called = true;
          done();
        }
      });
  }
};

Builder.prototype._shouldSkipHash = function (assetOptions) {
  return (this.options.skipHash === true || ((this.options.skipHash === null || typeof this.options.skipHash === 'undefined') && assetOptions.skipHash === true));
};

Builder.prototype.buildFolderAsset = function (_assetOptions, done) {
  var assetOptions = optionsParser.parseAssetOptions(this.options.baseDir, this._manifest.getAssetNames(), _assetOptions);

  var tempDist = path.join(this.options.destDir, ['_temp_', assetOptions.name].join(''));
  if (!fs.existsSync(assetOptions.folder)) {
    done();
    return;
  }
  var peckerObj = this;
  var hash = contentHash.createHash();
  var pattern = [];
  if (assetOptions.include.length > 0) {
    assetOptions.include.forEach(function (val) {
      pattern.push(path.join(assetOptions.folder, val));
    });
  } else {
    pattern.push(path.join(assetOptions.folder, '**/*.*'));
  }
  if (assetOptions.exclude.length > 0) {
    assetOptions.exclude.forEach(function (val) {
      pattern.push('!' + path.join(assetOptions.folder, val));
    });
  }
  gulp.src(pattern, {
    nosort: false // hash is dependent on file order, but sort is still not guaranteed 100%
  })
    .pipe(map(function (content) {
      hash.update(content);
      return content;
    }))
    .pipe(gulp.dest(tempDist))
    .on('end', function () {
      // generate folder name, depending on skipHash option
      var folderPath = path.join(this.options.destDir, assetOptions.name);
      if (!peckerObj._shouldSkipHash(assetOptions)) {
        var h = hash.digest('hex');
        folderPath = path.join(this.options.destDir, [assetOptions.name, '.', h].join(''));
      }
      if (fs.existsSync(folderPath)) {
        fs.removeSync(folderPath);
      }
      if (fs.existsSync(tempDist)) {
        fs.renameSync(tempDist, folderPath);
      }
      var val = path.join(this.options.baseUrl, path.basename(folderPath));
      this._manifest.addAsset(assetOptions.type, assetOptions.name, val, folderPath);
      done();
    }.bind(this));
};

Builder.prototype.buildFileAsset = function (_assetOptions, done) {
  var assetOptions = optionsParser.parseAssetOptions(this.options.baseDir, this._manifest.getAssetNames(), _assetOptions);

  // don't gulp-concat non-text files
  // if options.files returns multiple files, only one of the asset would referenced in manifest.json
  // TODO: investigate why gulp-concat seems to write additional data to images and such
  var skipConcat = [
    '.jpg',
    '.jpeg',
    '.gif',
    '.png',
    '.svg'
  ];
  var stream = gulp.src(assetOptions.files);

  // apply transform instructions
  for (var i = 0; i < assetOptions.transform.length; i++) {
    var t = assetOptions.transform[i];
    if (_.isString(t)) {
      t = {
        options: {},
        fn: t,
        args: {}
      };
    }

    if (_.isFunction(t)) {
      stream = stream.pipe(map(t));
    } else if (_.isPlainObject(t)) {
      var fn = TRANSFORMS_MAP[t.fn];
      if (!_.isFunction(fn)) {
        continue;
      }

      // Note: `concat` is a special built-in transform
      var args = (t.fn === 'concat') ? assetOptions.name : t.args;

      stream = stream.pipe(fn(args, this.options, assetOptions));
    }
  }

  if (skipConcat.indexOf(path.extname(assetOptions.name)) < 0) {
    stream = stream.pipe(concat(assetOptions.name));
  } else {
    stream = stream.pipe(rename(assetOptions.name));
  }

  stream
    .pipe(contentHash.vinylFileHash(this, __hookAddAsset, assetOptions))
    .pipe(gulp.dest(path.join(this.options.destDir)))
    .on('end', done);
};

Builder.prototype.buildUrlAsset = function (_assetOptions, done) {
  var assetOptions = optionsParser.parseAssetOptions(this.options.baseDir, this._manifest.getAssetNames(), _assetOptions);
  this._manifest.addAsset(assetOptions.type, assetOptions.name, assetOptions.url);
  done();
};

Builder.prototype.buildPackageAsset = function (assetOptions, done) {
  this._manifest.addAsset(assetOptions.type, assetOptions.name, assetOptions.assetNames);
  done();
};

Builder.prototype.buildPeckerClientFiles = function (done) {
  var assetOptions = {
    peckerPackage: {
      skipParseFns: ['name'],
      type: 'package',
      name: 'Pecker',
      assetNames: ['pecker.js', 'pecker-loader.js']
    },
    peckerJs: {
      skipParseFns: ['name', 'external', 'entries', 'require'],
      skipHash: false,
      type: 'browserify',
      name: 'pecker.js',
      entries: [],
      transform: [
        {
          options: {
            global: true
          },
          fn: 'uglifyify',
          args: {}
        }
      ],
      require: [
        {
          type: 'module',
          name: 'Pecker',
          expose: 'Pecker',
          location: path.join(__dirname, '/_pecker.js')
        }
      ]
    },
    peckerLoaderJs: {
      skipParseFns: ['name', 'external', 'entries', 'require'],
      type: 'file',
      name: 'pecker-loader.js',
      files: [path.join(__dirname, '/_pecker-loader.js')],
      transform: [
        function (content) {
          // bootstrap Pecker.init() payload
          var manifestContent = _.cloneDeep(this._manifest.read());
          // exclude pecker-loader asset in client-side because chicken-egg
          delete manifestContent.assets['pecker-loader.js'];
          delete manifestContent.assets.Pecker;
          var payload = {
            version: pkgInfo.version,
            manifest: manifestContent
          };
          content = content.toString().replace('/*DataTemplate*/', JSON.stringify(payload));
          return content;
        }.bind(this),
        {
          options: {},
          fn: 'uglify',
          args: {}
        }
      ]
    }
  };
  async.series([
    function buildPeckerPackage(next) {
      this.buildPackageAsset(assetOptions.peckerPackage, function () {
        next();
      });
    }.bind(this),
    function buildPeckerJs(next) {
      this.buildBrowserifyAsset(assetOptions.peckerJs, function () {
        next();
      });
    }.bind(this),
    function buildPeckerLoaderJs(next) {
      this.buildFileAsset(assetOptions.peckerLoaderJs, function () {
        next();
      });
    }.bind(this)
  ], function () {
    if (typeof done === 'function') {
      done();
    }
  });
};
/**
 * Director methods
 */

Builder.prototype.buildAssets = function (done) {

  var self = this;

  async.each(self.options.assets, function (assetOptions, callback) {
    switch (assetOptions.type) {
      case 'file':
        self.log('buildFileAsset start', assetOptions.name);
        self.buildFileAsset(assetOptions, function (err, results) {
          self.log('buildFileAsset done', assetOptions.name);
          callback(err, results);
        });
        break;
      case 'folder':
        self.log('buildFolderAsset start', assetOptions.name);
        self.buildFolderAsset(assetOptions, function (err, results) {
          self.log('buildFolderAsset done', assetOptions.name);
          callback(err, results);
        });
        break;
      case 'browserify':
        self.log('buildBrowserifyAsset start', assetOptions.name);
        self.buildBrowserifyAsset(assetOptions, function (err, results) {
          self.log('buildBrowserifyAsset done', assetOptions.name);
          callback(err, results);
        });
        break;
      // no build required for packages / urls
      case 'package':
        self.log('buildPackageAsset start', assetOptions.name);
        self.buildPackageAsset(assetOptions, function (err, results) {
          self.log('buildPackageAsset done', assetOptions.name);
          callback(err, results);
        });
        break;
      case 'url':
        self.log('buildUrlAsset start', assetOptions.name);
        self.buildUrlAsset(assetOptions, function (err, results) {
          self.log('buildUrlAsset done', assetOptions.name);
          callback(err, results);
        });
        break;
    }
  }, function (err) {
    if (err) {
      self.log('error', err);
      done(err, {
        config: self.options,
        manifest: self._manifest.read()
      });
      return;
    }
    self.buildPeckerClientFiles(function () {
      self.log('done');
      done(err, {
        config: self.options,
        manifest: self._manifest.read()
      });
    });
  });
};

Builder.prototype.watchAssets = function (options, done) {

  var self = this;

  options = _.assign({
    error: function () {},
    changed: function () {},
    complete: function () {}
  }, options);

  function onChanged(events) {
    if (_.isFunction(options.changed)) {
      options.changed(events);
    }
  }
  function onComplete(events) {
    if (_.isFunction(options.complete)) {
      options.complete(events);
    }
  }

  async.each(self.options.assets, function (assetOptions, callback) {
    if (!assetOptions.watch || assetOptions.watch.length <= 0) {
      return callback();
    }

    switch (assetOptions.type) {
      case 'file':
        watch(assetOptions.watch, {
          name: assetOptions.name
        }, function (events) {
          onChanged(events);
          self.buildFileAsset(assetOptions, function () {
            self.buildPeckerClientFiles(function () {
              self.log('buildFileAsset done', assetOptions.name);
              onComplete(events);
            });
          });
        });
        callback();
        break;
      case 'folder':
        watch(assetOptions.watch, {
          name: assetOptions.name
        }, function (events) {
          onChanged(events);
          self.buildFolderAsset(assetOptions, function () {
            self.buildPeckerClientFiles(function () {
              self.log('buildFolderAsset done', assetOptions.name);
              onComplete(events);
            });
          });
        });
        callback();
        break;
      case 'browserify':
        watch(assetOptions.watch, {
          name: assetOptions.name
        }, function (events) {
          onChanged(events);
          self.buildBrowserifyAsset(assetOptions, function () {
            self.buildPeckerClientFiles(function () {
              self.log('buildBrowserifyAsset done', assetOptions.name);
              onComplete(events);
            });
          });
        });
        callback();
        break;
      // no build required for packages / urls
      case 'package':
      case 'url':
        callback();
        break;
    }
  }, function (err) {
    if (err) {
      self.log('error', err);
    }
    self.log('done');
    if (_.isFunction(done)) {
      done();
    }
  });
};

/**
 * Helper/Getter methods
 */

Builder.prototype.getManifestFilePath = function () {
  if (!this._manifest) {
    // shouldn't happen if you guys didn't mess around with my private parts
    return null;
  }
  return this._manifest.filePath;
};

Builder.prototype.log = function () {
  if (this.options.silent === true) {
    return;
  }
  var args = Array.prototype.slice.call(arguments, 0);
  gutil.log(args.join(' '));
};

/**
 * setOptions Sets the options for Builder object.
 * Use this member method to modify / update the options. This replace the
 * previous `this.options` completely.
 * Do not modify `this.options` directly (treat it as immutable)
 * @param options
 */
Builder.prototype.setOptions = function (options) {
  this.options = optionsParser.parsePeckerOptions(options);
  this._manifest = new Manifest({ destDir: this.options.destDir });
  this._manifest.setValue('name', this.options.name);
  this._manifest.setValue('baseUrl', this.options.baseUrl);
};

module.exports = Builder;


text:
clients=1
members=3

gc_log="-Xloggc:gc.log -XX:+PrintGC -XX:+PrintGCDetails \
        -XX:+PrintGCTimeStamps  -XX:+PrintGCDateStamps"

jfr="-XX:+UnlockCommercialFeatures \
     -XX:+FlightRecorder \
     -XX:StartFlightRecording=duration=3600s,filename=recording.jfr,settings=upload/allocation.jfc \
     -XX:+UnlockDiagnosticVMOptions \
     -XX:+DebugNonSafepoints "

diagnostics="-Dhazelcast.diagnostics.enabled=true \
            -Dhazelcast.diagnostics.metric.level=debug \
            -Dhazelcast.diagnostics.metrics.period.seconds=5 \
            -Dhazelcast.diagnostics.max.rolled.file.size.mb=1000"

agent-ssh "sudo killall -9 java || true"

coordinator --duration 3m \
            --driver "hazelcast4" \
            --clients $clients \
            --clientType "javaclient" \
            --clientArgs "-Xms3g -Xmx3g $gc_log" \
            --members $members \
            --dedicatedMemberMachines $members \
            --memberArgs "-Xms3G -Xmx3G $gc_log \
                          -Dhazelcast.initial.min.cluster.size=$members" \
            test.properties

redpajama_set_name: RedPajamaGithub


text:
<?php

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;

abstract class MFController extends MFComponent
{

    private $_id;
    private $_action;
    private $_response;

    public function __construct($id)
    {
        $this->_id = $id;
        $this->_response = $this->createResponse();
    }

    protected function createResponse()
    {
        return new Response();
    }

    public function init()
    {
    }

    public function getId()
    {
        return $this->_id;
    }

    public function getAction()
    {
        return $this->_action;
    }

    public function setAction($action)
    {
        $this->_action = $action;
    }

    public function getResponse()
    {
        return $this->_response;
    }

    public function run($actionID)
    {
        try
        {
            if(($action = $this->createAction($actionID)) !== null)
                $this->runAction($action);
            else
                $this->missingAction($actionID);
        }
        catch(Exception $exception)
        {
            $this->_response = $this->handleException($exception);
        }
        return $this->_response;
    }

    public function runAction($action)
    {
        $priorAction = $this->_action;
        $this->_action = $action;
        $output = $action->runWithParams($this->getActionParams());
        if($output === false)
            $output = $this->invalidActionParams($action);
        if(is_a($output, 'Symfony\Component\HttpFoundation\Response'))
        {
            $this->_response = $output;
        }
        else
        {
            $this->setOutput($this->processOutput($output));
        }
        $this->_action = $priorAction;
    }

    public function setOutput($output)
    {
        $this->_response->setContent($output);
    }

    public function getActionParams()
    {
        return $_GET;
    }

    public function createAction($actionID)
    {
        if(method_exists($this, 'action'.$actionID) && strcasecmp($actionID, 's')) // we have actions method
            return new MFAction($this, $actionID);
        return null;
    }

    public function invalidActionParams($actionID)
    {
        throw new MFHttpException(400, MF::t('core', 'Your request is invalid.'));
    }

    public function missingAction($actionID)
    {
        throw new MFHttpException(404, MF::t('core', 'The system is unable to find the requested action "{action}".',
            array('{action}'=>$actionID)));
    }

    public function redirect($url, $statusCode=302, $headers=array())
    {
        return new RedirectResponse($url, $statusCode, $headers);
    }

    protected function processOutput($output)
    {
        return $output;
    }

    protected function handleException($exception)
    {
        throw $exception;
    }
}


text:
package com.fernandocejas.android10.sample.presentation.view.activity;

import android.animation.Animator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.fernandocejas.android10.sample.presentation.R;
import com.fernandocejas.android10.sample.presentation.internal.di.components.DaggerSearchActivityComponent;
import com.fernandocejas.android10.sample.presentation.model.ProductWrapperModel;
import com.fernandocejas.android10.sample.presentation.view.CircleAnimationUtil;
import com.fernandocejas.android10.sample.presentation.view.adapter.ProductListAdapter;
import com.jakewharton.rxbinding.widget.RxTextView;

import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observer;

public class SearchActivity extends BaseActivity {
    private final static int COLUMN_COUNT = 2;

    @BindView(R.id.search_edit_text)
    EditText searchEditText;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.products_list)
    RecyclerView productsList;
    @BindView(R.id.counter)
    TextView counter;
    @BindView(R.id.empty_view)
    View emptyView;
    @BindView(R.id.error_view)
    View errorView;
    @BindView(R.id.bcg)
    View bcg;
    @BindView(R.id.progress)
    ProgressBar progress;

    @Inject
    ProductListAdapter productListAdapter;
    @BindView(R.id.delete)
    ImageView delete;
    @BindView(R.id.action_shopping_cart)
    ImageView actionShoppingCart;

    public static Intent getCallingIntent(Context context) {
        return new Intent(context, SearchActivity.class);
    }

    @OnClick({R.id.delete, R.id.action_shopping_cart})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.delete:
                searchEditText.setText("");
                break;
            case R.id.action_shopping_cart:
                navigator.navigateToCart(this);
                break;
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateCartNumber();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        productsList.setLayoutManager(new GridLayoutManager(this, COLUMN_COUNT));
        productsList.setAdapter(productListAdapter);
        progress.getIndeterminateDrawable().setColorFilter(getPrimaryColor(), PorterDuff.Mode.SRC_IN);
        toolbar.setBackgroundColor(getAccentColor());
        bcg.setBackgroundColor(getBackgroundColor());
        productListAdapter.setOnItemClickListener(new ProductListAdapter.OnItemClickListener() {
            @Override
            public void onItemClicked(ProductWrapperModel categoryModel) {
                openProductDescription(categoryModel);
            }

            @Override
            public void onCartClicked(View addToCart, ProductWrapperModel productDescriptionModel) {
                String url = null;
                if (productDescriptionModel.getImages() != null) {
                    if (!productDescriptionModel.getImages().isEmpty()) {
                        if (productDescriptionModel.getImages().get(0) != null) {
                            url = productDescriptionModel.getImages().get(0).getUrl();
                        }
                    }
                }

                interactor.addProductToCart(productDescriptionModel.getProduct(), url);
                new CircleAnimationUtil().attachActivity(getActivity())
                        .setTargetView(addToCart)
                        .setMoveDuration(500)
                        .setDestView(counter)
                        .setAnimationListener(new Animator.AnimatorListener() {
                            @Override
                            public void onAnimationStart(Animator animation) {

                            }

                            @Override
                            public void onAnimationEnd(Animator animation) {
                                updateCartNumber();
                            }

                            @Override
                            public void onAnimationCancel(Animator animation) {

                            }

                            @Override
                            public void onAnimationRepeat(Animator animation) {

                            }
                        }).startAnimation();
            }
        });

        RxTextView.textChanges(searchEditText)
                .filter(s -> s.length() > 2)
                .doOnEach(notification -> {
                    emptyView.setVisibility(View.GONE);
                    errorView.setVisibility(View.GONE);
                    progress.setVisibility(View.VISIBLE);
                    productsList.setVisibility(View.GONE);
                })
                .debounce(500, TimeUnit.MILLISECONDS)
                .switchMap(charSequence -> interactor.searchForItems(charSequence.toString()))
                .subscribe(getObserver());
    }

    @Override
    protected void additionalCreateOperations() {
        DaggerSearchActivityComponent
                .builder()
                .view(this)
                .accentColor(getAccentColor())
                .primaryColor(getPrimaryColor())
                .textColor(getTextColor())
                .appComponent(getApplicationComponent())
                .build()
                .inject(this);
    }

    private Activity getActivity() {
        return this;
    }

    private void updateCartNumber() {
        counter.setText("" + interactor.getItemsNumberFromCart());
    }

    @NonNull
    private Observer<List<ProductWrapperModel>> getObserver() {
        return new Observer<List<ProductWrapperModel>>() {
            @Override
            public void onNext(List<ProductWrapperModel> value) {
                progress.setVisibility(View.GONE);
                setProductList(value);
            }

            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                progress.setVisibility(View.GONE);
                showError();
            }
        };
    }

    private void showError() {
        errorView.setVisibility(View.VISIBLE);
        errorView.setVisibility(View.VISIBLE);
    }

    private void showEmpty() {
        errorView.setVisibility(View.GONE);
        productsList.setVisibility(View.GONE);
        emptyView.setVisibility(View.VISIBLE);
    }

    private void setProductList(List<ProductWrapperModel> productList) {
        if (productList == null || productList.isEmpty()) {
            showEmpty();
        } else {
            productsList.setVisibility(View.VISIBLE);
            productListAdapter.setList(productList);
        }
    }

    private void openProductDescription(ProductWrapperModel productDescriptionModel) {
        navigator.navigateToProductDescription(this, productDescriptionModel.getProduct().getId());
    }

    @OnClick(R.id.try_again_button)
    void onTryAgain() {
        errorView.setVisibility(View.GONE);
        emptyView.setVisibility(View.GONE);
        interactor.searchForItems(searchEditText.getText().toString())
                .subscribe(getObserver());
    }
}


text:
package org.swcraft.springframework.core.configuration.xml;

import java.util.List;

public class SimpleMovieLister {

	// the SimpleMovieLister has a dependency on a MovieFinder
	private MovieFinder movieFinder;

	// a constructor so that the Spring container can inject a MovieFinder
	public SimpleMovieLister(MovieFinder movieFinder) {
		this.movieFinder = movieFinder;
	}

	public void listAll() {
		List<Movie> movies = movieFinder.findAll();
		movies.forEach(System.out::println);
	}
}


text:
class MapTasks < Volt::Task

  def getmaps
    url = 'http://splatoon.ink/schedule.json'
    resp = Net::HTTP.get_response(URI.parse(url))
    buffer = resp.body
    result = JSON.parse(buffer)
    $mapnames_current = []
    result['schedule'][0]['regular']['maps'].each do |item|
      $mapnames_current << item['nameEN']
    end
    result['schedule'][0]['ranked']['maps'].each do |item|
      $mapnames_current << item['nameEN']
    end
    $gamemode_current = result['schedule'][0]['ranked']['rulesEN']
  end

  def printmap(num)
    $mapnames_current[num]
  end

  def printmode
    $gamemode_current
  end

end


text:
The OpenCL integration with Stan is meant to be seamless and user friendly - setting a flag moves the computation of supported routines to the GPU, with no need to change Stan code. The API provides experts with a simple way of implementing their GPU kernels or to use existing GPU kernels as building blocks. In the below we detail the main pieces of the architecture and how to add your own OpenCL routines.

Stan's OpenCL backend uses a single context to receive data and routines from individual nodes in the expression tree. Ensuring there is only one context and queue per device for the life of the program makes context management simpler. The implementation of the OpenCL context which manages the device queue follows the Meyers singleton pattern and sits in the class `opencl_context_base`.

Instead of calling `opencl_context_base::getInstance().method()`, developers can access the context through a friend adapter class `opencl_context` which provides an API for accessing the base context. If the OpenCL implementation supports asynchronous operations, then the context asynchronously executes kernels. Asynchronous operations are particularly useful in conjunction with threading as the individual threads will be able to enqueue operations, which will execute while threads do other calculations using CPU.

## Matrices On The GPU

The base matrix class `matrix_cl` holds the device memory buffer, meta-information on the matrix, and methods for reading and writing event stacks for asynchronous computation. When a kernel receives a `matrix_cl`, the kernel's event is attached to the appropriate read or write event stack. Reading and writing to OpenCL buffers uses the generic `enqueueWriteBuffer` and `enqueueWriteBuffer` methods. Because Stan Math heavily relies on Eigen matrices, constructors and methods are available for passing data back and forth.

Developers can pass in Eigen matrices directly to the `matrix_cl` constructor or use the `to_matrix_cl()` or `from_matrix_cl()` methods.

```cpp

Eigen::MatrixXd m(2, 2);
m << 1, 2, 3, 4;

matrix_cl<double> A(m);
matrix_cl<double> B(2, 2);

B = to_matrix_cl(m);
Eigen::MatrixXd C = from_matrix_cl(B);
```

Similar constructors for the `matrix_cl` class are available for standard vectors `std::vector<T>` and arrays of doubles.

We can reduce the data transfers of triangular matrices by only transferring the non-zero parts of the matrix in a packed form. The kernel `unpack` deals with unpacking the packed form shown on the right-hand side on to a flat matrix shown on the left-hand side. For lower (upper) triangular matrices, the upper (lower) triangular fill with zeros. The kernel `pack` packs the flat matrix to packed form for the transfer back to the host's global memory.

```cpp
  matrix_cl<double> L = packed_copy(L_val_cpu, M_, matrix_view::Lower);
```

## Adding New OpenCL Kernels

The OpenCL specification demands that strings are used to represent OpenCL kernels. However, having a large number of files comprised of strings is unwieldy and difficult to maintain. Stan wraps its kernels inside of a STRINGIFY macro, which gives developers access to the standard set of developer tools such as code highlighting, linting, Doxygen, and auto-formatting. This style makes the kernel code easier to maintain compared to having files full of strings.

```cpp
const char *example_kernel_code = STRINGIFY(

  __kernel void example(double *A, double *B, int *val) {
  	  // kernel code...
  }

);

const kernel_cl<out_buffer, in_buffer, int> example(
  "example", example_kernel_code, {"THREAD_BLOCK_SIZE", 32);
```

In the above, a developer uses `STRINGIFY` to create a `const char*` that holds the kernel code. That string passes into the `kernel_cl` struct templated by the kernel argument types and with arguments giving the name of the kernel, the kernel code, and optional kernel macros they would like to have defined in the kernel.

Internally, we keep track of OpenCL events via queues on each `matrix_cl` object that we use to conservatively prevent race conditions and provide ordering where necessary. `out_buffer` and `in_buffer` are empty structs that we pass as template arguments to configure the kernel during construction to indicate the directionality of each input buffer. At runtime, the kernel will check the correct event queues on its arguments for events it needs to wait for and then attach the event representing the kernel's completion to each buffer's queues correctly. That way we ensure that an operation that, for example, writes to a buffer, is completed before we allow the OpenCL runtime to read from that buffer.

When the `kernel_cl` struct is constructed, it compiles the kernel and developers call the kernel with

```cpp
matrix_cl<double> foo = //...
matrix_cl<double> goo;
example(cl::NDRange(...), goo, foo, 10);
```

Depending on the`in/out_buffer` passed when constructing the kernel, events will be added to the appropriate `matrix_cl` read and/or write event stack. For instance, in the above, `goo` in the output and will have the kernel's event attached to it's `write_stack`. While `foo` will have the kernel's event attached to it's `read_stack`. Later kernel calls that write to `foo` will know to wait for all the event's in `foo`'s `read_stack` and `write_stack` while kernels that use `goo` as input will know to wait for the event's in `goo`'s `write_stack`.


text:
<?php

namespace PostNL\Data;

use PostNL\Mapping\MappingGenerator;

/**
 * Rembours object.
 */
class Rembours extends MappingGenerator
{
    /**
     * Mapping array waarin wordt aangegeven welke getter overeenkomt
     * met welke veldcode. Definieert tevens de volgorde.
     *
     * @var array
     */
    protected $mapping = [
        'A228' => 'IBAN',
        'A229' => 'BIC'
    ];

    /**
     * IBAN rekeningnummer van de verzender.
     *
     * @var string
     */
    protected $IBAN;

    /**
     * BIC code van de verzender.
     *
     * @var string
     */
    protected $BIC;

    /**
     * Getter voor het IBAN rekeningnummer.
     *
     * @return string
     */
    protected function getIBAN()
    {
        return $this->IBAN;
    }

    /**
     * Getter voor de BIC code.
     *
     * @return string
     */
    protected function getBIC()
    {
        return $this->BIC;
    }

    /**
     * Stel het IBAN rekeningnummer in van de verzender.
     *
     * @param  string $IBAN
     * @return \PostNL\Data\Rembours
     */
    public function setIBAN($IBAN)
    {
        // @todo check op geldige IBAN code
        $this->IBAN = $IBAN;
        return $this;
    }

    /**
     * Stel het BIC nummer in van de verzender.
     *
     * @param  string $BIC
     * @throws \Exception
     * @return \PostNL\Data\Rembours
     */
    public function setBIC($BIC)
    {
        if (strlen($BIC) < 8 || strlen($BIC) > 11) {
            throw new \Exception('Ongeldige BIC-code.');
        }

        $this->BIC = $BIC;
        return $this;
    }

    /**
     * Valideer de ingevoerde gegevens voordat de mapping wordt toegepast om
     * output te genereren.
     *
     * @throws \Exception
     */
    protected function validate()
    {
        $mandatory = ['IBAN', 'BIC'];
        foreach ($mandatory as $property) {
            if (empty($this->$property)) {
                throw new \Exception(
                    'Verplichte property niet gevuld: ' . $property
                );
            }
        }
    }
}


text:
<!DOCTYPE html>

    {% include head.html %}

    {% include nav.html %}

      {{ content }}

    {% include js.html %}


text:
layout: post
title: 7 reasons to use Yeoman's angular-fullstack generator
date: 2014-10-18 12:17
tags:
- javascript
- angular
- mean
- yeoman
---
For my next project and, after looking for candidates and reading some hundreds of lines of documentation, I finally choose to work with the so called MEAN stack: mongodb, express, angular and node.

As with any other technology ecosystem, the great number of frameworks, libraries and tools can make our choice a challenge, and JavaScript is not an exception. But for JavaScript projects we have lot of help and I decide to use the awesome [Yeoman](http://yeoman.io/) tool. Yeoman combines the power of [grunt](http://gruntjs.com/), [bower](http://bower.io/), [npm](https://www.npmjs.org/) and adds its own salt: the generators.

> Yeoman generators are tasks responsible to build the initial project scaffolding.

Yeoman offers an extensive set of official generators oriented to create: webapps, backbone app, chrome extension, etc but we can also found a myriad of non official generators (yes, because anyone can create a new generator to satisfy his/her needs).

Within all the generators I chose [angular-fullstack](https://github.com/DaftMonk/generator-angular-fullstack) to create my MEAN project structure and next are my reasons:

## 1. Easy to install

You require to have [node](http://nodejs.org/) and [npm](https://www.npmjs.org/) installed on your system. Once you have them install[Yeoman](http://yeoman.io/) and the [angular-fullstack](https://github.com/DaftMonk/generator-angular-fullstack) is as easy as:

$ npm install -g yo
$ npm install -g generator-angular-fullstack

Once installed the generator you simply need to create a new folder and initialise your project:

{% highlight bash %}
> mkdir my-new-project && cd $_
> yo angular-fullstack [app-name]
{% endhighlight %}

## 2. Creates both client and server scaffoldings

The generator generates the _full stack_ of your project, both the client and server code. Your project will start well organised and prepared to create an awesome RIA application.

## 3. Introduces good practices in the generated code

Because the generated is made by experienced developers, they applies good practices in code organisation and style programming (like the environment configuration on the server side using node).

For me, this is one of the most important reasons to use this generator. Anybody knows starting with a new technology is always hard, but it is nothing when you start with four new technologies :)

## 4. Server side API prepared to use authentication

Following best practices the code is prepared so you can easily add security to you API via a node middleware so each request requires authentication of the client side.

## 5. Support HTML or jade templating on client side

You can use any template engine for client side but by default the generator works with HTML and Jade. I don't really like Jade too much so I always try to use EJS or similar (_Warning this last sentence is the author's opinion_).

## 6. Support for different CSS preprocessors

For different opinions there are different alternatives. This way [angular-fullstack](https://github.com/DaftMonk/generator-angular-fullstack) has support for plain CSS, [Stylus](http://learnboost.github.io/stylus/), [Sass](http://sass-lang.com/) or [LESS](http://lesscss.org/) pre-processors. Choose your preferred.

## 7. Commands to scaffold anything

With the[angular-fullstack](https://github.com/DaftMonk/generator-angular-fullstack) you can create new end points for the server side or client side components (like routes, controllers, services, filters, directives, ...) with a sentences. So, next command:

{% highlight bash %}
>yo angular-fullstack:endpoint message
[?] What will the url of your endpoint to be? /api/messages
{% endhighlight %}

will produce:

{% highlight bash %}
server/api/message/index.js
server/api/message/message.spec.js
server/api/message/message.controller.js
server/api/message/message.model.js  (optional)
server/api/message/message.socket.js (optional)
{% endhighlight %}

##  Conclusion

In my opinion, [angular-fullstack](https://github.com/DaftMonk/generator-angular-fullstack) is a really powerful tool that simplifies our day to day work.

As always it is not the panacea, it is simply a generic tool to automatize many common tasks. Because of this we can found situations it lacks some feature.


text:
<?php

namespace Lokos\ShopBundle\Form\Fields;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * ImageType
 *
 * @package    Mindk\PublishBundle\Form\Fields
 */
class ExtendedCollectionType extends AbstractType
{

    /**
     * @inheritdoc
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(
            array(
                'extended_data' => array(),
            )
        );
    }

    /**
     * @inheritdoc
     */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        parent::buildView($view, $form, $options);

        $view->vars['extended_data'] = $options['extended_data'];
    }

    /**
     * @inheritdoc
     */
    public function getParent()
    {
        return CollectionType::class;
    }

    /**
     * @inheritdoc
     */
    public function getBlockPrefix()
    {
        return 'ExtendedCollection';
    }
}


text:
namespace EDSLot
{
        using System;
        using System.Collections.Generic;
        using System.ServiceModel;
        using System.Runtime.Serialization;

        [DataContract]
        public partial class Record_MCCB:Record
        {
        }
}


text:
调用方式:createStore(reducer, [initialState])

创建一个 Redux store 来以存放应用中所有的 state,应用中应有且仅有一个 store。
这个API返回一个store,这个store中保存了应用所有 state 的对象。改变 state 的惟一方法是 dispatch action。你也可以 subscribe 监听 state 的变化,然后更新 UI。我们来看一个示例

**我们可以试着模拟 createStore,深入了解其原理**

```
// reducer 纯函数,具体的action执行逻辑
const counter = (state = 0, action) => {
  switch (action.type) {
      case 'INCREMENT':
        return state + 1;
      case 'DECREMENT':
        return state - 1;
      default:
        return state;
  }
}

// 模拟create store,了解其原理
const createStore = (reducer) => {
  let state;
  let listeners = [];

  const getState = () => state;

  const dispatch = (action) => {
    state = reducer(state, action);
    listeners.forEach(listener => listener());
  }

  const subscribe = (listener) => {
      listeners.push(listener);
      return () => {
        listeners = listeners.filter(item => item !== listener);
      }
  }

  dispatch({});

  return { getState, dispatch, subscribe };
}

const store = createStore(counter);

// view 对应到React里面的component
const PureRender = () => {
  document.body.innerText = store.getState();
}

// store subscribe 订阅或是监听view(on)
store.subscribe(PureRender);
PureRender();

document.addEventListener('click', function( e ){
  // store dispatch 调度分发一个 action(fire)
  store.dispatch({ type: 'DECREMENT'});
})

```

### combineReducers

调用方式:combineReducers(reducers)

随着应用变得复杂,需要对 reducer 函数进行拆分,拆分后的每一块独立负责管理 state 的一部分。把一个由多个不同 reducer 函数作为 value 的 object,合并成一个最终的 reducer 函数,然后就可以对这个 reducer 调用 createStore。

**示例如下**

代码清单:`reducer/todos.js`
```
export default function todos(state = [], action) {
  switch (action.type) {
  case 'ADD_TODO':
    return state.concat([action.text])
  default:
    return state
  }
}
```

代码清单:`reducer/counter.js`
```
export default function counter(state = 0, action) {
  switch (action.type) {
  case 'INCREMENT':
    return state + 1
  case 'DECREMENT':
    return state - 1
  default:
    return state
  }
}
```

代码清单:`reducers/index.js`
```
import { combineReducers } from 'redux'
import todos from './todos'
import counter from './counter'

export default combineReducers({
  todos,
  counter
})
```

代码清单:`App.js`
```
import { createStore } from 'redux'
import reducer from './reducer/index.js'

let store = createStore(reducer)
console.log('当前的 state :', store.getState())

store.dispatch({
  type: 'ADD_TODO',
  text: 'Use Redux'
})
store.dispatch({
  type: 'INCREMENT',
})
console.log('改变后的 state :', store.getState())

```

### applyMiddleware

调用方式:applyMiddleware(...middlewares)

使用包含自定义功能的 middleware 来扩展 Redux 是一种推荐的方式。Middleware 可以让你包装 store 的 dispatch 方法来达到你想要的目的。同时, middleware 还拥有"可组合"这一关键特性。多个 middleware 可以被组合到一起使用,形成 middleware 链。其中,每个 middleware 都不需要关心链中它前后的 middleware 的任何信息。

具体用法我们高级部分详细说明。

### bindActionCreators

调用方式:bindActionCreators(actionCreators, dispatch)

惟一使用 bindActionCreators 的场景是当你需要把 action creator 往下传到一个组件上,却不想让这个组件觉察到 Redux 的存在,而且不希望把 Redux store 或 dispatch 传给它。

具体用法我们高级部分详细说明。

### compose

调用方式:compose(...functions)

compose 用来实现从右到左来组合传入的多个函数,它做的只是让你不使用深度右括号的情况下来写深度嵌套的函数,仅此而已。


text:
<?php

namespace MicroCore\Components;

use Psr\Http\Message\ServerRequestInterface as RequestInterface;
use Psr\Http\Message\ResponseInterface;

interface ActionInterface
{
    /**
     * @param RequestInterface $request
     * @param ResponseInterface $response
     * @return ResponseInterface
     */
    public function __invoke(RequestInterface $request, ResponseInterface $response);
}


text:
namespace RavenAdminLogsCollectionTool.Services
{
    public interface IDialogService
    {
        void ShowMessage(string message, string caption = "Information");
        void ShowErrorMessage(string message, string caption = "Error");
    }
}


text:
module Tinkit
  @@top = File.join(File.dirname(__FILE__), '../..')  #main bufs directory
  @@lib = File.join(@@top, 'lib/')
  @@helpers = File.join(@@top, 'lib/helpers/')
  @@moabs = File.join(@@lib, 'moabs')
  @@midas = File.join(@@lib, 'midas')
  @@glue = File.join(@@lib, 'glue_envs')
  @@specs = File.join(@@top, 'spec')
  @@spec_helpers = File.join(@@specs, 'helpers')
  @@fixtures = File.join(@@top, 'bufs_fixtures')

  def self.lib(req_file)
    File.expand_path(File.join(@@lib, req_file))
  end

  def self.helpers(req_file)
    File.expand_path(File.join(@@helpers, req_file))
  end

  def self.spec(req_file)
    File.expand_path(File.join(@@specs, req_file))
  end

  def self.spec_helpers(req_file)
    File.expand_path(File.join(@@spec_helpers, req_file))
  end

  def self.fixtures(req_file)
    File.expand_path(File.join(@@fixtures, req_file))
  end

  def self.moabs(req_file)
    File.expand_path(File.join(@@moabs, req_file))
  end

  def self.midas(req_file)
    File.expand_path(File.join(@@midas, req_file))
  end

  def self.glue(req_file)
    File.expand_path(File.join(@@glue, req_file))
  end
end


text:
package net.sourceforge.ganttproject.time;

import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 * @author bard
 * Date: 31.01.2004
 */
public interface TimeUnit {
    public String getName();
    public boolean isConstructedFrom(TimeUnit unit);
    public int getAtomCount(TimeUnit atomUnit);
    public TimeUnit getDirectAtomUnit();
    public int DAY = 0;
    //
    public void setTextFormatter(TextFormatter formatter);
    public String format(Date baseDate);
}


text:
package me.jaredhewitt.skindepot.mixin;

import com.mojang.authlib.GameProfile;
import com.mojang.authlib.minecraft.MinecraftProfileTexture.Type;

import me.jaredhewitt.skindepot.HDSkinManager;
import net.minecraft.client.renderer.tileentity.TileEntitySkullRenderer;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.tileentity.TileEntitySkull;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;

import java.util.Optional;

@Mixin(TileEntitySkullRenderer.class)
public abstract class MixinSkullRenderer extends TileEntitySpecialRenderer<TileEntitySkull> {

    @Redirect(
            method = "renderSkull",
            at = @At(
                    value = "INVOKE",
                    target = "Lnet/minecraft/client/renderer/tileentity/TileEntitySkullRenderer;bindTexture(Lnet/minecraft/util/ResourceLocation;)V",
                    ordinal = 4))
    private void onBindTexture(TileEntitySkullRenderer tesr, ResourceLocation rl, float x, float y, float z, EnumFacing facing, float rotation, int meta,
                               GameProfile profile, int p_180543_8_, float ticks) {
        if (profile != null) {
            Optional<ResourceLocation> skin = HDSkinManager.INSTANCE.getSkinLocation(profile, Type.SKIN, true);
            if (skin.isPresent())
                // rebind
                this.bindTexture(skin.get());
            else
                this.bindTexture(rl);
        } else
            this.bindTexture(rl);
    }
}


text:
using System.Collections.Generic;
using System.IO;
using DNS.Protocol;
using DNS.Protocol.ResourceRecords;

namespace Stratis.Bitcoin.Features.Dns
{
    /// <summary>
    /// This interface defines a DNS masterfile used to cache the whitelisted peers discovered by the DNS Seed service.
    /// </summary>
    public interface IMasterFile
    {
        /// <summary>
        /// Gets a list of resource records that match the question.
        /// </summary>
        /// <param name="question">The question to ask of the masterfile.</param>
        /// <returns>A list of resource records.</returns>
        IList<IResourceRecord> Get(Question question);

        /// <summary>
        /// Loads the saved masterfile from the specified stream.
        /// </summary>
        /// <param name="stream">The stream containing the masterfile.</param>
        void Load(Stream stream);

        /// <summary>
        /// Saves the cached masterfile to the specified stream.
        /// </summary>
        /// <param name="stream">The stream to write the masterfile to.</param>
        void Save(Stream stream);

        /// <summary>
        /// Seeds the masterfile with the SOA and NS DNS records with the DNS specific settings.
        /// </summary>
        void Seed(DnsSettings dnsSettings);
    }
}


text:
package com.springboot.spark.starter.basic.rdd;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Map;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.Optional;
import org.apache.spark.api.java.function.PairFunction;

import scala.Tuple2;

/**
 */
public class PairRDDleftOuterJoin implements Serializable {

  private static final long serialVersionUID = 5924321403879655951L;

  private final static SparkConf sparkConf = new SparkConf() //
      .setAppName(PairRDDleftOuterJoin.class.getName()) //
      .setMaster("local") //
  ; //

  public final static JavaSparkContext sc = new JavaSparkContext(sparkConf);

  public void using() {
    // Create PairRDD
    JavaRDD<String> rdd = sc.parallelize(Arrays.asList("1", "2", "3", "4", "5", "3", "4"));
    // A function that returns key-value pairs (Tuple2<K, V>), and can be used
    // to construct PairRDDs.
    // 第一个为target,第二个为key,第三个为value。
    PairFunction<String, String, Integer> keyData = new PairFunction<String, String, Integer>() {
      private static final long serialVersionUID = 4172878058463748739L;

      @Override
      public Tuple2<String, Integer> call(String x) throws Exception {
        return new Tuple2<String, Integer>(x, Integer.valueOf(x) * -1);
      }
    };
    JavaPairRDD<String, Integer> javaPairRDD = rdd.mapToPair(keyData);
    JavaPairRDD<String, Integer> javaPairRDD2 = sc.parallelize(Arrays.asList("3", "4", "5"))
        .mapToPair(new PairFunction<String, String, Integer>() {
          private static final long serialVersionUID = 8598252966534641094L;

          @Override
          public Tuple2<String, Integer> call(String x) throws Exception {
            return new Tuple2<String, Integer>(x, Integer.valueOf(x) * 3);
          }
        });
    // Return the key-value pairs in this RDD to the master as a Map.
    Map<String, Integer> map = javaPairRDD.collectAsMap();
    System.err.println("javaPairRDD.mapToPair()=>");
    System.err.println(map);

    // leftOuterJoin类似于SQL中的左外关联left outer
    // join,返回结果以前面的RDD为主,关联不上的记录为空。只能用于两个RDD之间的关联,如果要多个RDD关联,多关联几次即可。
    // 参数numPartitions用于指定结果的分区数
    // 参数partitioner用于指定分区函数
    JavaPairRDD<String, Tuple2<Integer, Optional<Integer>>> leftOuterJoin = javaPairRDD.leftOuterJoin(javaPairRDD2);
     System.err.println(leftOuterJoin.collect());
    // [(4,(-4,Optional[12])), (4,(-4,Optional[12])), (5,(-5,Optional[15])), (2,(-2,Optional.empty)), (3,(-3,Optional[9])), (3,(-3,Optional[9])), (1,(-1,Optional.empty))]
  }

  public static void main(String[] args) {
    new PairRDDleftOuterJoin().using();
    sc.close();
  }

}


text:
<?php

use App\Models\Ability;
use Illuminate\Database\Seeder;

class AbilitiesTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        //Test abilities
        factory(Ability::class)->create();
        factory(Ability::class)->create(['key' => 'test-ability2']);
        factory(Ability::class)->create(['key' => 'test-ability3']);
    }
}


text:
var expect = require('chai').expect;
var assert = require('chai').assert;

var fs = require("fs");

var hl7 = require("../index.js");

describe('parse.js test', function () {
    var data = "";

    before(function () {
        data = fs.readFileSync('./test/fixtures/isabella_jones_lipid_panel.txt').toString().split("\n").join("\r");

    });

    it('should parse an HL7 string without error', function () {
        assert.notStrictEqual(undefined, hl7.parseString(data));
    });

    it('parses fields with the correct mapping', function () {
        var parsed = hl7.parseString(data);

        assert.equal('JONES', parsed[1][5][0][0]); // parsed[SEGMENT][FIELD][FIELDREPEAT][COMPONENT]
        assert.equal('ISABELLA', parsed[1][5][0][1]);
    });

    it('translates HL7 sequence number to element name', function () {
        var tr = hl7.translate(hl7.parseString(data));

        assert.equal('PID', tr[1]["Segment"]);
        assert.equal('JONES', tr[1]['Patient Name'][0][0]);
        assert.equal('ISABELLA', tr[1]['Patient Name'][0][1]);
    });

    it('serializes parsed HL7 to a string', function () {
        var serialized = hl7.serializeJSON(hl7.parseString(data));

        assert.equal(data, serialized);
    });

    it('correctly interprets the FIELDREPEAT character', function () {
        var parsed = hl7.parseString(data);

        assert.equal('185L29839X64489JLPF', parsed[3][3][0][0]);
        assert.equal('X64489', parsed[3][3][1][0]);
    });
});


text:
require_relative './../../../spec_helper'

describe 'oneview_test::logical_interconnect_update_telemetry_configuration' do
  let(:resource_name) { 'logical_interconnect' }
  include_context 'chef context'

  # Mocks the update_handler
  before(:each) do
    allow_any_instance_of(OneviewSDK::LogicalInterconnect).to receive(:exists?).and_return(true)
    allow_any_instance_of(OneviewSDK::LogicalInterconnect).to receive(:retrieve!).and_return(true)
    allow_any_instance_of(OneviewSDK::LogicalInterconnect).to receive(:like?).and_return(false)
  end

  it 'updates telemetry configuration' do
    expect_any_instance_of(OneviewSDK::LogicalInterconnect).to receive(:update_telemetry_configuration).and_return(true)
    expect(real_chef_run).to update_oneview_logical_interconnect_telemetry_configuration('LogicalInterconnect-update_telemetry_configuration')
  end
end


text:
<script src='{{ site.url }}/js/jquery.min.js'></script>
<script src='{{ site.url }}/js/foundation.min.js'></script>
<script src='{{ site.url }}/js/jquery.countTo.js'></script>
<script src='{{ site.url }}/js/jquery.appear.js'></script>
<script src='{{ site.url }}/js/app.js'></script>


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Return.cs" company="Tyson J. Hayes">
//   © 2014 - Refer to the License.md for the project.
// </copyright>
// <summary>
//   The object that is returned when a request is made for a thing.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace BGGAPI.Thing
{
    using System.Collections.Generic;

    /// <summary>
    /// The object that is returned when a request is made for a thing.
    /// </summary>
    public class Return : Shared.IReturn
    {
        /// <summary>
        /// Gets or sets the items.
        /// </summary>
        public List<Item> Items { get; set; }

        public int TotalItems { get; set; }
        public string TermsOfUse { get; set; }
    }
}


text:
$('#name').blur(function(){
    // =============================
    // variables
    // =============================
    // obtenemos el name
    var name   = $('#name');
    var submit  = $('#submit');
    var idError = 'error-name';

    // =============================
    // lógica
    // =============================
    // Si el name está vacio
    if(!validaciones.isEmpty(name, idError, 'empty', 'name')){
        result = (validaciones.submitDisable(submit)) ? false : true;
        return result;
    } else if (!validaciones.objectShortLength(name, idError, 'short', 'nombre', 2)){
        result = (validaciones.submitDisable(submit)) ? false : true;
        return result;
    } else if (!validaciones.objectHighLength(name, idError, 'long', 'nombre', 40)){
        result = (validaciones.submitDisable(submit)) ? false : true;
        return result;
    } else if (!validaciones.objectValid(name, idError, 'name', 'nombre', 'regexName')) {
        result = (validaciones.submitDisable(submit)) ? false : true;
        return result;
    } else {
        // realizamos el saneamiento del campo
        name.text($.trim(name.val()));
        // invertimos el resultado
        result = (validaciones.submitEnable(submit)) ? true : false;
        return result;
    }
})// Validar #name

// código para resetear los errores del name
$('#name').focus(function(){
    var submit = $('#submit');
    validaciones.submitDisable(submit);
    var idError = 'error-name';
    var name = $('#' + idError);
    var errorName = $('#' + idError);
    if(errorName){
        errorName.fadeOut("fast");
    }
    name.removeClass('invalid');
})// resetear name


text:
from django.middleware.csrf import get_token
from django.template.loader import render_to_string
from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic.base import (View, TemplateResponseMixin)

from django_modalview.generic.component import (ModalButton, GET_TEMPLATE,
                                                GET_TEMPLATE_CONTENT,
                                                BASE_TEMPLATE)
from django_modalview.generic.response import (ModalJsonResponse,
                                               ModalJsonResponseRedirect)

class ModalContextMixin(object):

    """
            A default modal context mixin that passes the keyword arguments
            received by get_context_modal_data as the modal template context.
    """

    def get_context_data(self, **kwargs):
        if 'view' not in kwargs:
            kwargs['view'] = self
        return kwargs

    def __init__(self, title=None, description=None, icon=None, *args,
                 **kwargs):
        super(ModalContextMixin, self).__init__(*args, **kwargs)
        self.title = "title"
        self.response = None
        self.icon = icon
        self.description = ""
        self.close_button = ModalButton('Close', button_type='primary')
        self.content_template_name = None
        self.base_template_name = BASE_TEMPLATE
        # use to know if you can redirect. Disable for the first request.

    def _generate_modal_context(self):
        return {
            'title': self.title,
            'description': self.description,
            'button_close': self.close_button,
            'content_template_name': self.content_template_name,
            'base_template_name': self.base_template_name,
            'icon': self.icon,
            'response': self.response,
        }

    def get_context_modal_data(self, **kwargs):
        kwargs.update(self._generate_modal_context())
        return kwargs

class ModalView(View):

    """
            Parent class of all the ModalView. Extends the Django generic View
            to override the dispatch method and to overload the get method.
    """

    def __init__(self, *args, **kwargs):
        super(ModalView, self).__init__(*args, **kwargs)
        self.is_ajax = False
        self._can_redirect = False
        self.redirect_to = None

    def can_redirect(self):
        return self._can_redirect and self.redirect_to

    def dispatch(self, request, *args, **kwargs):
        self.is_ajax = request.is_ajax()
        return super(ModalView, self).dispatch(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        context = self.get_context_modal_data(**kwargs)
        return self.render_to_response(
            context=context
        )

class ModalTemplateMixin(TemplateResponseMixin):

    """
            Mixin use to render a template. A modal view can be called by a
            simple Http request or by an Ajax request. The type of the response
            is different for these two cases.
    """
    json_response_class = ModalJsonResponse
    json_response_redirect_class = ModalJsonResponseRedirect
    http_response_class = HttpResponse
    http_response_redirect_class = HttpResponseRedirect

    def _valid_template(self):
        if not self.is_ajax:
            self.template_name = GET_TEMPLATE

    def _get_content(self, context):
        """
                Add the csrf_token_value because the mixin use render_to_string
                and not render.
        """
        self._valid_template()
        context.update({
            "csrf_token_value": get_token(self.request)
        })
        return render_to_string(self.get_template_names(), context)

    def get_response(self):

        if self.is_ajax:
            if not self.can_redirect():
                return self.json_response_class
            else:
                return self.json_response_redirect_class
        else:
            if not self.can_redirect():
                return self.http_response_class
            else:
                return self.http_response_redirect_class

    def render_to_response(self, context):
        ResponseClass = self.get_response()
        if not self.can_redirect():
            context.update(self.get_context_data())
            return ResponseClass(self._get_content(context))
        else:
            return ResponseClass(self.redirect_to)

class ModalUtilMixin(object):

    """
            Mixin that permit to launch a method with a modal button.
    """

    def __init__(self, *args, **kwargs):
        super(ModalUtilMixin, self).__init__(*args, **kwargs)
        self.util_kwargs = {}

    def get_util(self, func_name, *args, **kwargs):
        if hasattr(self, func_name):
            util_kwargs = self.get_util_kwargs(**kwargs)
            getattr(self, func_name)(*args, **self.util_kwargs)
        else:
            raise Exception("You should implement one method name"
                            " {name}!".format(name=func_name))

    def get_util_kwargs(self, *args, **kwargs):
        kwargs.update(self.request.GET)
        self.util_kwargs.update(**kwargs)

class BaseModalView(ModalContextMixin, ModalView):

    """
            A base view to handle a simple modal
    """

    def __init__(self, *args, **kwargs):
        super(BaseModalView, self).__init__(*args, **kwargs)
        self.template_name = GET_TEMPLATE
        self.content_template_name = GET_TEMPLATE_CONTENT

class ModalTemplateView(ModalTemplateMixin, BaseModalView):

    """
            A view that display a simple modal
    """

class ModalTemplateUtilView(ModalUtilMixin, ModalTemplateView):

    """
            A view that display a modal and that is able to handle an util method.
            A new button is displayed in the modal to run the tool.
    """

    def __init__(self, button=None, *args, **kwargs):
        super(ModalTemplateUtilView, self).__init__(*args, **kwargs)
        self.util_button = button if button else ModalButton('Run test')
        self.util_name = 'util'

    def dispatch(self, request, *args, **kwargs):
        self.util_button.url = request.META['PATH_INFO'] + '?util=true'
        return super(ModalTemplateUtilView, self).dispatch(request, *args,
                                                           **kwargs)

    def get_context_modal_data(self, **kwargs):
        kwargs.update({
            'util_button': self.util_button
        })
        return super(ModalTemplateUtilView,
                     self).get_context_modal_data(**kwargs)

    def get(self, request, *args, **kwargs):
        get_dict = self.request.GET
        if get_dict.get('util'):
            self._can_redirect = True
            self.get_util(self.util_name, **self.kwargs)
            self.template_name = self.content_template_name

        return super(ModalTemplateUtilView, self).get(request, *args,
                                                      **kwargs)


text:
// =========================================================================== //
//                                                                             //
// Copyright 2008-2011 Andrew Casey, Jun Li, Jesse Doherty,                    //
//   Maxime Chevalier-Boisvert, Toheed Aslam, Anton Dubrau, Nurudeen Lameed,   //
//   Amina Aslam, Rahul Garg, Soroush Radpour, Olivier Savary Belanger,        //
//   Laurie Hendren, Clark Verbrugge and McGill University.                    //
//                                                                             //
//   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.                                            //
//                                                                             //
// =========================================================================== //

package natlab;

public class TypeInferException extends RuntimeException {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	public Object node;
	public TypeInferException() {
		// TODO Auto-generated constructor stub
	}

	public TypeInferException(String arg0) {
		super(arg0);
		// TODO Auto-generated constructor stub
	}

	public TypeInferException(Throwable arg0) {
		super(arg0);
		// TODO Auto-generated constructor stub
	}

	public TypeInferException(String arg0, Throwable arg1) {
		super(arg0, arg1);
		// TODO Auto-generated constructor stub
	}
	// Passing some object back, such as node pointer,
	public TypeInferException(String arg0, Object node) {
		super(arg0);
		this.node = node;
	}
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycologia 39(2): 152 (1947)

#### Original name
Chytriomyces spinosus Fay, 1947

### Remarks
null


text:
package org.apache.shardingsphere.data.pipeline.api.impl;

import com.google.common.collect.ImmutableMap;
import lombok.SneakyThrows;
import org.apache.shardingsphere.data.pipeline.api.PipelineJobAPIFactory;
import org.apache.shardingsphere.data.pipeline.api.RuleAlteredJobAPI;
import org.apache.shardingsphere.data.pipeline.api.check.consistency.DataConsistencyCheckResult;
import org.apache.shardingsphere.data.pipeline.api.config.rulealtered.JobConfiguration;
import org.apache.shardingsphere.data.pipeline.api.config.rulealtered.PipelineConfiguration;
import org.apache.shardingsphere.data.pipeline.api.datasource.config.PipelineDataSourceConfiguration;
import org.apache.shardingsphere.data.pipeline.api.datasource.config.PipelineDataSourceConfigurationFactory;
import org.apache.shardingsphere.data.pipeline.api.job.progress.JobProgress;
import org.apache.shardingsphere.data.pipeline.api.pojo.DataConsistencyCheckAlgorithmInfo;
import org.apache.shardingsphere.data.pipeline.api.pojo.JobInfo;
import org.apache.shardingsphere.data.pipeline.core.datasource.creator.PipelineDataSourceCreatorFactory;
import org.apache.shardingsphere.data.pipeline.core.fixture.EmbedTestingServer;
import org.apache.shardingsphere.data.pipeline.core.fixture.FixtureDataConsistencyCheckAlgorithm;
import org.apache.shardingsphere.data.pipeline.core.util.PipelineContextUtil;
import org.apache.shardingsphere.data.pipeline.core.util.ResourceUtil;
import org.junit.BeforeClass;
import org.junit.Test;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

public final class RuleAlteredJobAPIImplTest {

    private static RuleAlteredJobAPI ruleAlteredJobAPI;

    @BeforeClass
    public static void beforeClass() {
        EmbedTestingServer.start();
        PipelineContextUtil.mockModeConfig();
        ruleAlteredJobAPI = PipelineJobAPIFactory.getRuleAlteredJobAPI();
    }

    @Test
    public void assertStartAndList() {
        Optional<String> jobId = ruleAlteredJobAPI.start(ResourceUtil.mockJobConfig());
        assertTrue(jobId.isPresent());
        JobInfo jobInfo = getNonNullJobInfo(jobId.get());
        assertTrue(jobInfo.isActive());
        assertThat(jobInfo.getTables(), is("t_order"));
        assertThat(jobInfo.getShardingTotalCount(), is(1));
        List<Long> uncompletedJobIds = ruleAlteredJobAPI.getUncompletedJobIds("logic_db");
        assertTrue(uncompletedJobIds.size() > 0);
    }

    private Optional<JobInfo> getJobInfo(final String jobId) {
        return ruleAlteredJobAPI.list().stream().filter(each -> Objects.equals(each.getJobId(), jobId)).reduce((a, b) -> a);
    }

    private JobInfo getNonNullJobInfo(final String jobId) {
        Optional<JobInfo> result = getJobInfo(jobId);
        assertTrue(result.isPresent());
        return result.get();
    }

    @Test
    public void assertStartOrStopById() {
        Optional<String> jobId = ruleAlteredJobAPI.start(ResourceUtil.mockJobConfig());
        assertTrue(jobId.isPresent());
        assertTrue(getNonNullJobInfo(jobId.get()).isActive());
        ruleAlteredJobAPI.stop(jobId.get());
        assertFalse(getNonNullJobInfo(jobId.get()).isActive());
        ruleAlteredJobAPI.startDisabledJob(jobId.get());
        assertTrue(getNonNullJobInfo(jobId.get()).isActive());
    }

    @Test
    public void assertRemove() {
        Optional<String> jobId = ruleAlteredJobAPI.start(ResourceUtil.mockJobConfig());
        assertTrue(jobId.isPresent());
        assertTrue(getJobInfo(jobId.get()).isPresent());
        ruleAlteredJobAPI.remove(jobId.get());
        assertFalse(getJobInfo(jobId.get()).isPresent());
    }

    @Test
    public void assertGetProgress() {
        Optional<String> jobId = ruleAlteredJobAPI.start(ResourceUtil.mockJobConfig());
        assertTrue(jobId.isPresent());
        Map<Integer, JobProgress> jobProgressMap = ruleAlteredJobAPI.getProgress(jobId.get());
        assertThat(jobProgressMap.size(), is(1));
    }

    @Test
    public void assertListDataConsistencyCheckAlgorithms() {
        Collection<DataConsistencyCheckAlgorithmInfo> algorithmInfos = ruleAlteredJobAPI.listDataConsistencyCheckAlgorithms();
        assertTrue(algorithmInfos.size() > 0);
        Optional<DataConsistencyCheckAlgorithmInfo> algorithmInfoOptional = algorithmInfos.stream().filter(each -> each.getType().equals(FixtureDataConsistencyCheckAlgorithm.TYPE)).findFirst();
        assertTrue(algorithmInfoOptional.isPresent());
        DataConsistencyCheckAlgorithmInfo algorithmInfo = algorithmInfoOptional.get();
        assertThat(algorithmInfo.getType(), is(FixtureDataConsistencyCheckAlgorithm.TYPE));
        FixtureDataConsistencyCheckAlgorithm fixtureAlgorithm = new FixtureDataConsistencyCheckAlgorithm();
        assertThat(algorithmInfo.getDescription(), is(fixtureAlgorithm.getDescription()));
        assertThat(algorithmInfo.getSupportedDatabaseTypes(), is(fixtureAlgorithm.getSupportedDatabaseTypes()));
        assertThat(algorithmInfo.getProvider(), is(fixtureAlgorithm.getProvider()));
    }

    @Test
    public void assertIsDataConsistencyCheckNeeded() {
        Optional<String> jobId = ruleAlteredJobAPI.start(ResourceUtil.mockJobConfig());
        assertTrue(jobId.isPresent());
        assertThat(ruleAlteredJobAPI.isDataConsistencyCheckNeeded(jobId.get()), is(true));
    }

    @Test
    public void assertDataConsistencyCheck() {
        Optional<String> jobId = ruleAlteredJobAPI.start(ResourceUtil.mockJobConfig());
        assertTrue(jobId.isPresent());
        JobConfiguration jobConfig = ruleAlteredJobAPI.getJobConfig(jobId.get());
        initTableData(jobConfig.getPipelineConfig());
        PipelineContextUtil.mockContextManager();
        Map<String, DataConsistencyCheckResult> checkResultMap = ruleAlteredJobAPI.dataConsistencyCheck(jobId.get());
        assertThat(checkResultMap.size(), is(1));
    }

    @Test
    public void assertDataConsistencyCheckWithAlgorithm() {
        Optional<String> jobId = ruleAlteredJobAPI.start(ResourceUtil.mockJobConfig());
        assertTrue(jobId.isPresent());
        JobConfiguration jobConfig = ruleAlteredJobAPI.getJobConfig(jobId.get());
        initTableData(jobConfig.getPipelineConfig());
        PipelineContextUtil.mockContextManager();
        Map<String, DataConsistencyCheckResult> checkResultMap = ruleAlteredJobAPI.dataConsistencyCheck(jobId.get(), FixtureDataConsistencyCheckAlgorithm.TYPE);
        assertThat(checkResultMap.size(), is(1));
        assertTrue(checkResultMap.get("t_order").isRecordsCountMatched());
        assertTrue(checkResultMap.get("t_order").isRecordsContentMatched());
        assertThat(checkResultMap.get("t_order").getTargetRecordsCount(), is(2L));
    }

    @Test
    public void assertAggregateDataConsistencyCheckResults() {
        String jobId = "1";
        Map<String, DataConsistencyCheckResult> checkResultMap;
        checkResultMap = Collections.emptyMap();
        assertThat(ruleAlteredJobAPI.aggregateDataConsistencyCheckResults(jobId, checkResultMap), is(false));
        DataConsistencyCheckResult trueResult = new DataConsistencyCheckResult(1, 1);
        trueResult.setRecordsContentMatched(true);
        DataConsistencyCheckResult checkResult;
        checkResult = new DataConsistencyCheckResult(100, 95);
        checkResultMap = ImmutableMap.<String, DataConsistencyCheckResult>builder().put("t", trueResult).put("t_order", checkResult).build();
        assertThat(ruleAlteredJobAPI.aggregateDataConsistencyCheckResults(jobId, checkResultMap), is(false));
        checkResult = new DataConsistencyCheckResult(100, 100);
        checkResult.setRecordsContentMatched(false);
        checkResultMap = ImmutableMap.<String, DataConsistencyCheckResult>builder().put("t", trueResult).put("t_order", checkResult).build();
        assertThat(ruleAlteredJobAPI.aggregateDataConsistencyCheckResults(jobId, checkResultMap), is(false));
        checkResult = new DataConsistencyCheckResult(100, 100);
        checkResult.setRecordsContentMatched(true);
        checkResultMap = ImmutableMap.<String, DataConsistencyCheckResult>builder().put("t", trueResult).put("t_order", checkResult).build();
        assertThat(ruleAlteredJobAPI.aggregateDataConsistencyCheckResults(jobId, checkResultMap), is(true));
    }

    @Test
    public void assertResetTargetTable() {
        Optional<String> jobId = ruleAlteredJobAPI.start(ResourceUtil.mockJobConfig());
        assertTrue(jobId.isPresent());
        JobConfiguration jobConfig = ruleAlteredJobAPI.getJobConfig(jobId.get());
        initTableData(jobConfig.getPipelineConfig());
        ruleAlteredJobAPI.reset(jobId.get());
        Map<String, DataConsistencyCheckResult> checkResultMap = ruleAlteredJobAPI.dataConsistencyCheck(jobId.get(), FixtureDataConsistencyCheckAlgorithm.TYPE);
        assertThat(checkResultMap.get("t_order").getTargetRecordsCount(), is(0L));
    }

    @SneakyThrows(SQLException.class)
    private void initTableData(final PipelineConfiguration pipelineConfig) {
        PipelineDataSourceConfiguration sourceDataSourceConfig = PipelineDataSourceConfigurationFactory.newInstance(pipelineConfig.getSource().getType(), pipelineConfig.getSource().getParameter());
        initTableData(PipelineDataSourceCreatorFactory.getInstance(sourceDataSourceConfig.getType()).createPipelineDataSource(sourceDataSourceConfig.getDataSourceConfiguration()));
        PipelineDataSourceConfiguration targetDataSourceConfig = PipelineDataSourceConfigurationFactory.newInstance(pipelineConfig.getTarget().getType(), pipelineConfig.getTarget().getParameter());
        initTableData(PipelineDataSourceCreatorFactory.getInstance(targetDataSourceConfig.getType()).createPipelineDataSource(targetDataSourceConfig.getDataSourceConfiguration()));
    }

    private void initTableData(final DataSource pipelineDataSource) throws SQLException {
        try (Connection connection = pipelineDataSource.getConnection();
             Statement statement = connection.createStatement()) {
            statement.execute("DROP TABLE IF EXISTS t_order");
            statement.execute("CREATE TABLE t_order (id INT PRIMARY KEY, user_id VARCHAR(12))");
            statement.execute("INSERT INTO t_order (id, user_id) VALUES (1, 'xxx'), (999, 'yyy')");
        }
    }
}


text:
// +k8s:deepcopy-gen=package

// Package v1 is the v1 version of the API.
// +groupName=ark.heptio.com
package v1


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

namespace Limoncello\l10n\Messages;

use Limoncello\l10n\Contracts\Messages\ResourceBundleInterface;
use function array_keys;
use function assert;
use function is_scalar;
use function is_string;
use function locale_canonicalize;
use function strlen;

/**
 * @package Limoncello\l10n
 */
class ResourceBundle implements ResourceBundleInterface
{
    /**
     * @var string
     */
    private $locale;

    /**
     * @var string
     */
    private $namespace;

    /**
     * @var array
     */
    private $properties;

    /**
     * @param string $locale
     * @param string $namespace
     * @param array  $properties
     */
    public function __construct(string $locale, string $namespace, array $properties)
    {
        $this->setLocale($locale)->setNamespace($namespace)->setProperties($properties);
    }

    /**
     * @inheritdoc
     */
    public function getLocale(): string
    {
        return $this->locale;
    }

    /**
     * @inheritdoc
     */
    public function getNamespace(): string
    {
        return $this->namespace;
    }

    /**
     * @inheritdoc
     */
    public function getKeys(): array
    {
        return array_keys($this->getProperties());
    }

    /**
     * @inheritdoc
     */
    public function getValue(string $key): string
    {
        $properties = $this->getProperties();

        return $properties[$key];
    }

    /**
     * @param string $locale
     *
     * @return self
     */
    public function setLocale(string $locale): self
    {
        assert(empty($locale) === false && locale_canonicalize($locale) === $locale);

        $this->locale = $locale;

        return $this;
    }

    /**
     * @param string $namespace
     *
     * @return self
     */
    public function setNamespace(string $namespace): self
    {
        assert(empty($namespace) === false);

        $this->namespace = $namespace;

        return $this;
    }

    /**
     * @param array $properties
     *
     * @return self
     */
    public function setProperties(array $properties): self
    {
        // check all keys and values are non-empty strings
        $this->properties = [];
        foreach ($properties as $key => $value) {
            assert(is_scalar($key) === true && strlen((string)$key) > 0);
            assert(is_string($value) === true && strlen($value) > 0);
            $this->properties[(string)$key] = (string)$value;
        }

        return $this;
    }

    /**
     * @return array
     */
    public function getProperties(): array
    {
        return $this->properties;
    }
}


text:
package com.sun.mirror.util;

import com.sun.mirror.declaration.*;

/**
 * A visitor for declarations that scans declarations contained within
 * the given declaration.  For example, when visiting a class, the
 * methods, fields, constructors, and nested types of the class are
 * also visited.
 *
 * <p> To control the processing done on a declaration, users of this
 * class pass in their own visitors for pre and post processing.  The
 * preprocessing visitor is called before the contained declarations
 * are scanned; the postprocessing visitor is called after the
 * contained declarations are scanned.
 *
 * @deprecated All components of this API have been superseded by the
 * standardized annotation processing API.  The replacement for the
 * functionality of this class is {@link
 * javax.lang.model.util.ElementScanner6}.
 *
 * @author Joseph D. Darcy
 * @author Scott Seligman
 * @since 1.5
 */
@Deprecated
@SuppressWarnings("deprecation")
class DeclarationScanner implements DeclarationVisitor {
    protected DeclarationVisitor pre;
    protected DeclarationVisitor post;

    DeclarationScanner(DeclarationVisitor pre, DeclarationVisitor post) {
        this.pre = pre;
        this.post = post;
    }

    /**
     * Visits a declaration.
     *
     * @param d the declaration to visit
     */
    public void visitDeclaration(Declaration d) {
        d.accept(pre);
        d.accept(post);
    }

    /**
     * Visits a package declaration.
     *
     * @param d the declaration to visit
     */
    public void visitPackageDeclaration(PackageDeclaration d) {
        d.accept(pre);

        for(ClassDeclaration classDecl: d.getClasses()) {
            classDecl.accept(this);
        }

        for(InterfaceDeclaration interfaceDecl: d.getInterfaces()) {
            interfaceDecl.accept(this);
        }

        d.accept(post);
    }

    /**
     * Visits a member or constructor declaration.
     *
     * @param d the declaration to visit
     */
    public void visitMemberDeclaration(MemberDeclaration d) {
        visitDeclaration(d);
    }

    /**
     * Visits a type declaration.
     *
     * @param d the declaration to visit
     */
    public void visitTypeDeclaration(TypeDeclaration d) {
        d.accept(pre);

        for(TypeParameterDeclaration tpDecl: d.getFormalTypeParameters()) {
            tpDecl.accept(this);
        }

        for(FieldDeclaration fieldDecl: d.getFields()) {
            fieldDecl.accept(this);
        }

        for(MethodDeclaration methodDecl: d.getMethods()) {
            methodDecl.accept(this);
        }

        for(TypeDeclaration typeDecl: d.getNestedTypes()) {
            typeDecl.accept(this);
        }

        d.accept(post);
    }

    /**
     * Visits a class declaration.
     *
     * @param d the declaration to visit
     */
    public void visitClassDeclaration(ClassDeclaration d) {
        d.accept(pre);

        for(TypeParameterDeclaration tpDecl: d.getFormalTypeParameters()) {
            tpDecl.accept(this);
        }

        for(FieldDeclaration fieldDecl: d.getFields()) {
            fieldDecl.accept(this);
        }

        for(MethodDeclaration methodDecl: d.getMethods()) {
            methodDecl.accept(this);
        }

        for(TypeDeclaration typeDecl: d.getNestedTypes()) {
            typeDecl.accept(this);
        }

        for(ConstructorDeclaration ctorDecl: d.getConstructors()) {
            ctorDecl.accept(this);
        }

        d.accept(post);
    }

    /**
     * Visits an enum declaration.
     *
     * @param d the declaration to visit
     */
    public void visitEnumDeclaration(EnumDeclaration d) {
        visitClassDeclaration(d);
    }

    /**
     * Visits an interface declaration.
     *
     * @param d the declaration to visit
     */
    public void visitInterfaceDeclaration(InterfaceDeclaration d) {
        visitTypeDeclaration(d);
    }

    /**
     * Visits an annotation type declaration.
     *
     * @param d the declaration to visit
     */
    public void visitAnnotationTypeDeclaration(AnnotationTypeDeclaration d) {
        visitInterfaceDeclaration(d);
    }

    /**
     * Visits a field declaration.
     *
     * @param d the declaration to visit
     */
    public void visitFieldDeclaration(FieldDeclaration d) {
        visitMemberDeclaration(d);
    }

    /**
     * Visits an enum constant declaration.
     *
     * @param d the declaration to visit
     */
    public void visitEnumConstantDeclaration(EnumConstantDeclaration d) {
        visitFieldDeclaration(d);
    }

    /**
     * Visits a method or constructor declaration.
     *
     * @param d the declaration to visit
     */
    public void visitExecutableDeclaration(ExecutableDeclaration d) {
        d.accept(pre);

        for(TypeParameterDeclaration tpDecl: d.getFormalTypeParameters()) {
            tpDecl.accept(this);
        }

        for(ParameterDeclaration pDecl: d.getParameters()) {
            pDecl.accept(this);
        }

        d.accept(post);
    }

    /**
     * Visits a constructor declaration.
     *
     * @param d the declaration to visit
     */
    public void visitConstructorDeclaration(ConstructorDeclaration d) {
        visitExecutableDeclaration(d);
    }

    /**
     * Visits a method declaration.
     *
     * @param d the declaration to visit
     */
    public void visitMethodDeclaration(MethodDeclaration d) {
        visitExecutableDeclaration(d);
    }

    /**
     * Visits an annotation type element declaration.
     *
     * @param d the declaration to visit
     */
    public void visitAnnotationTypeElementDeclaration(
            AnnotationTypeElementDeclaration d) {
        visitMethodDeclaration(d);
    }

    /**
     * Visits a parameter declaration.
     *
     * @param d the declaration to visit
     */
    public void visitParameterDeclaration(ParameterDeclaration d) {
        visitDeclaration(d);
    }

    /**
     * Visits a type parameter declaration.
     *
     * @param d the declaration to visit
     */
    public void visitTypeParameterDeclaration(TypeParameterDeclaration d) {
        visitDeclaration(d);
    }
}


text:
package org.dcm4chee.xdsb.repository.ws.client;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.namespace.QName;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPHeaderElement;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPMessageContext;

import org.dcm4chee.xds.common.XDSConstants;
import org.dcm4chee.xds.common.utils.SOAPUtil;
import org.jboss.wsf.common.handler.GenericSOAPHandler;
import org.jboss.ws.core.soap.attachment.MimeConstants;
import org.jboss.ws.extensions.addressing.AddressingConstantsImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RegistryClientHeaderHandler extends GenericSOAPHandler
{
	private Logger log = LoggerFactory.getLogger(RegistryClientHeaderHandler.class);
	private static Set<QName> HEADERS = new HashSet<QName>();

	static {
		HEADERS.add( new AddressingConstantsImpl().getActionQName());
	}

	public Set getHeaders()
	{
		log.info("@@@@@@@@@@@@ REGISTRY CLIENT @@@@@@@@@@@@@@@@ getHeaders :"+HEADERS);
		return Collections.unmodifiableSet(HEADERS);
	}

	protected boolean handleOutbound(MessageContext msgContext) {
		log.debug("@@@@@@@@@@@@ REGISTRY CLIENT @@@@@@@@@@@@@@@@ handleOutbound");
		try {
			SOAPMessage msg = ((SOAPMessageContext)msgContext).getMessage();
			if (log.isDebugEnabled()) {
				log.debug("@@@@@@@@@@@@ REGISTRY CLIENT @@@@@@@@@@@@@@@@ handleOutbound --SOAP Message end.");
				SOAPUtil.getInstance().logSOAPMessage(log, msg, true);
				log.debug("@@@@@@@@@@@@ REGISTRY CLIENT @@@@@@@@@@@@@@@@ handleOutbound --SOAP Message end.");
			}
			SOAPHeaderElement hdr = msg.getSOAPHeader().addHeaderElement(
					new QName(XDSConstants.NS_WS_ADDRESSING, XDSConstants.SOAP_HEADER_ACTION, "wsa"));
			hdr.setMustUnderstand(true);
			hdr.setValue(XDSConstants.URN_IHE_ITI_2007_REGISTER_DOCUMENT_SET_B);

			SOAPHeaderElement hdrMsgId = msg.getSOAPHeader().addHeaderElement(
					new QName(XDSConstants.NS_WS_ADDRESSING, XDSConstants.SOAP_HEADER_MSG_ID, "wsa"));
			hdrMsgId.setValue(XDSConstants.MSG_ID_REGISTER_DOCUMENT_SET_B);
			/*_*/
			log.info("@@@@@@@@@@@@ REGISTRY CLIENT @@@@@@@@@@@@@@@@ handleOutbound --SOAP Message with added Action header.");
			SOAPUtil.getInstance().logSOAPMessage(log, msg, true);
			log.info("@@@@@@@@@@@@ REGISTRY CLIENT @@@@@@@@@@@@@@@@ handleOutbound --SOAP Message end.");
		} catch (Exception e) {
			log.error("Error:",e);
		}
		log.debug("@@@@@@@@@@@@ REGISTRY CLIENT @@@@@@@@@@@@@@@@ handleOutbound end.");
		return true;
	}

	private void logMimeHdrContentType(MimeHeaders headers) {
		if (headers == null ) {
			log.info("MimeHeaders is null!");
			return;
		}
		String[] type = headers.getHeader(MimeConstants.CONTENT_TYPE);
		if ( type == null) {
			log.info("No contentType in MimeHeaders!");
			return;
		}
		for ( int i = 0; i < type.length ; i++) {
			log.info("contentType("+i+"):"+type[i]);
		}
	}
	protected boolean handleInbound(MessageContext msgContext) {
		log.debug("@@@@@@@@@@@@ CLIENT @@@@@@@@@@@@@@@@ handleInbound");
		return true;
	}
}


text:
"""Main django-unfriendly package."""

VERSION = (0, 6)
__version__ = '.'.join([str(x) for x in VERSION])


text:
package cn.remex.wechat.event;

import cn.remex.core.RemexEvent;

/**
 * 名称:
 * 缩写:
 * 用途:
 * Created by yangy on 2016/4/9 0009.
 */
public class WeChatScanEvent extends RemexEvent {
    private static final long serialVersionUID = -5467836967924859761L;
    private String openId;
    private String eventKey;
    private String tickets;
    public WeChatScanEvent(String source, String openId, String eventKey,String tickets) {
        super(source, openId, eventKey, tickets);
        this.openId = openId;
        this.eventKey = eventKey;
        this.tickets = tickets;
    }

    public String getEventKey() {
        return eventKey;
    }

    public void setEventKey(String eventKey) {
        this.eventKey = eventKey;
    }

    public String getOpenId() {
        return openId;
    }

    public void setOpenId(String openId) {
        this.openId = openId;
    }

    public String getTickets() {
        return tickets;
    }

    public void setTickets(String tickets) {
        this.tickets = tickets;
    }
}