text:
namespace mesos {
namespace state {

// An abstraction of "state" (possibly between multiple distributed
// components) represented by "variables" (effectively key/value
// pairs). Variables are versioned such that setting a variable in the
// state will only succeed if the variable has not changed since last
// fetched. Varying implementations of state provide varying
// replicated guarantees.
//
// Note that the semantics of 'fetch' and 'store' provide
// atomicity. That is, you cannot store a variable that has changed
// since you did the last fetch. That is, if a store succeeds then no
// other writes have been performed on the variable since your fetch.
//
// Example:
//
//   Storage* storage = new ZooKeeperStorage();
//   State* state = new State(storage);
//   Future<Variable> variable = state->fetch("slaves");
//   std::string value = update(variable.value());
//   variable = variable.mutate(value);
//   state->store(variable);

// Forward declarations.
class State;

// Wrapper around a state "entry" to force immutability.
class Variable
{
public:
  std::string value() const
  {
    return entry.value();
  }

  Variable mutate(const std::string& value) const
  {
    Variable variable(*this);
    variable.entry.set_value(value);
    return variable;
  }

private:
  friend class State; // Creates and manages variables.

  explicit Variable(const internal::state::Entry& _entry)
    : entry(_entry)
  {}

  internal::state::Entry entry; // Not const to keep Variable assignable.
};

class State
{
public:
  explicit State(Storage* _storage) : storage(_storage) {}
  virtual ~State() {}

  // Returns a variable from the state, creating a new one if one
  // previously did not exist (or an error if one occurs).
  process::Future<Variable> fetch(const std::string& name);

  // Returns the variable specified if it was successfully stored in
  // the state, otherwise returns none if the version of the variable
  // was no longer valid, or an error if one occurs.
  process::Future<Option<Variable>> store(const Variable& variable);

  // Returns true if successfully expunged the variable from the state.
  process::Future<bool> expunge(const Variable& variable);

  // Returns the collection of variable names in the state.
  process::Future<std::set<std::string>> names();

private:
  // Helpers to handle future results from fetch and swap. We make
  // these static members of State for friend access to Variable's
  // constructor.
  static process::Future<Variable> _fetch(
      const std::string& name,
      const Option<internal::state::Entry>& option);

  static process::Future<Option<Variable>> _store(
      const internal::state::Entry& entry,
      const bool& b); // TODO(benh): Remove 'const &' after fixing libprocess.

  Storage* storage;
};

inline process::Future<Variable> State::fetch(const std::string& name)
{
  return storage->get(name)
    .then(lambda::bind(&State::_fetch, name, lambda::_1));
}

inline process::Future<Variable> State::_fetch(
    const std::string& name,
    const Option<internal::state::Entry>& option)
{
  if (option.isSome()) {
    return Variable(option.get());
  }

  // Otherwise, construct a Variable with a new Entry (with a random
  // UUID and no value to start).
  internal::state::Entry entry;
  entry.set_name(name);
  entry.set_uuid(UUID::random().toBytes());

  return Variable(entry);
}

inline process::Future<Option<Variable>> State::store(const Variable& variable)
{
  // Note that we try and swap an entry even if the value didn't change!
  UUID uuid = UUID::fromBytes(variable.entry.uuid()).get();

  // Create a new entry to replace the existing entry provided the
  // UUID matches.
  internal::state::Entry entry;
  entry.set_name(variable.entry.name());
  entry.set_uuid(UUID::random().toBytes());
  entry.set_value(variable.entry.value());

  return storage->set(entry, uuid)
    .then(lambda::bind(&State::_store, entry, lambda::_1));
}

inline process::Future<Option<Variable>> State::_store(
    const internal::state::Entry& entry,
    const bool& b) // TODO(benh): Remove 'const &' after fixing libprocess.
{
  if (b) {
    return Some(Variable(entry));
  }

  return None();
}

inline process::Future<bool> State::expunge(const Variable& variable)
{
  return storage->expunge(variable.entry);
}

inline process::Future<std::set<std::string>> State::names()
{
  return storage->names();
}

} // namespace state {
} // namespace mesos {

#endif // __MESOS_STATE_STATE_HPP__


text:
module ArtisanClient

  class UrlBuilder

    def initialize a_base_url, a_project_key
      @base_url = a_base_url
      @project_key = a_project_key
    end

    def iterations
      build_api_uri_for 'projects/iterations'
    end

    def total_billed_points_by_craftsman an_iteration_number
      build_api_uri_for "projects/iterations/#{an_iteration_number}/total_billed_points_by_craftsman"
    end

    def users
      build_api_uri_for 'projects/users'
    end

    def build_api_uri_for(a_path)
      URI "#{@base_url}/api/#{a_path}.json?key=#{@project_key}"
    end

  end

end

redpajama_set_name: RedPajamaGithub


text:
var WebsocketServer = require('ws').Server;
var config = require('../../config/config');
var redis = require('redis');
var redisClient = redis.createClient(config['REDIS_PORT'], config['FOXRIVER_IP']);
var computeOrderKey = require('./redisKeyCompute').computeOrderKey;
var computeCustomerKey = require('./redisKeyCompute').computeCustomerKey;
var TTL = require('./redisKeyCompute').TTL;
var NO_INFLIGHT_ORDER = require('./redisKeyCompute').NO_INFLIGHT_ORDER;
var INFLIGHT_ORDERS = require('./redisKeyCompute').INFLIGHT_ORDERS;
var writeWS = require('./writeWS');
var async = require('async');
var BIG_NEGATIVE_DT = -99999999;

module.exports = function(winston) {

	function removeCustomerFromQueue(customer, callback) {
		redisClient.lrem(INFLIGHT_ORDERS, 0, computeCustomerKey(customer), function(err, result) {
			if (err) {
				return callback('cannot delete from inflight list');
			}

			callback(null, customer);
		});
	}

	function getSetCustomerOrderDone(customer, callback) {
		redisClient.getset(computeCustomerKey(customer), NO_INFLIGHT_ORDER,
			function(err, prevOrderKey) {
				if (err) {
					return callback('cannot set customerKey to done');
				}

				if (prevOrderKey === NO_INFLIGHT_ORDER) {
					return callback(customer + ' didnt have pending order');
				}

				callback(null, customer, prevOrderKey);
			}
		);
	}

	function setCustomerTTL(customer, prevOrderKey, callback) {
		redisClient.expire(computeCustomerKey(customer), TTL, function(err, result) {
			if (err) {
				return callback('set customer TTL failed');
			}

			callback(null, customer, prevOrderKey);
		});
	}

	function getDeliveryTime(customer, prevOrderKey, callback) {
		redisClient.get(prevOrderKey + ':deliveryTime', function(err, deliveryTime) {

			if (err) {
				return callback('get deliveryTime failed');
			}

			callback(null, customer, prevOrderKey, deliveryTime);
		});
	}

	function setDeliveryTimeToNow(customer, prevOrderKey, deliveryTime, callback) {
		var timeNow = new Date().getTime();
		var dt = timeNow - deliveryTime;
		redisClient.incrby(prevOrderKey + ':deliveryTime', dt, function(err, newDeliveryTime) {
			if (err) {
				return callback('set deliveryTime to now failed');
			}

			callback(null, customer, timeNow);
		});
	}

	function notifyCustomer(customer, newDeliveryTime, callback) {
		redisClient.publish(computeCustomerKey(customer), newDeliveryTime);
		callback(null, {});
	}

	return function(params, ws) {
		var customer = params.customer;
		if (!customer) {
			return writeWS(ws, 400, 'no customer in parameter', {});
		}

		async.waterfall([
			function(callback) {
				callback(null, customer);
			},
			removeCustomerFromQueue,
			getSetCustomerOrderDone,
			setCustomerTTL,
			getDeliveryTime,
			setDeliveryTimeToNow,
			notifyCustomer
		],
			function(err, result) {
				if (err) {
					winston.error(err);
					return writeWS(ws, 500, err, {});
				}
				//intentionally don't write result back to client.
			}
		);
	};
};


text:
<?php defined('SYSPATH') OR die('No direct script access.');

/**
 * Tests for Jam_Timezone.
 *
 * @package Jam
 * @group   jam
 * @group   jam.event
 */
class Jam_EventTest extends PHPUnit_Framework_TestCase {

	public $event;

	public function setUp()
	{
		parent::setUp();
		$this->event = new Jam_Event('test_position');
	}

	public function test_bind()
	{
		$sender = new stdClass;

		$observer = $this->getMock('Jam_EventTest_Observer', array('callback'));
		$observer
			->expects($this->once())
			->method('callback')
			->with($this->equalTo($sender), $this->isInstanceOf('Jam_Event_Data'));

		$this->event->bind('test_event', array($observer, 'callback'));

		$this->event->trigger('test_event', $sender);
	}

}

class Jam_EventTest_Observer {

}


text:
package dev.tauri.seals
package checker

import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

import io.circe.Decoder

import circe.Codecs._

class ExtractorSpec extends AnyFlatSpec with Matchers {

  val decoder = Decoder[Model]
  val pack = this.getClass.getPackage.getName

  val fooName = s"$pack.Foo"
  val ccName = s"$pack.CC"
  val wfooName = s"$pack.Wrap.WFoo"
  val wccName = s"$pack.Wrap.WCC"

  // force WFoo subclasses (SI-7046 workaround):
  def dummy1: Wrap.Bar = sys.error("dummy1")
  def dummy2: Wrap.Baz.type = sys.error("dummy2")

  val extractor = Extractor(
    this.getClass.getClassLoader,
    new java.io.File(this.getClass.getProtectionDomain.getCodeSource.getLocation.toURI)
  )

  "Extractor#allClasses" should "find every class" in {
    val expected = Set(
      "Foo",
      "Foo$",
      "CC",
      "CC$",
      "Wrap$"
    )
    assert(expected.subsetOf(extractor.allClasses(pack).toSet))
  }

  "Extractor#extractAll" should "find all marked classes in a package" in {
    val models: Map[String, Model] = extractor.extractAll(pack)
    val expected = Map(
      fooName -> Foo.reifiedFoo.model,
      ccName -> CC.reifiedCC.model,
      wfooName -> Wrap.WFoo.reifiedWFoo.model,
      wccName -> Wrap.WCC.reifiedWCC.model
    )
    models should === (expected)
  }

  "Extractor#allSchemas" should "collect all annotated classes" in {
    extractor.allSchemasOfPackage(pack).map(_.fullName).toSet should === (Set(
      fooName,
      ccName,
      wfooName,
      wccName
    ))
  }
}


text:
class OpenOcd < Formula
  desc "On-chip debugging, in-system programming and boundary-scan testing"
  homepage "https://sourceforge.net/projects/openocd/"
  url "https://downloads.sourceforge.net/project/openocd/openocd/0.10.0/openocd-0.10.0.tar.bz2"
  sha256 "7312e7d680752ac088b8b8f2b5ba3ff0d30e0a78139531847be4b75c101316ae"

  bottle do
    rebuild 1
    sha256 "281978e21362ed00dd198715825d77f0f2aeb64ad99954714a34ce128e1a0df8" => :sierra
    sha256 "e1fc5f8a8bf079954a56459b330313cd82a69a219114821c14f9d3df2fd3ea25" => :el_capitan
    sha256 "568ae702a3488805b8651b5456346c9484ca6f8486a09f3c2a4473664370a481" => :yosemite
  end

  head do
    url "https://git.code.sf.net/p/openocd/code.git"

    depends_on "autoconf" => :build
    depends_on "automake" => :build
    depends_on "libtool" => :build
    depends_on "texinfo" => :build
  end

  option "without-hidapi", "Disable building support for devices using HIDAPI (CMSIS-DAP)"
  option "without-libftdi", "Disable building support for libftdi-based drivers (USB-Blaster, ASIX Presto, OpenJTAG)"
  option "without-libusb",  "Disable building support for all other USB adapters"

  depends_on "pkg-config" => :build
  depends_on "libusb" => :recommended
  # some drivers are still not converted to libusb-1.0
  depends_on "libusb-compat" if build.with? "libusb"
  depends_on "libftdi" => :recommended
  depends_on "hidapi" => :recommended

  def install
    # all the libusb and hidapi-based drivers are auto-enabled when
    # the corresponding libraries are present in the system
    args = %W[
      --disable-dependency-tracking
      --prefix=#{prefix}
      --enable-dummy
      --enable-buspirate
      --enable-jtag_vpi
      --enable-remote-bitbang
    ]

    ENV["CCACHE"] = "none"

    system "./bootstrap", "nosubmodule" if build.head?
    system "./configure", *args
    system "make", "install"
  end
end


text:
import sublime

from utils.scratch_view import ScratchView

Region = sublime.Region

def run():
    # Generate new scratch file
    scratch_view = ScratchView()
    try:
        # Injection point for input variables
        content = """{{content}}"""
        target_sel = {{target_sel}}

        # Output single.input to scratch
        scratch_view.set_content(content)

        # Update selection
        scratch_view.set_sel(target_sel)

        # Run command
        scratch_view.view.settings().set('syntax', u'Packages/JavaScript/JavaScript.tmLanguage')
        scratch_view.run_command('js_var_delete')

        # Injection point for assertion variables
        expected_content = """{{expected_content}}"""
        expected_sel = {{expected_sel}}

        # Assert input to output
        # TODO: Move to self.assertEqual
        # TODO: One method - Move run to class + run, inherit from unittest.TestCase
        actual_content = scratch_view.get_content()
        error_msg = 'Expected content "%s" does not match actual content "%s"' % (expected_content, actual_content)
        assert expected_content == actual_content, error_msg

        # Assert current selection to output selection
        # TODO: To get full agreement, move to RegionSet?
        # TODO: Make this into a util? (e.g. sublime_utils.to_region_set)
        actual_sel = scratch_view.get_sel()
        error_msg = 'Expected selection "%s" does not match actual selection "%s"' % (expected_sel, actual_sel)
        assert Region(expected_sel[0][0], expected_sel[0][1]) == actual_sel[0], error_msg
    finally:
        # No matter what happens, close the view
        scratch_view.destroy()


text:
#region MIT
//
// Gorgon.
// Copyright (C) 2019 Michael Winsor
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Created: August 31, 2019 9:12:06 PM
//
#endregion

using System.Linq;
using Gorgon.Core;
using Gorgon.Editor.ImageEditor.ViewModels;
using Gorgon.Editor.UI;
using Gorgon.Math;

namespace Gorgon.Editor.ImageEditor
{
    ///
    /// The view model for the alpha settings view.
    ///
    internal class AlphaSettings
        : HostedPanelViewModelBase<HostedPanelViewModelParameters>, IAlphaSettings
    {
        #region Variables.
        // The number of mip map levels in the image.
        private int _alpha = 255;
        // The range of alpha values to update.
        private GorgonRange _alphaUpdateRange = new(0, 255);
        #endregion

        #region Properties.
        /// Property to return whether the panel is modal.
        public override bool IsModal => true;

        ///
        /// Property to set or return the lower and upper bounds of the alpha range to update.
        ///
        public GorgonRange UpdateRange
        {
            get => _alphaUpdateRange;
            set
            {
                if (_alphaUpdateRange.Equals(value))
                {
                    return;
                }

                OnPropertyChanging();
                _alphaUpdateRange = value;
                OnPropertyChanged();
            }
        }

        /// Property to set or return the alpha value to set.
        public int AlphaValue
        {
            get => _alpha;
            set
            {
                value = value.Max(0).Min(255);

                if (_alpha == value)
                {
                    return;
                }

                OnPropertyChanging();
                _alpha = value;
                OnPropertyChanged();
            }
        }
        #endregion

        #region Methods.
        /// Function to inject dependencies for the view model.
        /// <param name="injectionParameters">The parameters to inject.</param>
        /// <remarks>
        /// Applications should call this when setting up the view model for complex operations and/or dependency injection. The constructor should only be used for simple set up and initialization of objects.
        /// </remarks>
        protected override void OnInitialize(HostedPanelViewModelParameters injectionParameters)
        {
        }
        #endregion
    }
}


text:
using System.Collections.Generic;
using System.Reflection;
using Microsoft.Extensions.Options;

namespace Orleans.Configuration
{
    /// <summary>
    /// Specifies serialization provider and fallback serializer options.
    /// </summary>
    public class SerializationProviderOptions
    {
        /// <summary>
        /// Externally registered serializers
        /// </summary>
        public List<TypeInfo> SerializationProviders { get; set; } = new List<TypeInfo>();

        /// <summary>
        /// Serializer used if no serializer is found for a type.
        /// </summary>
        public TypeInfo FallbackSerializationProvider { get; set; }
    }
}


text:
    <title>EmberDragDrop by Wildhoney</title>

    <link rel="stylesheet" type="text/css" href="styles/default.css" />
    <link href='http://fonts.googleapis.com/css?family=Lato:100,300,400,700,900,100italic,300italic,400italic,700italic,900italic' rel='stylesheet' type='text/css'>


text:
#ifndef OGR_GEOMEDIA_H_INCLUDED
#define OGR_GEOMEDIA_H_INCLUDED

#include "ogrsf_frmts.h"
#include "cpl_odbc.h"
#include "cpl_error.h"
#include "ogr_pgeo.h"

/************************************************************************/
/*                          OGRGeomediaLayer                            */
/************************************************************************/

class OGRGeomediaDataSource;

class OGRGeomediaLayer : public OGRLayer
{
  protected:
    OGRFeatureDefn     *poFeatureDefn;

    CPLODBCStatement   *poStmt;

    // Layer spatial reference system, and srid.
    OGRSpatialReference *poSRS;
    int                 nSRSId;

    GIntBig             iNextShapeId;

    OGRGeomediaDataSource    *poDS;

    char                *pszGeomColumn;
    char                *pszFIDColumn;

    int                *panFieldOrdinals;

    CPLErr              BuildFeatureDefn( const char *pszLayerName,
                                          CPLODBCStatement *poStmt );

    virtual CPLODBCStatement *  GetStatement() { return poStmt; }

    void                LookupSRID( int );

  public:
                        OGRGeomediaLayer();
    virtual             ~OGRGeomediaLayer();

    virtual void        ResetReading();
    virtual OGRFeature *GetNextRawFeature();
    virtual OGRFeature *GetNextFeature();

    virtual OGRFeature *GetFeature( GIntBig nFeatureId );

    OGRFeatureDefn *    GetLayerDefn() { return poFeatureDefn; }

    virtual int         TestCapability( const char * );

    virtual const char *GetFIDColumn();
    virtual const char *GetGeometryColumn();
};

/************************************************************************/
/*                       OGRGeomediaTableLayer                          */
/************************************************************************/

class OGRGeomediaTableLayer : public OGRGeomediaLayer
{
    int                 bUpdateAccess;

    char                *pszQuery;

    void		ClearStatement();
    OGRErr              ResetStatement();

    virtual CPLODBCStatement *  GetStatement();

  public:
                        OGRGeomediaTableLayer( OGRGeomediaDataSource * );
                        ~OGRGeomediaTableLayer();

    CPLErr              Initialize( const char *pszTableName,
                                    const char *pszGeomCol,
                                    OGRSpatialReference* poSRS );

    virtual void        ResetReading();
    virtual GIntBig     GetFeatureCount( int );

    virtual OGRErr      SetAttributeFilter( const char * );
    virtual OGRFeature *GetFeature( GIntBig nFeatureId );

    virtual int         TestCapability( const char * );
};

/************************************************************************/
/*                        OGRGeomediaSelectLayer                        */
/************************************************************************/

class OGRGeomediaSelectLayer : public OGRGeomediaLayer
{
    char                *pszBaseStatement;

    void		ClearStatement();
    OGRErr              ResetStatement();

    virtual CPLODBCStatement *  GetStatement();

  public:
                        OGRGeomediaSelectLayer( OGRGeomediaDataSource *,
                                           CPLODBCStatement * );
                        ~OGRGeomediaSelectLayer();

    virtual void        ResetReading();
    virtual GIntBig     GetFeatureCount( int );

    virtual OGRFeature *GetFeature( GIntBig nFeatureId );

    virtual int         TestCapability( const char * );
};

/************************************************************************/
/*                        OGRGeomediaDataSource                         */
/************************************************************************/

class OGRGeomediaDataSource : public OGRDataSource
{
    OGRGeomediaLayer  **papoLayers;
    int                 nLayers;

    OGRGeomediaLayer  **papoLayersInvisible;
    int                 nLayersWithInvisible;

    char               *pszName;

    int                 bDSUpdate;
    CPLODBCSession      oSession;

    CPLString          GetTableNameFromType(const char* pszTableType);
    OGRSpatialReference* GetGeomediaSRS(const char* pszGCoordSystemTable,
                                        const char* pszGCoordSystemGUID);

  public:
                        OGRGeomediaDataSource();
                        ~OGRGeomediaDataSource();

    int                 Open( const char *, int bUpdate, int bTestOpen );
    int                 OpenTable( const char *pszTableName,
                                   const char *pszGeomCol,
                                   int bUpdate );

    const char          *GetName() { return pszName; }
    int                 GetLayerCount() { return nLayers; }
    OGRLayer            *GetLayer( int );
    OGRLayer            *GetLayerByName( const char* pszLayerName );

    int                 TestCapability( const char * );

    virtual OGRLayer *  ExecuteSQL( const char *pszSQLCommand,
                                    OGRGeometry *poSpatialFilter,
                                    const char *pszDialect );
    virtual void        ReleaseResultSet( OGRLayer * poLayer );

    // Internal use
    CPLODBCSession     *GetSession() { return &oSession; }
};

/************************************************************************/
/*                          OGRGeomediaDriver                           */
/************************************************************************/

class OGRGeomediaDriver : public OGRODBCMDBDriver
{
  public:
                ~OGRGeomediaDriver();

    const char  *GetName();
    OGRDataSource *Open( const char *, int );

    int          TestCapability( const char * );
};

#endif /* ndef _OGR_Geomedia_H_INCLUDED */


text:
package net.sf.sparql.benchmarking.operations;

import java.util.concurrent.Callable;

import net.sf.sparql.benchmarking.options.Options;
import net.sf.sparql.benchmarking.stats.OperationRun;

/**
 * Interface for operation callables
 *
 * @author rvesse
 *
 * @param <T>
 *            Options type
 */
public interface OperationCallable<T extends Options> extends Callable<OperationRun> {

    /**
     * Cancels the runner
     */
    public abstract void cancel();

}


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.LinuxPackager = undefined;

var _electronBuilderCore;

function _load_electronBuilderCore() {
    return _electronBuilderCore = require("electron-builder-core");
}

var _fsExtraP;

function _load_fsExtraP() {
    return _fsExtraP = require("fs-extra-p");
}

var _path = _interopRequireWildcard(require("path"));

var _sanitizeFilename;

function _load_sanitizeFilename() {
    return _sanitizeFilename = _interopRequireDefault(require("sanitize-filename"));
}

var _platformPackager;

function _load_platformPackager() {
    return _platformPackager = require("./platformPackager");
}

var _LinuxTargetHelper;

function _load_LinuxTargetHelper() {
    return _LinuxTargetHelper = require("./targets/LinuxTargetHelper");
}

var _targetFactory;

function _load_targetFactory() {
    return _targetFactory = require("./targets/targetFactory");
}

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

class LinuxPackager extends (_platformPackager || _load_platformPackager()).PlatformPackager {
    constructor(info) {
        super(info);
        const executableName = this.platformSpecificBuildOptions.executableName;
        this.executableName = (0, (_sanitizeFilename || _load_sanitizeFilename()).default)(executableName == null ? this.appInfo.name.toLowerCase() : executableName);
    }
    get defaultTarget() {
        return ["appimage"];
    }
    createTargets(targets, mapper, cleanupTasks) {
        let helper;
        const getHelper = () => {
            if (helper == null) {
                helper = new (_LinuxTargetHelper || _load_LinuxTargetHelper()).LinuxTargetHelper(this);
            }
            return helper;
        };
        for (const name of targets) {
            if (name === (_electronBuilderCore || _load_electronBuilderCore()).DIR_TARGET) {
                continue;
            }
            const targetClass = (() => {
                switch (name) {
                    case "appimage":
                        return require("./targets/appImage").default;
                    case "snap":
                        return require("./targets/snap").default;
                    case "deb":
                    case "rpm":
                    case "sh":
                    case "freebsd":
                    case "pacman":
                    case "apk":
                    case "p5p":
                        return require("./targets/fpm").default;
                    default:
                        return null;
                }
            })();
            mapper(name, outDir => targetClass === null ? (0, (_targetFactory || _load_targetFactory()).createCommonTarget)(name, outDir, this) : new targetClass(name, this, getHelper(), outDir));
        }
    }
    get platform() {
        return (_electronBuilderCore || _load_electronBuilderCore()).Platform.LINUX;
    }
    postInitApp(appOutDir) {
        return (0, (_fsExtraP || _load_fsExtraP()).rename)(_path.join(appOutDir, this.electronDistExecutableName), _path.join(appOutDir, this.executableName));
    }
}
exports.LinuxPackager = LinuxPackager; //# sourceMappingURL=linuxPackager.js.map


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using DbUp.Engine;
using System.Resources;
using System.Collections;

namespace CrmUp
{
    /// <summary>
    /// Single responsbility: Extends the DbUp concept of a "SqlScript" to be a Dynamics Crm Solution File.
    /// </summary>
    public class CrmSolutionFile : SqlScript
    {

        public CrmSolutionFile(string name, Byte[] fileBytes)
            : base(name, Convert.ToBase64String(fileBytes))
        {
            FileBytes = fileBytes;
        }

        /// <summary>
        /// Returns a new Crm Solution file from the given stream.
        /// </summary>
        /// <param name="assembly"></param>
        /// <param name="manifestResourceName"></param>
        /// <returns></returns>
        public static CrmSolutionFile FromFile(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentException("path");
            }

            var scriptName = System.IO.Path.GetFileNameWithoutExtension(path);
            using (var resourceStreamReader = new StreamReader(path, Encoding.Default, true))
            {
                return new CrmSolutionFile(scriptName, GetStreamBytes(resourceStreamReader.BaseStream));
            }
        }

        /// <summary>
        /// Returns a new Crm Solution file from the given stream.
        /// </summary>
        /// <param name="assembly"></param>
        /// <param name="manifestResourceName"></param>
        /// <returns></returns>
        public static CrmSolutionFile FromEmbeddedResource(Assembly assembly, string manifestResourceName)
        {
            if (string.IsNullOrEmpty(manifestResourceName))
            {
                throw new ArgumentException("manifestResourceName");
            }

            if (assembly == null)
            {
                throw new ArgumentNullException("assembly");
            }

            // Split the resource manifest name into is components, removing path information relating to where it is in assembly. We only want the file name.
            var scriptPathArray = manifestResourceName.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
            int segmentCount = scriptPathArray.Count();
            if (segmentCount < 2)
            {
                throw new Exception("Embedded solution files should be named ending '.zip'");
            }

            var fileName = string.Format("{0}.{1}", scriptPathArray[segmentCount - 2], scriptPathArray[segmentCount - 1]);
            var scriptName = System.IO.Path.GetFileNameWithoutExtension(fileName);
            using (var resource = assembly.GetManifestResourceStream(manifestResourceName))
            {
                if (resource == null)
                {
                    throw new ArgumentException("No embedded resource found with the name " + manifestResourceName + " inside assembly: " + assembly.FullName);
                }

                using (var resourceStreamReader = new StreamReader(resource, Encoding.Default, true))
                {
                    return new CrmSolutionFile(scriptName, GetStreamBytes(resourceStreamReader.BaseStream));
                }
            }
        }

        /// <summary>
        /// Returns the Bytes from a stream, as a Byte Array.
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        protected static byte[] GetStreamBytes(Stream stream)
        {
            if (stream.CanSeek && stream.Position > 0)
            {
                stream.Seek(0, SeekOrigin.Begin);
            }
            if (stream.Position > 0)
            {
                throw new NotSupportedException("The stream containing the solution file must be at postion 0.");
            }

            var readBuffer = new byte[1024];
            var outputBytes = new List<byte>();

            //int offset = 0;

            while (true)
            {
                int bytesRead = stream.Read(readBuffer, 0, readBuffer.Length);
                if (bytesRead == 0)
                {
                    break;
                }
                if (bytesRead == readBuffer.Length)
                {
                    outputBytes.AddRange(readBuffer);
                }
                else
                {
                    var tempBuf = new byte[bytesRead];
                    Array.Copy(readBuffer, tempBuf, bytesRead);
                    outputBytes.AddRange(tempBuf);
                    break;
                }
                // offset += bytesRead;
            }
            return outputBytes.ToArray();
        }

        public Byte[] FileBytes { get; set; }

    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>bid.adonis.lau</groupId>
        <artifactId>springboot-demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

    <artifactId>springboot-validation-over-json</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-validation-over-json :: Validation with http over json Demo</name>

</project>


text:
package hope.admin;

import de.codecentric.boot.admin.config.EnableAdminServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableAdminServer
public class SpringBootAdminWebApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootAdminWebApplication.class, args);
    }
}


text:
alias toggleFn='osascript ~/Dropbox/Cooper/toggle-f-keys.scpt'

#shortcut to convertify directory
alias ccc='cd ~/sites/cfy'

#shortcut to sites
alias sites='cd ~/sites'

#google
alias ggl='google'


text:
define(['jquery','common/util', 'common/class', 'bootstrap-grid'], function ($, util, Class) {
    "use strict";

    var Grid = Class.create({
        initialize: function(options) {
            this.options = $.extend({}, defaults, options);
            var options = this.options;
            this.$element = $(options.element);
            this.$gridBar = $(options.barElement);

            this._init();
        },
        _init: function() {
            this._processOptions();
            this.render();
            //this._bindEvents();
        },
        _processOptions: function() {
            var self = this;
            var options = this.options;
            var checkColumnIndex = options.checkColumnIndex;
            var cellTemplates = [];
            var headerTemplates = [];
            var CHECK_ALL_HTML = '<input type="checkbox" class="checkbox" id="' + options.checkAllId + '"/>	';
            var CHECK_ITEM_HTML = '<input type="checkbox" class="checkbox">';

            // 有 checkbox
            if (options.hasCheckbox) {
                var colSize = options.columnNames.length + 1;

                if (options.cellTemplates !== null) {
                    this.options.cellTemplates.splice(checkColumnIndex, 0, CHECK_ITEM_HTML);
                } else {
                    for(var i = 0; i < colSize; i++) {
                        if (i == checkColumnIndex) {
                            cellTemplates[i] = CHECK_ITEM_HTML;
                        } else {
                            cellTemplates[i] = null;
                        }
                    }
                    this.options.cellTemplates = cellTemplates;
                }

                if (options.headerTemplates !== null) {
                    this.options.headerTemplates.splice(checkColumnIndex, 0, CHECK_ALL_HTML);
                } else {
                    for(var j = 0; j < colSize; j++) {
                        if (j == checkColumnIndex) {
                            headerTemplates[j] = CHECK_ALL_HTML;
                            break;
                        } else {
                            headerTemplates[j] = null;
                        }
                    }
                    this.options.headerTemplates = headerTemplates;
                }

                this.options.columnNames.splice(checkColumnIndex, 0, '');
                this.options.columnKeys.splice(checkColumnIndex, 0, null);
            }
            this.options.pageRenderedEvent = $.proxy(this.pageRenderedEvent, this);
        },
        postData: function() {

        },
        pageRenderedEvent: function() {
            var self = this;
            var options = this.options;
            this._parseElement();
            this.initGridBar();
            this._bindEvents();
            if (typeof options.gridRendered == 'function') {
                this.$element.simplePagingGrid('currentPageData', function(data) {
                    options.gridRendered.call(self, data);
                })
            }

        },
        $: function(el) {
            return this.$element.find(el);
        },
        initGridBar: function() {
            this.$gridBar.find('[data-role=multiCheck]').prop('disabled', true).addClass('disabled');
            this.$gridBar.find('[data-role=edit]').prop('disabled', true).addClass('disabled');
            this.options.hasCheckbox && this.$checkAll.prop('checked', false);
        },
        _parseElement: function() {
            this.$checkAll = $(this.options.checkAllId);
            this.$tbody = this.$('tbody');
        },
        _bindEvents: function() {
            this._bindRowEvent();
            this.options.hasCheckbox && this._bindCheckEvents();
        },
        _bindRowEvent: function() {
            var self = this;
            var options = self.options;
            this.$tbody.on('dblclick', 'tr', function() {
                var $row = $(this);
                var $check = $row.find('input[type=checkbox]');

                if (options.hasCheckbox) {
                    self.$element.find('input[type=checkbox]').prop('checked',false);
                    $check.prop('checked', true);
                }
                options.onDblClickRow && options.onDblClickRow.call(self.$gridBar);
            });
        },
        _bindCheckEvents: function() {
            var self = this;
            var options = self.options;
            var $checks = self.$tbody.find('input[type=checkbox]');
            //console.log(this.$checkAll)

            self.$element.on('click', 'input[type=checkbox]', function() {
                var $self = $(this);
                var $checks = self.$tbody.find('input[type=checkbox]');
                if ($self.attr('id') == self.options.checkAllId) {
                    $checks.prop('checked', $self.prop('checked'));
                    options.onCheckAll && options.onCheckAll.call(self.$gridBar, $self.prop('checked'));
                } else {
                    var len = $checks.length;
                    var checkedLen = self.$tbody.find(':checked').length;

                    self.$checkAll.prop('checked', checkedLen === len?true:false);
                    options.onCheck && options.onCheck.call(self.$gridBar, checkedLen, len);
                }
            })
        },

        /**
         * 获取单页checked的id集合
         * @return {Array}
         */
        getCheckedIds: function() {
            var ret = [];
            var self = this;

            if (!this.this.options.hasCheckbox) {
                return ret;
            }

            this.$element.simplePagingGrid('currentPageData', function(data) {
                self.$tbody.find(':checkbox').each(function(i) {
                    $(this).prop('checked') && data[i] && ret.push(data[i].id);
                });
            });
            return ret;
        },

        /**
         * 获取单条checked的数据
         * @return {{}}
         */
        getSingleData: function() {
            var ret = {};
            var self = this;

            if (!this.this.options.hasCheckbox) {
                return ret;
            }

            this.$element.simplePagingGrid('currentPageData', function(data) {
                self.$tbody.find(':checkbox').each(function(i) {
                    if ($(this).prop('checked')) {
                        ret = data[i];
                        return false;
                    }
                });
            });
            return ret;
        },
        render: function() {
            var self = this;
            var options = this.options;

            this.$element.simplePagingGrid(options);
        },
        refresh: function() {
            var dataUrl = this.options.dataUrl;
            this.$element.simplePagingGrid('refresh', dataUrl);
        }
    });
    var buttonBarTemplate = '
 \
                                    {{#if showGotoPage}} \

 \

 \
                                                <input class="form-control pagetextpicker" type="text" value="{{currentPage}}" /> \
                                                 \
                                                    <button class="btn btn-default pagetextpickerbtn" type="button">Go</button> \
                                                 \

 \

 \
                                    {{/if}} \

 \
                                        {{#if isFirstPage}} \
                                            {{#if pageNumbersEnabled}} \

 \
                                            {{/if}} \

 \
                                        {{/if}} \
                                        {{#unless isFirstPage}} \
                                            {{#if pageNumbersEnabled}} \

 \
                                            {{/if}} \

 \
                                        {{/unless}} \
                                        {{#if pageNumbersEnabled}} \
                                            {{#each pages}} \
                                                {{#if isCurrentPage}} \

{{displayPageNumber}}
 \
                                                {{/if}} \
                                                {{#unless isCurrentPage}} \

{{displayPageNumber}}
 \
                                                {{/unless}} \
                                            {{/each}} \
                                        {{/if}} \
                                        {{#if isLastPage}} \

 \
                                            {{#if pageNumbersEnabled}} \

 \
                                            {{/if}} \
                                        {{/if}} \
                                        {{#unless isLastPage}} \

 \
                                            {{#if pageNumbersEnabled}} \

 \
                                            {{/if}} \
                                        {{/unless}} \

 \

';

    var defaults = Grid.defaults = {
        element: '#J_Grid',
        pageSize: 15,
        barElement: '#J_GridBar',
        checkAllId: '#J_CheckAll',
        showLoadingOverlay: false,
        minimumVisibleRows: 15,
        urlUpdatingEnabled: false,
        templates: {
            buttonBarTemplate: buttonBarTemplate
        },
        /**
         * 是否有 checkbox
         * @type {Boolean}
         */
        hasCheckbox: false,
        checkColumnIndex: 1,
        tableClass: 'table table-bordered table-striped table-hover',

        /**
         * 表格数据渲染后执行的回调
         */
        gridRendered: null,

        /**
         * 是否全部选中触发事件
         * @param checked 是否全部选中
         */
        onCheckAll: null,

        /**
         * 选中触发事件
         * @param checkedLen 已选中的个数
         * @param len 单页的checkbox的个数
         */
        onCheck: null,
        cellTemplates: null,
        headerTemplates: null,
        columnNames: null,
        columnKeys: null
    };

    return Grid;
});


text:
**NOTE** Bazel build support is primarily for internal project infrastructure.
We strongly recommend users build with CMake instead.

This guide walks through building the core compiler and runtime parts of IREE
from source. Auxiliary components like the Python bindings and Vulkan driver are
documented separately, as they require further setup.

## Prerequisites

### Install Bazel

Install Bazel, matching IREE's
[`.bazelversion`](https://github.com/iree-org/iree/blob/main/.bazelversion) by
following the
[official docs](https://docs.bazel.build/versions/master/install.html).

### Install a Compiler

We recommend Clang. GCC is not fully supported.

```shell
$ sudo apt install clang
```

Set environment variables for Bazel:

```shell
export CC=clang
export CXX=clang++
```

### Install python3 numpy

```shell
$ python3 -m pip install numpy
```

## Clone and Build

### Clone

Clone the repository, initialize its submodules and configure:

```shell
$ git clone https://github.com/iree-org/iree.git
$ cd iree
$ git submodule update --init
$ python3 configure_bazel.py
```

> Tip:

>     Editors and other programs can also clone the
> repository, just make sure that they initialize the submodules.

### Build

Run all core tests:

```shell
$ bazel test -k iree/...
```

> Tip:

>     You can add flags like
> `--test_env=IREE_VULKAN_DISABLE=1` to your test command to change how/which
> tests run.

In general, build artifacts will be under the `bazel-bin` directory at the top
level.

## Recommended user.bazelrc

You can put a user.bazelrc at the root of the repository and it will be ignored
by git. The recommended contents for Linux are:

```shell
build --disk_cache=/tmp/bazel-cache

# Use --config=debug to compile IREE and LLVM without optimizations
# and with assertions enabled.
build:debug --config=asserts --compilation_mode=opt '--per_file_copt=iree|llvm@-O0' --strip=never

# Use --config=asserts to enable assertions. This has to be done globally:
# Code compiled with and without assertions can't be linked together (ODR violation).
build:asserts --compilation_mode=opt '--copt=-UNDEBUG'
```

## What's next?

### Take a Look Around

Build all of IREE's 'tools' directory:

```shell
$ bazel build tools/...
```

Check out what was built:

```shell
$ ls bazel-bin/tools/
$ ./bazel-bin/tools/iree-compile --help
```

Translate a
[MLIR file](https://github.com/iree-org/iree/blob/main/samples/models/simple_abs.mlir)
and execute a function in the compiled module:

```shell
# iree-run-mlir <compiler flags> [input.mlir] <runtime flags>
$ ./bazel-bin/tools/iree-run-mlir \
  --iree-hal-target-backends=vmvx --print-mlir \
  ./samples/models/simple_abs.mlir \
  --function_input=f32=-2
```


text:
// Copyright 2019 DeepMind Technologies Limited
//
// 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.

#include "open_spiel/games/pig.h"

#include <sys/types.h>

#include <utility>

#include "open_spiel/game_parameters.h"
#include "open_spiel/spiel.h"
#include "open_spiel/utils/tensor_view.h"

namespace open_spiel {
namespace pig {

namespace {
// Moves.
enum ActionType { kRoll = 0, kStop = 1 };

// Bin size for the information state vectors: how many score values to put
// into one bin. Higher means more coarser.
constexpr int kBinSize = 1;

// Default parameters.
constexpr int kDefaultDiceOutcomes = 6;
constexpr int kDefaultHorizon = 1000;
constexpr int kDefaultPlayers = 2;
constexpr int kDefaultWinScore = 100;
constexpr bool kDefaultPiglet = false;

// Facts about the game
const GameType kGameType{
    /*short_name=*/"pig",
    /*long_name=*/"Pig",
    GameType::Dynamics::kSequential,
    GameType::ChanceMode::kExplicitStochastic,
    GameType::Information::kPerfectInformation,
    GameType::Utility::kZeroSum,
    GameType::RewardModel::kTerminal,
    /*max_num_players=*/10,
    /*min_num_players=*/2,
    /*provides_information_state_string=*/false,
    /*provides_information_state_tensor=*/false,
    /*provides_observation_string=*/true,
    /*provides_observation_tensor=*/true,
    /*parameter_specification=*/
    {
        {"players", GameParameter(kDefaultPlayers)},
        {"horizon", GameParameter(kDefaultHorizon)},
        {"winscore", GameParameter(kDefaultWinScore)},
        {"diceoutcomes", GameParameter(kDefaultDiceOutcomes)},
        {"piglet", GameParameter(kDefaultPiglet)},
    }};

static std::shared_ptr<const Game> Factory(const GameParameters& params) {
  return std::shared_ptr<const Game>(new PigGame(params));
}

REGISTER_SPIEL_GAME(kGameType, Factory);
}  // namespace

std::string PigState::ActionToString(Player player, Action move_id) const {
  if (player == kChancePlayerId) {
    return absl::StrCat("Roll ", piglet_ ? move_id : 1 + move_id);
  } else if (move_id == kRoll) {
    return "roll";
  } else {
    return "stop";
  }
}

bool PigState::IsTerminal() const {
  if (total_moves_ >= horizon_) {
    return true;
  }

  for (auto p = Player{0}; p < num_players_; p++) {
    if (scores_[p] >= win_score_) {
      return true;
    }
  }
  return false;
}

std::vector<double> PigState::Returns() const {
  if (!IsTerminal()) {
    return std::vector<double>(num_players_, 0.0);
  }

  // For (n>2)-player games, must keep it zero-sum.
  std::vector<double> returns(num_players_, -1.0 / (num_players_ - 1));

  for (auto player = Player{0}; player < num_players_; ++player) {
    if (scores_[player] >= win_score_) {
      returns[player] = 1.0;
      return returns;
    }
  }

  // Nobody has won? (e.g. over horizon length.) Then everyone gets 0.
  return std::vector<double>(num_players_, 0.0);
}

std::string PigState::ObservationString(Player player) const {
  SPIEL_CHECK_GE(player, 0);
  SPIEL_CHECK_LT(player, num_players_);
  return ToString();
}

std::vector<int> PigGame::ObservationTensorShape() const {
  int num_bins = (win_score_ / kBinSize) + 1;
  return {1 + num_players_, num_bins};
}

void PigState::ObservationTensor(Player player,
                                 absl::Span<float> values) const {
  SPIEL_CHECK_GE(player, 0);
  SPIEL_CHECK_LT(player, num_players_);

  // One extra bin for when value is >= max.
  // So for win_score_ 100, binSize = 1 -> 0, 1, ..., 99, >= 100.
  int num_bins = (win_score_ / kBinSize) + 1;

  // One-hot encoding: turn total (#bin) followed by p1, p2, ...
  // Treat `values` as a 2-d tensor.
  TensorView<2> view(values, {1 + num_players_, num_bins}, true);

  // One-hot encoding:
  //  - turn total (#bins)
  //  - player 0 (#bins)
  //  - player 1 (#bins)
  //      .
  //      .
  //      .

  // turn total
  view[{0, std::min(turn_total_ / kBinSize, num_bins - 1)}] = 1;

  for (auto p = Player{0}; p < num_players_; p++) {
    // score of each player
    view[{1 + p, std::min(scores_[p] / kBinSize, num_bins - 1)}] = 1;
  }
}

PigState::PigState(std::shared_ptr<const Game> game, int dice_outcomes,
                   int horizon, int win_score, bool piglet)
    : State(game),
      dice_outcomes_(dice_outcomes),
      horizon_(horizon),
      win_score_(win_score),
      piglet_(piglet) {
  total_moves_ = 0;
  cur_player_ = 0;
  turn_player_ = 0;
  scores_.resize(game->NumPlayers(), 0);
  turn_total_ = 0;
}

int PigState::CurrentPlayer() const {
  return IsTerminal() ? kTerminalPlayerId : cur_player_;
}

void PigState::DoApplyAction(Action move) {
  // For decision node: 0 means roll, 1 means stop.
  // For chance node: outcome of the dice (x-1, piglet: [x != 1]).
  if (cur_player_ >= 0 && move == kRoll) {
    // Player roll -> chance node.
    cur_player_ = kChancePlayerId;
    total_moves_++;
  } else if (cur_player_ >= 0 && move == kStop) {
    // Player stops. Take turn total and pass to next player.
    scores_[turn_player_] += turn_total_;
    turn_total_ = 0;
    turn_player_ = NextPlayerRoundRobin(turn_player_, num_players_);
    cur_player_ = turn_player_;
    total_moves_++;
  } else if (IsChanceNode()) {
    // Resolve chance node outcome. If 1, reset turn total and change players;
    // else, add to total and keep going.
    if (move == 0) {
      // Reset turn total and loses turn!
      turn_total_ = 0;
      turn_player_ = NextPlayerRoundRobin(turn_player_, num_players_);
      cur_player_ = turn_player_;
    } else {
      // Add to the turn total.
      turn_total_ += (piglet_ ? 1 : move + 1);
      cur_player_ = turn_player_;
    }
  } else {
    SpielFatalError(absl::StrCat("Move ", move, " is invalid."));
  }
}

std::vector<Action> PigState::LegalActions() const {
  if (IsChanceNode()) {
    return LegalChanceOutcomes();
  } else if (IsTerminal()) {
    return {};
  } else {
    if (scores_[cur_player_] + turn_total_ >= win_score_) {
      return {kStop};
    } else {
      return {kRoll, kStop};
    }
  }
}

std::vector<std::pair<Action, double>> PigState::ChanceOutcomes() const {
  SPIEL_CHECK_TRUE(IsChanceNode());
  std::vector<std::pair<Action, double>> outcomes;

  if (piglet_) {
    // Chance outcomes are labelled 0 or 1, corresponding to rolling 1 or not 1
    // respectively
    outcomes.reserve(2);
    outcomes.push_back(std::make_pair(0, 1.0 / dice_outcomes_));
    outcomes.push_back(std::make_pair(1, 1.0 - (1.0 / dice_outcomes_)));
  } else {
    // Chance outcomes are labelled 0+, corresponding to rolling 1+x.
    outcomes.reserve(dice_outcomes_);
    for (int i = 0; i < dice_outcomes_; i++) {
      outcomes.push_back(std::make_pair(i, 1.0 / dice_outcomes_));
    }
  }

  return outcomes;
}

std::string PigState::ToString() const {
  return absl::StrCat("Scores: ", absl::StrJoin(scores_, " "),
                      ", Turn total: ", turn_total_,
                      "\nCurrent player: ", turn_player_,
                      (cur_player_ == kChancePlayerId ? " (rolling)\n" : "\n"));
}

std::unique_ptr<State> PigState::Clone() const {
  return std::unique_ptr<State>(new PigState(*this));
}

PigGame::PigGame(const GameParameters& params)
    : Game(kGameType, params),
      dice_outcomes_(ParameterValue<int>("diceoutcomes")),
      horizon_(ParameterValue<int>("horizon")),
      num_players_(ParameterValue<int>("players")),
      win_score_(ParameterValue<int>("winscore")),
      piglet_(ParameterValue<bool>("piglet")) {}

}  // namespace pig
}  // namespace open_spiel


text:
<?php

//----------------------------------------------------------------------
//
//  Copyright (C) 2018 Artem Rodygin
//
//  You should have received a copy of the MIT License along with
//  this file. If not, see <http://opensource.org/licenses/MIT>.
//
//----------------------------------------------------------------------

namespace Linode\Entity\NodeBalancers;

use Linode\Entity\Entity;
use Linode\Internal\NodeBalancers\NodeBalancerNodeRepository;

/**
 * A NodeBalancer config represents the configuration of this NodeBalancer
 * on a single port. For example, a NodeBalancer Config on port 80 would
 * typically represent how this NodeBalancer response to HTTP requests.
 *
 * NodeBalancer configs have a list of backends, called "nodes," that they
 * forward requests between based on their configuration.
 *
 * @property int         $id              This config's unique ID.
 * @property int         $port            The port this Config is for. These values must be unique across configs
 *                                        on a single NodeBalancer (you can't have two configs for port 80, for
 *                                        example). While some ports imply some protocols, no enforcement is done
 *                                        and you may configure your NodeBalancer however is useful to you. For
 *                                        example, while port 443 is generally used for HTTPS, you do not need
 *                                        SSL configured to have a NodeBalancer listening on port 443.
 * @property string      $protocol        The protocol this port is configured to serve. If this is set to `https`
 *                                        you must include an `ssl_cert` and an `ssl_key`.
 * @property string      $algorithm       What algorithm this NodeBalancer should use for routing traffic to backends.
 * @property string      $stickiness      Controls how session stickiness is handled on this port.
 * @property string      $check           The type of check to perform against backends to ensure they are serving
 *                                        requests. This is used to determine if backends are up or down.
 * @property int         $check_interval  How often, in seconds, to check that backends are up and serving requests.
 * @property int         $check_timeout   How long, in seconds, to wait for a check attempt before considering it failed.
 * @property int         $check_attempts  How many times to attempt a check before considering a backend to be down.
 * @property string      $check_path      The URL path to check on each backend. If the backend does not respond
 *                                        to this request it is considered to be down.
 * @property string      $check_body      This value must be present in the response body of the check in order for
 *                                        it to pass. If this value is not present in the response body of a check
 *                                        request, the backend is considered to be down.
 * @property bool        $check_passive   If true, any response from this backend with a `5xx` status code will be
 *                                        enough for it to be considered unhealthy and taken out of rotation.
 * @property string      $cipher_suite    What ciphers to use for SSL connections served by this NodeBalancer.
 * @property string      $ssl_commonname  The common name for the SSL certification this port is serving
 *                                        if this port is not configured to use SSL.
 * @property string      $ssl_fingerprint The fingerprint for the SSL certification this port is serving
 *                                        if this port is not configured to use SSL.
 * @property string      $ssl_cert        The certificate this port is serving. This is not returned. If set,
 *                                        this field will come back as "<REDACTED>".
 * @property string      $ssl_key         The private key corresponding to this port's certificate. This is not
 *                                        returned. If set, this field will come back as "<REDACTED>".
 * @property int         $nodebalancer_id The ID for the NodeBalancer this config belongs to.
 * @property NodesStatus $nodes_status    A structure containing information about the health of the backends
 *                                        for this port. This information is updated periodically as checks
 *                                        are performed against backends.
 * @property \Linode\Repository\NodeBalancers\NodeBalancerNodeRepositoryInterface $nodes Nodes of the config.
 */
class NodeBalancerConfig extends Entity
{
    // Available fields.
    public const FIELD_ID              = 'id';
    public const FIELD_PORT            = 'port';
    public const FIELD_PROTOCOL        = 'protocol';
    public const FIELD_ALGORITHM       = 'algorithm';
    public const FIELD_STICKINESS      = 'stickiness';
    public const FIELD_CHECK           = 'check';
    public const FIELD_CHECK_INTERVAL  = 'check_interval';
    public const FIELD_CHECK_TIMEOUT   = 'check_timeout';
    public const FIELD_CHECK_ATTEMPTS  = 'check_attempts';
    public const FIELD_CHECK_PATH      = 'check_path';
    public const FIELD_CHECK_BODY      = 'check_body';
    public const FIELD_CHECK_PASSIVE   = 'check_passive';
    public const FIELD_CIPHER_SUITE    = 'cipher_suite';
    public const FIELD_SSL_COMMONNAME  = 'ssl_commonname';
    public const FIELD_SSL_FINGERPRINT = 'ssl_fingerprint';
    public const FIELD_SSL_CERT        = 'ssl_cert';
    public const FIELD_SSL_KEY         = 'ssl_key';

    // Extra field for create/update operations.
    public const FIELD_NODES = 'nodes';

    // Protocols.
    public const PROTOCOL_HTTP  = 'http';
    public const PROTOCOL_HTTPS = 'https';
    public const PROTOCOL_TCP   = 'tcp';

    // Rotation algorithms.
    public const ALGORITHM_ROUNDROBIN = 'roundrobin';
    public const ALGORITHM_LEASTCONN  = 'leastconn';
    public const ALGORITHM_SOURCE     = 'source';

    // Session stickiness.
    public const STICKINESS_NONE        = 'none';
    public const STICKINESS_TABLE       = 'table';
    public const STICKINESS_HTTP_COOKIE = 'http_cookie';

    // Check types.
    public const CHECK_NONE       = 'none';
    public const CHECK_CONNECTION = 'connection';
    public const CHECK_HTTP       = 'http';
    public const CHECK_HTTP_BODY  = 'http_body';

    // Cipher suites.
    public const CIPHER_RECOMMENDED = 'recommended';
    public const CIPHER_LEGACY      = 'legacy';

    /**
     * {@inheritdoc}
     */
    public function __get(string $name)
    {
        if ($name === 'nodes_status') {
            return new NodesStatus($this->client, $this->data[$name]);
        }

        if ($name === 'nodes') {
            return new NodeBalancerNodeRepository($this->client, $this->nodebalancer_id, $this->id);
        }

        return parent::__get($name);
    }
}


text:
<?php

/**
 * PHPExcel_RichText_ITextElement
 *
 * @category   PHPExcel
 * @package    PHPExcel_RichText
 * @copyright  Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
 */
interface PHPExcel_RichText_ITextElement
{
	/**
	 * Get text
	 *
	 * @return string	Text
	 */
	public function getText();

	/**
	 * Set text
	 *
	 * @param 	$pText string	Text
	 * @return PHPExcel_RichText_ITextElement
	 */
	public function setText($pText = '');

	/**
	 * Get font
	 *
	 * @return PHPExcel_Style_Font
	 */
	public function getFont();

	/**
	 * Get hash code
	 *
	 * @return string	Hash code
	 */
	public function getHashCode();
}


text:
using System.Drawing;
using System.IO;
using ImageProcessor;
using ImageProcessor.Imaging;
using ImageProcessor.Imaging.Formats;
using Microsoft.Azure.WebJobs;
using Microsoft.ServiceBus.Messaging;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.Table;

namespace Nancy.Demo.AzureWebSitesWithWebJobs.Job
{
    public class Functions
    {
        public static void ProcessImageQueueMessage(
            [QueueTrigger("images")] Common.Entities.Image img,
            [Blob("images/uploads/{Id}")] CloudBlockBlob uploadedBlob,
            [Blob("images/handled/{Id}.img")] CloudBlockBlob outputBlob,
            [Blob("images/handled/{Id}_thumbnail.img")] CloudBlockBlob outputThumbnailBlob,
            [Table("images")]CloudTable imageTable,
            [ServiceBus("images")] out string message,
            TextWriter log)
        {
            log.WriteLine("Got message from queue to process image: " + img.Source + ", with ID: " + img.RowKey);

            using (var input = new MemoryStream())
            {
                uploadedBlob.DownloadToStream(input);
                using (var output = outputThumbnailBlob.OpenWrite())
                {
                    ProcessImage(img.ContentType, input, output, quality: 70, maxWidth: 150);
                    outputThumbnailBlob.Properties.ContentType = img.ContentType;
                    outputThumbnailBlob.Properties.CacheControl = "public, max-age=31536000"; // 1 year cache
                }
                log.WriteLine("Created thumbnail for " + img.Id);
                using (var output = outputBlob.OpenWrite())
                {
                    ProcessImage(img.ContentType, input, output, quality: 90, maxWidth: 1920);
                    outputBlob.Properties.ContentType = img.ContentType;
                    outputBlob.Properties.CacheControl = "public, max-age=31536000"; // 1 year cache
                }
            }
            log.WriteLine("Created full image for " + img.Id);

            // Insert to table storage
            img.Source = outputBlob.Uri.AbsolutePath;
            img.Thumbnail = outputThumbnailBlob.Uri.AbsolutePath;

            var opp = TableOperation.Insert(img);
            imageTable.Execute(opp);
            log.WriteLine("Inserted outputted image for " + img.Id);

            //using (var m = new MemoryStream())
            //{
            //    using (var t = new StreamWriter(m))
            //    {
            //        t.Write("ImageUploaded");
            //        t.Flush();
            //    }
            //    message = new BrokeredMessage(m);
            //}
            message = "ImageUploaded";
            uploadedBlob.DeleteIfExists();
            log.WriteLine("Message to service bus assigned");
        }

        private static void ProcessImage(string contentType, Stream input, Stream output, int quality, int maxWidth)
        {
            ISupportedImageFormat format = new JpegFormat { Quality = quality };
            if (contentType == "image/gif")
                format = new GifFormat { Quality = quality };
            if (contentType == "image/png")
                format = new PngFormat { Quality = quality };
            var maxSize = new Size(maxWidth, 0);
            var resize = new ResizeLayer(maxSize, ResizeMode.Max, AnchorPosition.Center, false, null, maxSize);
            using (var memoryOutput = new MemoryStream())
            {
                using (var imageFactory = new ImageFactory(preserveExifData: true))
                {
                    imageFactory.Load(input)
                                .Resize(resize)
                                .Format(format)
                                .Save(memoryOutput);
                }
                memoryOutput.Seek(0, SeekOrigin.Begin);
                memoryOutput.CopyTo(output);
            }
        }
    }
}


text: Testbench in this folder may not work properly due to source code change.


text:
/* config.h.  Generated by configure.  */
/* config.h.in -- template for config.h			-*- C -*-
 *
 *   Copyright (C) 1996-2014 by Ian Piumarta and other authors/contributors
 *                              listed elsewhere in this file.
 *   All rights reserved.
 *
 *   This file is part of Unix Squeak.
 *
 *   Permission is hereby granted, free of charge, to any person obtaining a
 *   copy of this software and associated documentation files (the "Software"),
 *   to deal in the Software without restriction, including without limitation
 *   the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *   and/or sell copies of the Software, and to permit persons to whom the
 *   Software is furnished to do so, subject to the following conditions:
 *
 *   The above copyright notice and this permission notice shall be included in
 *   all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 *   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 *   DEALINGS IN THE SOFTWARE.
 */

/* Author: Ian.Piumarta@squeakland.org
 *
 * Last edited: 2014-12-02 11:16 by eliot.miranda@gmail.com
 *
 * THIS FILE IS A BUG!!  It *SHOULD NOT* exist!  Any automatically-derived
 * configuration should be produced at compile-time, not hard-wired like this
 * excressence.  But at least for the time being we're stuck with it.
 * eem 12/2/2014 11:16
 */

#ifndef __sq_config_h
#define __sq_config_h

/* package options */

#define	USE_X11 1
/* #undef	USE_X11_GLX */
#define	USE_QUARTZ 1
#define	USE_QUARTZ_CGL 1
/* #undef	USE_RFB */

/* libraries */

/* #undef	HAVE_LIBX11 */
#define	HAVE_LIBXEXT 1
/* #undef	HAVE_LIBDL */
#define	HAVE_DYLD 1
/* #undef	HAVE_LIBFFI */
/* #undef	HAVE_ICONV */

/* #undef	USE_AUDIO_NONE */
/* #undef	USE_AUDIO_SUN */
/* #undef	USE_AUDIO_NAS */
/* #undef	USE_AUDIO_OSS */
/* #undef	USE_AUDIO_MACOSX */
/* #undef	OSS_DEVICE */

/* header files */

#define	HAVE_UNISTD_H 1
/* #undef	NEED_GETHOSTNAME_P */

#define	HAVE_DIRENT_H 1
/* #undef	HAVE_SYS_NDIR_H */
/* #undef	HAVE_SYS_DIR_H */
/* #undef	HAVE_NDIR_H */

#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3
#undef	HAVE_DLFCN_H
#else
#define	HAVE_DLFCN_H 1
#endif

#define	HAVE_ICONV_H 1

#define	HAVE_SYS_TIME_H 1
#define	TIME_WITH_SYS_TIME 1

#define	HAVE_SYS_FILIO_H 1

/* #undef	HAVE_SYS_AUDIOIO_H */
/* #undef	HAVE_SUN_AUDIOIO_H */

/* #undef	HAVE_PTY_H */
#define	HAVE_UTIL_H 1
/* #undef	HAVE_LIBUTIL_H */
/* #undef	HAVE_STROPTS_H */

/* #undef	HAVE_GL_GL_H */
#define	HAVE_OPENGL_GL_H 1

/* system calls/library functions */

#define	AT_EXIT atexit

#define	HAVE_EXECINFO_H 1
#define	HAVE_TZSET 1

#define	HAVE_OPENPTY 1
/* #undef	HAVE_UNIX98_PTYS */

#define	HAVE_SNPRINTF 1
/* #undef	HAVE___SNPRINTF */

#define	HAVE_MMAP 1

#define	HAVE_DYLD 1

#define	HAVE_LANGINFO_CODESET 1

#define	HAVE_ALLOCA 1
#define	HAVE_ALLOCA_H 1

#define	HAVE_UNSETENV 1

/* widths of primitive types */

#if _LP64 || __x86_64 || __x86_64__
# define SIZEOF_INT 4
# define SIZEOF_LONG 8
# define SIZEOF_LONG_LONG 8
# define SIZEOF_VOID_P 8
#endif

#if (i386 || __i386 || __i386__) || (ppc || __ppc || __ppc__)
# define SIZEOF_INT 4
# define SIZEOF_LONG 4
# define SIZEOF_LONG_LONG 8
# define SIZEOF_VOID_P 4
#endif

/* structures */

#define	HAVE_TM_GMTOFF 1
#define	HAVE_TIMEZONE 1

/* typedefs */

/* #undef	size_t */

/* architecture */

#define	OS_TYPE "unix"

/* #undef	VM_HOST_VENDOR */
/* #undef	VM_HOST_OS */

#if defined(__BIG_ENDIAN__)
# define	WORDS_BIGENDIAN 1
# define VMENDIANNESS 1
#else
# undef	WORDS_BIGENDIAN
# define VMENDIANNESS 0
# define LSB_FIRST 1
#endif

#define HAVE_LIBDL 1

/* damage containment */

#define	DARWIN 1

/* other configured variables */

#define VM_MODULE_PREFIX ""
/* #undef VM_DLSYM_PREFIX */
#define VM_X11DIR "/usr/X11R6/lib"

/* avoid dependencies on glibc2.3 */

/* #undef HAVE_FEATURES_H */

#endif /* __sq_config_h */


text:
package org.westfield.action;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import junit.framework.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import org.westfield.TestHelper;
import org.westfield.configuration.LookupHint;
import org.westfield.configuration.MediaToolConfig;
import org.westfield.media.HDHomeRunTagParser;
import org.westfield.media.IMediaDetails;
import org.westfield.parser.TokenParser;

import java.nio.file.Path;

import static org.mockito.Mockito.when;

public class ShowLookupTest
{

    @Test
    public void showLookupNoHintsTest() throws Exception
    {
        MediaToolConfig config =  Mockito.mock(MediaToolConfig.class);
        when(config.getShowLookup()).thenReturn(ImmutableMap.of(
                "key", "70FBF9A03F0D083D",
                "enabled", "true",
                "cache_key", "true",
                "cache_location", "/tmp/theTvdbKey.dat"
        ));
        Path item = TestHelper.getTestResourcePath("criminal-s11e03.dat");
        IMediaDetails media_details = HDHomeRunTagParser.fromFile(item.toFile());

        ShowLookup subject = new ShowLookup();
        subject.configure(config);
        subject.describe();
        IMediaDetails result = subject.process(media_details);

        Assert.assertEquals(18, result.getExtendedDetails().size());
        Assert.assertEquals("199", result.getExtendedDetails().getOrDefault("absoluteNumber", -1));
    }

    @Test
    public void showLookupWithIDHints() throws Exception
    {
        MediaToolConfig config =  Mockito.mock(MediaToolConfig.class);
        when(config.getShowLookup()).thenReturn(ImmutableMap.of(
                "key", "70FBF9A03F0D083D",
                "enabled", "true",
                "cache_key", "true",
                "cache_location", "/tmp/theTvdbKey.dat"
        ));
        when(config.getLookupHints()).thenReturn(ImmutableList.of(
                new LookupHint("S.W.A.T.", 328687, null, null)
        ));
        Path item = TestHelper.getTestResourcePath("swat-s01e02.dat");
        IMediaDetails media_details = HDHomeRunTagParser.fromFile(item.toFile());

        ShowLookup subject = new ShowLookup();
        subject.configure(config);
        IMediaDetails result = subject.process(media_details);

        org.junit.Assert.assertEquals("2", TokenParser.getMediaToken(media_details, "{absoluteNumber}"));
        org.junit.Assert.assertEquals("1", TokenParser.getMediaToken(media_details, "{airedSeason}"));
        org.junit.Assert.assertEquals("2", TokenParser.getMediaToken(media_details, "{dvdEpisodeNumber}"));
        org.junit.Assert.assertEquals("1", TokenParser.getMediaToken(media_details, "{dvdSeason}"));
        org.junit.Assert.assertEquals("Cuchillo", TokenParser.getMediaToken(media_details, "{episodeName}"));
        org.junit.Assert.assertEquals("2017-11-09", TokenParser.getMediaToken(media_details, "{firstAired}"));
        org.junit.Assert.assertEquals("328687", TokenParser.getMediaToken(media_details, "{id}"));
        org.junit.Assert.assertEquals("CBS", TokenParser.getMediaToken(media_details, "{network}"));
        org.junit.Assert.assertEquals("Continuing", TokenParser.getMediaToken(media_details, "{status}"));
    }

    @Test
    public void showLookupWithImDbTest() throws Exception
    {
        MediaToolConfig config =  Mockito.mock(MediaToolConfig.class);
        when(config.getShowLookup()).thenReturn(ImmutableMap.of(
                "key", "70FBF9A03F0D083D",
                "enabled", "true",
                "cache_key", "true",
                "cache_location", "/tmp/theTvdbKey.dat"
        ));
        when(config.getLookupHints()).thenReturn(ImmutableList.of(
                new LookupHint("Food Factory", 268860, "tt2558662", null)
        ));
        Path item = TestHelper.getTestResourcePath("food-s03e03.dat");
        IMediaDetails media_details = HDHomeRunTagParser.fromFile(item.toFile());

        ShowLookup subject = new ShowLookup();
        subject.configure(config);
        IMediaDetails result = subject.process(media_details);

        org.junit.Assert.assertNull(TokenParser.getMediaToken(media_details, "{absoluteNumber}"));
        org.junit.Assert.assertEquals("3", TokenParser.getMediaToken(media_details, "{airedSeason}"));
        org.junit.Assert.assertNull( TokenParser.getMediaToken(media_details, "{dvdEpisodeNumber}"));
        org.junit.Assert.assertNull( TokenParser.getMediaToken(media_details, "{dvdSeason}"));
        org.junit.Assert.assertEquals("1", TokenParser.getMediaToken(media_details, "{airedEpisodeNumber}"));
        org.junit.Assert.assertEquals("Smell The Coffee", TokenParser.getMediaToken(media_details, "{episodeName}"));
        org.junit.Assert.assertEquals("2014-01-11", TokenParser.getMediaToken(media_details, "{firstAired}"));
        org.junit.Assert.assertEquals("268860", TokenParser.getMediaToken(media_details, "{id}"));
        org.junit.Assert.assertEquals("Food Network Canada", TokenParser.getMediaToken(media_details, "{network}"));
        org.junit.Assert.assertEquals("Continuing", TokenParser.getMediaToken(media_details, "{status}"));
    }
}


text:
@implementation UIImage (UU)

//修改图片尺寸(会变模糊)
+ (UIImage*)OriginImage:(UIImage *)image scaleToSize:(CGSize)size
{
    UIGraphicsBeginImageContext(size);  //size 为CGSize类型,即你所需要的图片尺寸

    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];

    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return scaledImage;   //返回的就是已经改变的图片
}

//修改图片尺寸(不会变模糊)
-(UIImage*)scaleToSize:(CGSize)size
{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    //Determine whether the screen is retina
    if([[UIScreen mainScreen] scale] == 2.0){
        UIGraphicsBeginImageContextWithOptions(size, NO, 2.0);
    }else{
        UIGraphicsBeginImageContext(size);
    }
    // 绘制改变大小的图片
    [self drawInRect:CGRectMake(0, 0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    // 返回新的改变大小后的图片
    return scaledImage;
}

//图片合并
+ (UIImage *)addImage:(UIImage *)image1 WithSize:(CGSize)image1Size toImage:(UIImage *)image2 startX:(float)startX startY:(float)startY proportion:(float)proportion
{
    UIGraphicsBeginImageContext(image2.size);

    //Draw image2
    [image2 drawInRect:CGRectMake(0, 0, image2.size.width, image2.size.height)];

    //Draw image1
    [image1 drawInRect:CGRectMake(startX, startY, image1Size.width * proportion, image1Size.height * proportion)];

    UIImage *resultImage=UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return resultImage;
}

//颜色转换成图片
+ (UIImage*)jImageWithColor:(UIColor*)color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

//颜色转换成图片
+ (UIImage *)jImageWithColor:(UIColor *)color size:(CGSize)size alpha:(float)alpha
{
    @autoreleasepool {
        CGRect rect = CGRectMake(0, 0, size.width, size.height);
        UIGraphicsBeginImageContext(rect.size);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetAlpha(context, alpha);
        CGContextSetFillColorWithColor(context,color.CGColor);
        CGContextFillRect(context, rect);
        UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return img;
    }
}

//获取调整大小后的图片
+ (UIImage *)resizableImageWithName:(NSString *)imageName {
    //加载原来的图片
    UIImage *norImage = [UIImage imageNamed:imageName];
    //获取原来图片的宽高一半
    CGFloat W = norImage.size.width * 0.5;
    CGFloat H = norImage.size.height * 0.5;
    //生成可以拉伸指定位置的图片
    UIImage *newImage = [norImage resizableImageWithCapInsets:UIEdgeInsetsMake(H, W, H, W) resizingMode:UIImageResizingModeStretch];
    return newImage;
}

@end


text:
package org.apache.gobblin.runtime;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.testng.Assert;
import org.testng.annotations.Test;

public class CountUpAndDownLatchTest {

  @Test
  public void test() throws Exception {

    ExecutorService executorService = null;
    try {
      executorService = Executors.newFixedThreadPool(1);

      CountUpAndDownLatch countUpAndDownLatch = new CountUpAndDownLatch(1);

      Assert.assertFalse(countUpAndDownLatch.await(50, TimeUnit.MILLISECONDS));

      countUpAndDownLatch.countUp();
      Assert.assertFalse(countUpAndDownLatch.await(50, TimeUnit.MILLISECONDS));

      countUpAndDownLatch.countDown();
      Assert.assertFalse(countUpAndDownLatch.await(50, TimeUnit.MILLISECONDS));

      countUpAndDownLatch.countDown();
      Assert.assertTrue(countUpAndDownLatch.await(1, TimeUnit.SECONDS));

      // count-up again
      countUpAndDownLatch.countUp();
      // verify we will wait even though the latch was at 0 before
      Assert.assertFalse(countUpAndDownLatch.await(50, TimeUnit.MILLISECONDS));

      countUpAndDownLatch.countDown();
      Assert.assertTrue(countUpAndDownLatch.await(1, TimeUnit.SECONDS));
    } finally {
      if (executorService != null) {
        executorService.shutdownNow();
      }
    }
  }

}


text:
/**
 * @implements {UI.ListWidget.Delegate}
 * @unrestricted
 */
Persistence.EditFileSystemView = class extends UI.VBox {
  /**
   * @param {string} fileSystemPath
   */
  constructor(fileSystemPath) {
    super(true);
    this.registerRequiredCSS('persistence/editFileSystemView.css');
    this._fileSystemPath = fileSystemPath;

    this._eventListeners = [
      Persistence.isolatedFileSystemManager.addEventListener(
          Persistence.IsolatedFileSystemManager.Events.ExcludedFolderAdded, this._update, this),
      Persistence.isolatedFileSystemManager.addEventListener(
          Persistence.IsolatedFileSystemManager.Events.ExcludedFolderRemoved, this._update, this)
    ];

    const excludedFoldersHeader = this.contentElement.createChild('div', 'file-system-header');
    excludedFoldersHeader.createChild('div', 'file-system-header-text').textContent =
        Common.UIString('Excluded folders');
    excludedFoldersHeader.appendChild(
        UI.createTextButton(Common.UIString('Add'), this._addExcludedFolderButtonClicked.bind(this), 'add-button'));
    this._excludedFoldersList = new UI.ListWidget(this);
    this._excludedFoldersList.element.classList.add('file-system-list');
    this._excludedFoldersList.registerRequiredCSS('persistence/editFileSystemView.css');
    const excludedFoldersPlaceholder = createElementWithClass('div', 'file-system-list-empty');
    excludedFoldersPlaceholder.textContent = Common.UIString('None');
    this._excludedFoldersList.setEmptyPlaceholder(excludedFoldersPlaceholder);
    this._excludedFoldersList.show(this.contentElement);

    this.contentElement.tabIndex = 0;
    this._update();
  }

  dispose() {
    Common.EventTarget.removeEventListeners(this._eventListeners);
  }

  _update() {
    if (this._muteUpdate)
      return;

    this._excludedFoldersList.clear();
    this._excludedFolders = [];
    for (const folder of Persistence.isolatedFileSystemManager.fileSystem(this._fileSystemPath)
             .excludedFolders()
             .values()) {
      this._excludedFolders.push(folder);
      this._excludedFoldersList.appendItem(folder, true);
    }
  }

  _addExcludedFolderButtonClicked() {
    this._excludedFoldersList.addNewItem(0, '');
  }

  /**
   * @override
   * @param {*} item
   * @param {boolean} editable
   * @return {!Element}
   */
  renderItem(item, editable) {
    const element = createElementWithClass('div', 'file-system-list-item');
    const pathPrefix = /** @type {string} */ (editable ? item : Common.UIString('%s (via .devtools)', item));
    const pathPrefixElement = element.createChild('div', 'file-system-value');
    pathPrefixElement.textContent = pathPrefix;
    pathPrefixElement.title = pathPrefix;
    return element;
  }

  /**
   * @override
   * @param {*} item
   * @param {number} index
   */
  removeItemRequested(item, index) {
    Persistence.isolatedFileSystemManager.fileSystem(this._fileSystemPath)
        .removeExcludedFolder(this._excludedFolders[index]);
  }

  /**
   * @override
   * @param {*} item
   * @param {!UI.ListWidget.Editor} editor
   * @param {boolean} isNew
   */
  commitEdit(item, editor, isNew) {
    this._muteUpdate = true;
    if (!isNew) {
      Persistence.isolatedFileSystemManager.fileSystem(this._fileSystemPath)
          .removeExcludedFolder(/** @type {string} */ (item));
    }
    Persistence.isolatedFileSystemManager.fileSystem(this._fileSystemPath)
        .addExcludedFolder(this._normalizePrefix(editor.control('pathPrefix').value));
    this._muteUpdate = false;
    this._update();
  }

  /**
   * @override
   * @param {*} item
   * @return {!UI.ListWidget.Editor}
   */
  beginEdit(item) {
    const editor = this._createExcludedFolderEditor();
    editor.control('pathPrefix').value = item;
    return editor;
  }

  /**
   * @return {!UI.ListWidget.Editor}
   */
  _createExcludedFolderEditor() {
    if (this._excludedFolderEditor)
      return this._excludedFolderEditor;

    const editor = new UI.ListWidget.Editor();
    this._excludedFolderEditor = editor;
    const content = editor.contentElement();

    const titles = content.createChild('div', 'file-system-edit-row');
    titles.createChild('div', 'file-system-value').textContent = Common.UIString('Folder path');

    const fields = content.createChild('div', 'file-system-edit-row');
    fields.createChild('div', 'file-system-value')
        .appendChild(editor.createInput('pathPrefix', 'text', '/path/to/folder/', pathPrefixValidator.bind(this)));

    return editor;

    /**
     * @param {*} item
     * @param {number} index
     * @param {!HTMLInputElement|!HTMLSelectElement} input
     * @return {boolean}
     * @this {Persistence.EditFileSystemView}
     */
    function pathPrefixValidator(item, index, input) {
      const prefix = this._normalizePrefix(input.value);
      const configurableCount =
          Persistence.isolatedFileSystemManager.fileSystem(this._fileSystemPath).excludedFolders().size;
      for (let i = 0; i < configurableCount; ++i) {
        if (i !== index && this._excludedFolders[i] === prefix)
          return false;
      }
      return !!prefix;
    }
  }

  /**
   * @param {string} prefix
   * @return {string}
   */
  _normalizePrefix(prefix) {
    if (!prefix)
      return '';
    return prefix + (prefix[prefix.length - 1] === '/' ? '' : '/');
  }
};


text:
import argparse
import logging

import numpy as np
import pandas as pd

from eval.scripts.compress_labelled_data import get_all_document_features
from discoutils.thesaurus_loader import DenseVectors

"""
Generates a random vector for each NP in all labelled corpora
"""

def generate(output, dim):
    np.random.seed(0)
    feats = ['rand%d' % i for i in range(dim)]
    phrases = list(get_all_document_features(include_unigrams=True))
    vectors = np.random.random((len(phrases), dim))

    v = DenseVectors(pd.DataFrame(vectors, index=phrases, columns=feats))
    v.to_tsv(output, dense_hd5=True)

if __name__ == '__main__':
    logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
    parser = argparse.ArgumentParser(description='Generate a random vectors for a set of words')
    parser.add_argument('--output', required=True, help='Path to output file')
    parser.add_argument('--dim', type=int, default=100, help='Dimensionality of vectors')

    args = parser.parse_args()
    generate(args.output, args.dim)


text:
class Marko::Client::LeadChanges < Cistern::Collection
  model Marko::Client::LeadChange

  attribute :next_page_token, type: :string, aliases: 'nextPageToken'
  attribute :fields, type: :array

  def all(params={})
    data = connection.get_lead_changes(params).body
    self.load(data["result"])
    self.merge_attributes(data)
    self
  end
end


text:
var _ = require('underscore'),
    $ = require('../cheerio'),
    updateDOM = $.parse.update,
    slice = Array.prototype.slice;

var removeChild = function(parent, elem) {
  $.each(parent.children, function(i, child) {
    if (elem === child)
      parent.children.splice(i, 1);
  });
};

/*
  Creates an array of cheerio objects,
  parsing strings if necessary
*/
var makeCheerioArray = function(elems) {
  var dom = [],
      len = elems.length,
      elem;

  for (var i = 0; i < len; i++) {
    elem = elems[i];
    // If a cheerio object
    if (elem.cheerio) {
      dom = dom.concat(elem.toArray());
    } else {
      dom = dom.concat($.parse.eval(elem));
    }
  }

  return dom;
};

var append = exports.append = function() {
  var elems = slice.call(arguments),
      dom = makeCheerioArray(elems);

  this.each(function() {
    if (_.isFunction(elems[0])) {
      // No yet supported
      return this;
    } else {
      if (!this.children) this.children = [];
      this.children = this.children.concat(dom);
      updateDOM(this.children, this);
    }
  });

  return this;
};

/*
  TODO: Refactor, only one line difference between,
  this function and append
*/
var prepend = exports.prepend = function() {
  var elems = slice.call(arguments),
      dom = makeCheerioArray(elems);

  this.each(function() {
    if (_.isFunction(elems[0])) {
      // No yet supported
      return this;
    } else {
      if (!this.children) this.children = [];
      this.children = dom.concat(this.children);
      updateDOM(this.children, this);
    }
  });

  return this;
};

var after = exports.after = function() {
  var elems = slice.call(arguments),
      dom = makeCheerioArray(elems);

  this.each(function() {
    var siblings = this.parent.children,
        index = siblings.indexOf(this);

    // If not found, move on
    if (!~index) return;

    // Add element after `this` element
    siblings.splice.apply(siblings, [++index, 0].concat(dom));

    // Update next, prev, and parent pointers
    updateDOM(siblings, this.parent);
    this.parent.children = siblings;

  });

  return this;
};

var before = exports.before = function() {
  var elems = slice.call(arguments),
      dom = makeCheerioArray(elems);

  this.each(function() {
    var siblings = this.parent.children,
        index = siblings.indexOf(this);

    // If not found, move on
    if (!~index) return;

    // Add element before `this` element
    siblings.splice.apply(siblings, [index, 0].concat(dom));

    // Update next, prev, and parent pointers
    updateDOM(siblings, this.parent);
    this.parent.children = siblings;

  });

  return this;
};

/*
  remove([selector])
*/
var remove = exports.remove = function(selector) {
  var elems = this;

  // Filter if we have selector
  if (selector)
    elems = elems.find(selector);

  elems.each(function() {
    var siblings = this.parent.children,
        index = siblings.indexOf(this);

    if (!~index) return;

    siblings.splice(index, 1);

    // Update next, prev, and parent pointers
    updateDOM(siblings, this.parent);
    this.parent.children = siblings;
  });

  return this;
};

var replaceWith = exports.replaceWith = function(content) {
  content = content.cheerio ? content.toArray() : $.parse.eval(content);

  this.each(function() {
    var siblings = this.parent.children,
        index = siblings.indexOf(this);

    if (!~index) return;

    siblings.splice.apply(siblings, [index, 1].concat(content));

    updateDOM(siblings, this.parent);
    this.parent.children = siblings;
  });

  return this;
};

var empty = exports.empty = function() {
  this.each(function() {
    this.children = [];
  });
  return this;
};

var html = exports.html = function(content) {
  if (content === undefined) {
    if (!this[0] || !this[0].children) return null;
    return $.html(this[0].children);
  }

  content = content.cheerio ? content.toArray() : $.parse.eval(content);

  this.each(function() {
    this.children = content;
    updateDOM(this.children, this);
  });

  return this;
};

var tidy = exports.tidy = function() {
  return $.tidy(this[0].children);
};

var text = exports.text = function(str) {
  // If `str` blank or an object
  if (!str || typeof str === 'object') {
    return $.text(this);
  } else if (_.isFunction(str)) {
    // Function support
    return this.each(function(i) {
      var self = $(this);
      return self.text(str.call(this, i, self.text()));
    });
  }

  var elem = {
    data : $.encode(str),
    type : 'text',
    parent : null,
    prev : null,
    next : null,
    children : []
  };

  // Append text node to each selected elements
  this.each(function() {
    this.children = elem;
    updateDOM(this.children, this);
  });

  return this;
};

var clone = exports.clone = function() {
  return $($.html(this));
};

module.exports = $.fn.extend(exports);


text:
package com.digero.maestro.view;

import info.clearthought.layout.TableLayout;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import com.digero.common.view.ColorTable;

public class Colorizer extends JPanel
{
	private JComboBox<ColorTable> picker;
	private SpinnerNumberModel hue;
	private SpinnerNumberModel sat;
	private SpinnerNumberModel brt;
	private boolean updating = false;
	private JPanel refresher;

	public Colorizer(JPanel coloredPanel)
	{
		super(new BorderLayout());
		this.refresher = coloredPanel;
		picker = new JComboBox<ColorTable>(ColorTable.values());

		picker.addActionListener(new ActionListener()
		{
			@Override public void actionPerformed(ActionEvent e)
			{
				updateSpinners();
			}
		});

		hue = new SpinnerNumberModel(0.0, 0.0, 1.0, 0.01);
		sat = new SpinnerNumberModel(0.0, 0.0, 1.0, 0.05);
		brt = new SpinnerNumberModel(0.0, 0.0, 1.0, 0.05);

		ChangeListener cl = new ChangeListener()
		{
			@Override public void stateChanged(ChangeEvent e)
			{
				if (!updating)
				{
					float h = hue.getNumber().floatValue();
					float s = sat.getNumber().floatValue();
					float b = brt.getNumber().floatValue();

					((ColorTable) picker.getSelectedItem()).set(new Color(Color.HSBtoRGB(h, s, b)));
					refresher.repaint();
				}
			}
		};

		hue.addChangeListener(cl);
		sat.addChangeListener(cl);
		brt.addChangeListener(cl);

		JPanel spinners = new JPanel(new TableLayout(//
				new double[] { TableLayout.PREFERRED, 0.33, TableLayout.PREFERRED, 0.33, TableLayout.PREFERRED, 0.34 },//
				new double[] { TableLayout.PREFERRED }));
		spinners.add(new JLabel("H:"), "0, 0");
		spinners.add(new JSpinner(hue), "1, 0");
		spinners.add(new JLabel(" S:"), "2, 0");
		spinners.add(new JSpinner(sat), "3, 0");
		spinners.add(new JLabel(" B:"), "4, 0");
		spinners.add(new JSpinner(brt), "5, 0");

		add(picker, BorderLayout.NORTH);
		add(spinners, BorderLayout.CENTER);

		updateSpinners();
	}

	private void updateSpinners()
	{
		boolean updatingSav = updating;
		updating = true;

		Color c = ((ColorTable) picker.getSelectedItem()).get();
		float[] hsb = Color.RGBtoHSB(c.getRed(), c.getGreen(), c.getBlue(), null);

		hue.setValue(Math.round(hsb[0] * 100.0f) / 100.0f);
		sat.setValue(Math.round(hsb[1] * 100.0f) / 100.0f);
		brt.setValue(Math.round(hsb[2] * 100.0f) / 100.0f);

		updating = updatingSav;
	}
}


text:
package tests

import (
	"testing"
)

// TestListCompanies tests the list rates command
func TestListRates(t *testing.T) {
	c := &dockerID{}
	c.start925r(t, "basic_projects")
	defer c.stop925r(t)
	userEnv := append(RunAsUser, c.EndpointEnv())
	(&CmdTestCase{
		Name:     "List rates",
		Env:      userEnv,
		Args:     []string{"list", "rates"},
		OutLines: 2,
		OutText: `1.00 [Normal Hours]
2.00 [Double]
`,
	}).Run(t)
}


text:
<!DOCTYPE html>
<!-- Page created by Trivial Tiny CMS -->
<head>
	<!-- Meta Data -->
	<meta http-equiv="Content-Type" content="text/html; charset=<?php echo $config['encoding']; ?>" />
	<meta name="description" content="<?php echo $config['description']; ?>" />
	<meta name="keywords" content="<?php echo $config['keywords']; ?>" />

	<!-- Site Title -->
	<title><?php echo $config['title']; ?></title>

	<!-- Style Sheets -->
	<link href="/css/reset.css" type="text/css" rel="stylesheet" />
	<link href="/template/<?php echo $config['template']; ?>.css" type="text/css" rel="stylesheet" />
</head>


text:
package org.openestate.is24.restapi.xml.common;

import javax.annotation.Generated;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for SiteConstructibleType.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="SiteConstructibleType">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="CONSTRUCTIONPLAN"/>
 *     <enumeration value="NEIGHBOURCONSTRUCTION"/>
 *     <enumeration value="EXTERNALAREA"/>
 *     <enumeration value="NO_INFORMATION"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "SiteConstructibleType")
@XmlEnum
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-07T09:44:49+02:00", comments = "JAXB RI v2.3.0")
public enum SiteConstructibleType {

    /**
     * Bebauungsplan
     *
     */
    CONSTRUCTIONPLAN,

    /**
     * wie Nachbarbebauung
     *
     */
    NEIGHBOURCONSTRUCTION,

    /**
     * Aussengebiet
     *
     */
    EXTERNALAREA,

    /**
     * Keine Angabe
     *
     */
    NO_INFORMATION;

    public String value() {
        return name();
    }

    public static SiteConstructibleType fromValue(String v) {
        return valueOf(v);
    }

}