text:
using System;
using System.Threading;
using BLToolkit.Reflection;
using BLToolkit.TypeBuilder;
using GeoToolkit.Logging;

namespace GeoToolkit.Access
{
    public abstract class AsyncUpdater<TA, TRes, TPar> : AsyncUpdater
        where TA : class, IUpdatable<TRes, TPar>
    {
        private readonly ManualResetEvent _resetEvent = new ManualResetEvent(false);
        private readonly object _syncRoot = new object();
        private bool _stopFlag;
        private Thread _workingThread;
        private bool _isAccessorAutoCreated;

        public bool AutoCreateAccessor { get; set; }

        protected AsyncUpdater(TA accessor) : this()
        {
            if (accessor == null)
                throw new ArgumentNullException("accessor");

            Accessor = accessor;
        }

        protected AsyncUpdater()
        {
            ThreadStopTimeout = TimeSpan.FromSeconds(10);

            AutoCreateAccessor = true;
        }

        public TimeSpan ThreadStopTimeout { get; set; }

        public override sealed DateTime LastUpdateTime
        {
            get { return Accessor.LastUpdated; }
        }

        /// <summary>
        /// Public constructor for safe use as a component
        /// </summary>
        public TA Accessor { get; set; }

        public override TimeSpan Interval
        {
            get
            {
                AssertAccessor();

                return Accessor.UpdateInterval;
            }
            set
            {
                AssertAccessor();

                Accessor.UpdateInterval = value;
            }
        }

        public event EventHandler<UpdatingEventArgs<TPar>> Updating
        {
            add
            {
                AssertAccessor();

                Accessor.Updating += value;
            }
            remove
            {
                AssertAccessor();

                Accessor.Updating -= value;
            }
        }

        public event EventHandler<UpdatedEventArgs<TRes>> Updated
        {
            add
            {
                AssertAccessor();

                Accessor.Updated += value;
            }
            remove
            {
                AssertAccessor();

                Accessor.Updated -= value;
            }
        }

        private void AssertAccessor()
        {
            if (Accessor != null)
                return;

            if (AutoCreateAccessor)
            {
                Accessor = TypeFactory.CreateInstance<TA>();
                _isAccessorAutoCreated = true;
                return;
            }

            throw new InvalidOperationException("You must initialize Accessor first");
        }

        private void DoWork()
        {
            while (!_stopFlag)
            {
                _resetEvent.WaitOne(Interval);

                if (_stopFlag)
                    return;

                try
                {
                    TPar updatingParam = GetUpdatingParameter();

                    UpdateSyncronized(updatingParam);
                }
                catch(UpdatingCancelledException e)
                {
                    this.LogWarn(e.Message);
                }
                catch (Exception e)
                {
                    this.LogError("Error during updating", e);
                }

                if (_stopFlag)
                    return;

                _resetEvent.Reset();
            }
        }

        protected abstract TPar GetUpdatingParameter();

        public TRes Update(TPar param = default(TPar))
        {
            AssertAccessor();

            return Accessor.Update(param);
        }

        public TRes UpdateSyncronized(TPar param = default(TPar))
        {
            AssertAccessor();

            try
            {
                Locked = true;

                lock (_syncRoot)
                    return Accessor.UpdateSyncronized(param);
            }
            finally
            {
                Locked = false;
            }
        }

        public override sealed void Start()
        {
            if (IsRunning)
            {
                this.LogWarn("Start method call for running updater. Do nothing...");
                return;
            }

            this.LogInfo("Starting...");

            _stopFlag = false;

            var startingEventArgs = new CancelableEventArgs();

            InvokeStarting(startingEventArgs);

            if (startingEventArgs.Cancel)
            {
                this.LogError("Starting was cancelled by user code: " + startingEventArgs.CancelReason);

                InvokeStartingCanceled(EventArgs.Empty);

                return;
            }

            _workingThread = new Thread(DoWork);
            _workingThread.Start();

            IsRunning = true;

            _resetEvent.Set();

            InvokeStarted(EventArgs.Empty);

            this.LogInfo("Started successfully");
        }

        protected override sealed void Stop(bool disposing)
        {
            this.LogInfo("Stopping...");

            if (!IsRunning)
            {
                this.LogWarn("No need to stop. The updater is already stopped");
                return;
            }

            if (!disposing)
            {
                var stoppingEventArgs = new CancelableEventArgs();
                InvokeStopping(stoppingEventArgs);
                if (stoppingEventArgs.Cancel)
                {
                    this.LogError("Stopping was cancelled by user code");
                    return;
                }
            }

            _stopFlag = true;

            if (_workingThread != null && _workingThread.IsAlive && _workingThread.ManagedThreadId != Thread.CurrentThread.ManagedThreadId)
            {
                _resetEvent.Set();

                this.LogDebug("Joining process...");
                if (!_workingThread.Join(ThreadStopTimeout))
                    _workingThread.Abort();

                this.LogInfo("Process stopped");
            }

            this.LogDebug("Invoke Stopped");
            if (!disposing)
                InvokeStopped(EventArgs.Empty);

            this.LogInfo("Stopped successfully");

            IsRunning = false;
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (_isAccessorAutoCreated && Accessor is IDisposable)
                ((IDisposable) Accessor).Dispose();
        }
    }
}


text:
// EXPRESS SERVER HERE //

// BASE SETUP
var express = require('express'),
    app = express(),
    bodyParser = require('body-parser'),
    cookieParser = require('cookie-parser'),
    session = require('express-session'),
    methodOverride = require('method-override'),
    // routes = require('./routes/routes'),
    morgan = require('morgan'),
    serveStatic = require('serve-static'),
    errorHandler = require('errorhandler');

// =========================CONFIGURATION===========================//
// =================================================================//
app.set('port', process.env.PORT || 9001);

/*
 * Set to 9001 to not interfere with Gulp 9000.
 * If you're using Cloud9, or an IDE that uses a different port, process.env.PORT will
 * take care of your problems. You don't need to set a new port.
 */

app.use(serveStatic('app', {'index': 'true'})); // Set to True or False if you want to start on Index or not
app.use('/bower_components', express.static(__dirname + '/bower_components'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(morgan('dev'));
app.use(cookieParser('secret'));
app.use(session({secret: 'evernote now', resave: true, saveUninitialized: true}));
app.use(function(req, res, next) {
    res.locals.session = req.session;
    next();
});

if (process.env.NODE_ENV === 'development') {
    app.use(errorHandler());
}
// ==========================ROUTER=================================//
// =================================================================//

// ROUTES FOR THE API - RUN IN THE ORDER LISTED

var router = express.Router();

// ------------- ROUTES ---------------- //

// REGISTERING THE ROUTES
app.use('/', router);

// STARTING THE SERVER

console.log('Serving on port ' + app.get('port') + '. Serving more Nodes than Big Macs!');
app.listen(app.get('port')); // Not used if Gulp is activated - it is bypassed
exports = module.exports = app; // This is needed otherwise the index.js for routes will not work

redpajama_set_name: RedPajamaGithub


text:
package com.microsoft.azure.management.managedapplications.v2019_07_01.implementation;

import java.util.List;
import com.microsoft.azure.management.managedapplications.v2019_07_01.JitAuthorizationPolicies;
import com.microsoft.azure.management.managedapplications.v2019_07_01.JitSchedulingPolicy;
import com.microsoft.azure.management.managedapplications.v2019_07_01.ProvisioningState;
import com.microsoft.azure.management.managedapplications.v2019_07_01.JitRequestState;
import com.microsoft.azure.management.managedapplications.v2019_07_01.ApplicationClientDetails;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.rest.serializer.JsonFlatten;
import com.microsoft.rest.SkipParentValidation;
import com.microsoft.azure.Resource;

/**
 * Information about JIT request definition.
 */
@JsonFlatten
@SkipParentValidation
public class JitRequestDefinitionInner extends Resource {
    /**
     * The parent application id.
     */
    @JsonProperty(value = "properties.applicationResourceId", required = true)
    private String applicationResourceId;

    /**
     * The publisher tenant id.
     */
    @JsonProperty(value = "properties.publisherTenantId", access = JsonProperty.Access.WRITE_ONLY)
    private String publisherTenantId;

    /**
     * The JIT authorization policies.
     */
    @JsonProperty(value = "properties.jitAuthorizationPolicies", required = true)
    private List<JitAuthorizationPolicies> jitAuthorizationPolicies;

    /**
     * The JIT request properties.
     */
    @JsonProperty(value = "properties.jitSchedulingPolicy", required = true)
    private JitSchedulingPolicy jitSchedulingPolicy;

    /**
     * The JIT request provisioning state. Possible values include:
     * 'NotSpecified', 'Accepted', 'Running', 'Ready', 'Creating', 'Created',
     * 'Deleting', 'Deleted', 'Canceled', 'Failed', 'Succeeded', 'Updating'.
     */
    @JsonProperty(value = "properties.provisioningState", access = JsonProperty.Access.WRITE_ONLY)
    private ProvisioningState provisioningState;

    /**
     * The JIT request state. Possible values include: 'NotSpecified',
     * 'Pending', 'Approved', 'Denied', 'Failed', 'Canceled', 'Expired',
     * 'Timeout'.
     */
    @JsonProperty(value = "properties.jitRequestState", access = JsonProperty.Access.WRITE_ONLY)
    private JitRequestState jitRequestState;

    /**
     * The client entity that created the JIT request.
     */
    @JsonProperty(value = "properties.createdBy", access = JsonProperty.Access.WRITE_ONLY)
    private ApplicationClientDetails createdBy;

    /**
     * The client entity that last updated the JIT request.
     */
    @JsonProperty(value = "properties.updatedBy", access = JsonProperty.Access.WRITE_ONLY)
    private ApplicationClientDetails updatedBy;

    /**
     * Get the parent application id.
     *
     * @return the applicationResourceId value
     */
    public String applicationResourceId() {
        return this.applicationResourceId;
    }

    /**
     * Set the parent application id.
     *
     * @param applicationResourceId the applicationResourceId value to set
     * @return the JitRequestDefinitionInner object itself.
     */
    public JitRequestDefinitionInner withApplicationResourceId(String applicationResourceId) {
        this.applicationResourceId = applicationResourceId;
        return this;
    }

    /**
     * Get the publisher tenant id.
     *
     * @return the publisherTenantId value
     */
    public String publisherTenantId() {
        return this.publisherTenantId;
    }

    /**
     * Get the JIT authorization policies.
     *
     * @return the jitAuthorizationPolicies value
     */
    public List<JitAuthorizationPolicies> jitAuthorizationPolicies() {
        return this.jitAuthorizationPolicies;
    }

    /**
     * Set the JIT authorization policies.
     *
     * @param jitAuthorizationPolicies the jitAuthorizationPolicies value to set
     * @return the JitRequestDefinitionInner object itself.
     */
    public JitRequestDefinitionInner withJitAuthorizationPolicies(List<JitAuthorizationPolicies> jitAuthorizationPolicies) {
        this.jitAuthorizationPolicies = jitAuthorizationPolicies;
        return this;
    }

    /**
     * Get the JIT request properties.
     *
     * @return the jitSchedulingPolicy value
     */
    public JitSchedulingPolicy jitSchedulingPolicy() {
        return this.jitSchedulingPolicy;
    }

    /**
     * Set the JIT request properties.
     *
     * @param jitSchedulingPolicy the jitSchedulingPolicy value to set
     * @return the JitRequestDefinitionInner object itself.
     */
    public JitRequestDefinitionInner withJitSchedulingPolicy(JitSchedulingPolicy jitSchedulingPolicy) {
        this.jitSchedulingPolicy = jitSchedulingPolicy;
        return this;
    }

    /**
     * Get the JIT request provisioning state. Possible values include: 'NotSpecified', 'Accepted', 'Running', 'Ready', 'Creating', 'Created', 'Deleting', 'Deleted', 'Canceled', 'Failed', 'Succeeded', 'Updating'.
     *
     * @return the provisioningState value
     */
    public ProvisioningState provisioningState() {
        return this.provisioningState;
    }

    /**
     * Get the JIT request state. Possible values include: 'NotSpecified', 'Pending', 'Approved', 'Denied', 'Failed', 'Canceled', 'Expired', 'Timeout'.
     *
     * @return the jitRequestState value
     */
    public JitRequestState jitRequestState() {
        return this.jitRequestState;
    }

    /**
     * Get the client entity that created the JIT request.
     *
     * @return the createdBy value
     */
    public ApplicationClientDetails createdBy() {
        return this.createdBy;
    }

    /**
     * Get the client entity that last updated the JIT request.
     *
     * @return the updatedBy value
     */
    public ApplicationClientDetails updatedBy() {
        return this.updatedBy;
    }

}


text:
from __future__ import annotations

import argparse
from typing import Any
from typing import Generator
from typing import NamedTuple
from typing import Sequence

import ruamel.yaml

yaml = ruamel.yaml.YAML(typ='safe')

def _exhaust(gen: Generator[str, None, None]) -> None:
    for _ in gen:
        pass

def _parse_unsafe(*args: Any, **kwargs: Any) -> None:
    _exhaust(yaml.parse(*args, **kwargs))

def _load_all(*args: Any, **kwargs: Any) -> None:
    _exhaust(yaml.load_all(*args, **kwargs))

class Key(NamedTuple):
    multi: bool
    unsafe: bool

LOAD_FNS = {
    Key(multi=False, unsafe=False): yaml.load,
    Key(multi=False, unsafe=True): _parse_unsafe,
    Key(multi=True, unsafe=False): _load_all,
    Key(multi=True, unsafe=True): _parse_unsafe,
}

def main(argv: Sequence[str] | None = None) -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '-m', '--multi', '--allow-multiple-documents', action='store_true',
    )
    parser.add_argument(
        '--unsafe', action='store_true',
        help=(
            'Instead of loading the files, simply parse them for syntax.  '
            'A syntax-only check enables extensions and unsafe contstructs '
            'which would otherwise be forbidden.  Using this option removes '
            'all guarantees of portability to other yaml implementations.  '
            'Implies --allow-multiple-documents'
        ),
    )
    parser.add_argument('filenames', nargs='*', help='Filenames to check.')
    args = parser.parse_args(argv)

    load_fn = LOAD_FNS[Key(multi=args.multi, unsafe=args.unsafe)]

    retval = 0
    for filename in args.filenames:
        try:
            with open(filename, encoding='UTF-8') as f:
                load_fn(f)
        except ruamel.yaml.YAMLError as exc:
            print(exc)
            retval = 1
    return retval

if __name__ == '__main__':
    raise SystemExit(main())


text:
import * as actions from '/actions/index.js';
import * as cotw from '/core/cotwContent.js';
import * as Item from '/core/item.js';

import {storeSetup, dispatch, getState} from '/tests/core/testStore.js';

describe("Action/Reducer - Items", () => {
  const bracers = Item.generateItem(cotw.Items.Bracers.BracersOfDefenseVS);
  const pack = Item.generateItem(cotw.Items.Pack.EnchantedMediumPackOfHolding);
  const sword = Item.generateItem(cotw.Items.Weapon.BastardSword);

  beforeEach(() => {
    storeSetup();
  });

  describe('Add/remove item interactions', () => {
    it('should add an item', () => {
      dispatch(actions.addItem(bracers));
      expect(actions.getItems(getState()).length).toEqual(1);
    });
    it('should remove an item', () => {
      dispatch(actions.addItem(bracers));
      dispatch(actions.removeItem(bracers.id));

      expect(getState().items).toEqual({});
      expect(actions.getItems(getState()).length).toEqual(0);
    });
  });
  it('should update the weight of an item');

  describe('Purse', () => {
    beforeEach(() => {
      storeSetup();
      let purseItem = Item.generateItem(cotw.Items.Purse.Purse);
      dispatch(actions.addItem(purseItem));
      dispatch(actions.equipItem('purse', purseItem.id));
    });

    it('should be able to equip a purse', () => {
      let purseId = getState().player.equipment.purse;
      expect(purseId).toBeTruthy();

      let purse = getState().items[purseId];
      expect(purse).toBeTruthy();
    });

    it('should be able to add coins to a purse', () => {
      let purseId = getState().player.equipment.purse;
      let purse = getState().items[purseId];

      expect(purse.copper).toEqual(0);

      dispatch(actions.addToPurse({copper: 100, gold: 1}));

      expect(getState().items[purseId].copper).toEqual(100);
      expect(getState().items[purseId].gold).toEqual(1);
      expect(getState().items[purseId].platinum).toEqual(0);
    });

    it('should be able to remove coins from a purse', () => {
      let purseId = getState().player.equipment.purse;
      let purse = getState().items[purseId];

      expect(purse.copper).toEqual(0);

      dispatch(actions.addToPurse({copper: 100, gold: 3}));
      dispatch(actions.removeFromPurse({copper: 50, gold: 1}));

      expect(getState().items[purseId].copper).toEqual(50);
      expect(getState().items[purseId].gold).toEqual(2);
      expect(getState().items[purseId].platinum).toEqual(0);
    });

    it('should not take out more than what the purse has', () => {
      let purseId = getState().player.equipment.purse;
      let purse = getState().items[purseId];

      expect(purse.copper).toEqual(0);

      dispatch(actions.removeFromPurse({copper: 50, gold: 1}));

      expect(getState().items[purseId].copper).toEqual(0);
      expect(getState().items[purseId].gold).toEqual(0);
    });
  })
});


text:
{% extends "base.html" %}

{% block title %}GameDay - The Blue Alliance{% endblock %}

{% block main_style %}
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css" type="text/css" />
    <link rel="stylesheet" href="/css/gameday2.css" type="text/css" />
{% endblock %}

{% block meta_description %}Watch live FIRST Robotics Competition events.{% endblock %}

{% block more_head_tags %}
  <meta property="og:title" content="Gameday - Live FIRST Robotics Video">
  <meta property="og:type" content="website">
  <meta property="og:url" content="http://www.thebluealliance.com/gameday">
  <meta property="og:image" content="http://www.thebluealliance.com/images/first_logo.png">
  <meta property="og:description" content="Watch live FIRST Robotics Competition events!">
  <meta property="og:site_name" content="The Blue Alliance">
{% endblock %}

{% block navbar %}{% endblock %}

{% block content %}

{{ events_with_webcasts|safe }}

{% endblock %}

{% block footer %}{% endblock %}

{% block main_javascript %}

{% endblock %}

{% block ganalytics_timer %}

{% endblock %}


text:
ACCEPTED

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

#### Published in
N. Amer. Polyp. (Oslo), Vol. 2 Megasporoporia - Wrightoporia 530 (1987)

#### Original name
Polyporus semistipitatus Lloyd, 1924

### Remarks
null


text:
angular
.module('app',[])
// Disabling $sce, not handling user created content
.config(['$sceProvider', $sceProvider=>$sceProvider.enabled(false)])
.directive('app',()=>({
  template: `

      <package-manager packages="packages" selected="selected" pids="pids"></package-manager>

    Shutdown
    ✕ Clear Packages
    {{pids|json}}

      <run-btn
        ng-repeat="(label, command) in packages[selected].scripts"
        ng-if="primaryScript(label)"
        title="{{command}}"
        command="command"
        label="label"
        path="packages[selected].path"
        pids="pids"
      ></run-btn>

      <run-btn
        ng-repeat="(label, command) in packages[selected].scripts"
        ng-if="!primaryScript(label)"
        title="{{command}}"
        command="command"
        label="label"
        path="packages[selected].path"
        pids="pids"
      ></run-btn>

      <npm-installer></npm-installer>

  `
  ,controller: [
    '$scope'
    ,'$http'
    ,($scope,$http)=>{
      // Initialize some basic methods and values
      console.info('App initialized');
      $scope.primaryScript = label => !!label.match(/^(start|build|build:watch:raw|build:watch|boot|debug:later|debug)$/);

      // Load the selected package if available
      $scope.selected = (location.hash||'').replace(/^#/,'') || localStorage.getItem('selected');

      // Stop the server method, terminates the server (which will also stop all pids running as children)
      $scope.stopServer = function stopServer(){
        alert('This will terminate the server, and you will not be able to refresh this page. Start npm-assistant again when needed.');
        $http.get('/stop')
          .then(console.info)
          .catch(console.error);
      }

      // Load the pids for the package if one available
      $scope.$watch('selected',(now,was)=>{
        if(!now) return $scope.pids={};

        // Update the localstorage for selected (the last selected item will always be the item stored in localStorage)
        localStorage.setItem('selected',$scope.selected);
        location.hash = `#${$scope.selected}`;

        // Load the pids based on package name
        var storedPids = localStorage.getItem(`pids-${$scope.selected}`);
        $scope.pids = storedPids ? JSON.parse(storedPids) : {};

        // Confirm running pids with the server
        var validatePids = Object.values($scope.pids);
        if(validatePids.length) {
          $http.get(`/validate/${validatePids}`)
          .then(res=>{
            var validPids = res.data;
            Object.keys($scope.pids).forEach(key=>{
              if(!~validPids.indexOf($scope.pids[key])){
                delete $scope.pids[key];
              }
            });
            console.warn(res.data);
          })
          .catch(res=>{
            alert('Error validating pids with the server');
            console.error(res.data.message);
          })
          ;
        }
      });

      // Remove the packages
      $scope.clearPackages = function clearPackages(){
        localStorage.clear();
        location.reload();
      }

      // Watch the pids changing
      $scope.$watch('pids',(now,was)=>{
        if(now && $scope.selected) {
          localStorage.setItem(`pids-${$scope.selected}`,JSON.stringify($scope.pids));
        }
      },true);

      // React to updates comming through the socket (these are being sent by the server periodically)
      window.socket.on('pids',data=>$scope.$apply(_=>syncPids(data)));

      // This message is broadcasted when some other client started a new process
      window.socket.on('newpid',data=>{
        // alert(JSON.stringify(data,null,' '));
        // alert($scope.selected);
        if($scope.selected===data.package) $scope.$apply(_=>$scope.pids[data.label]=data.pid);
      });

      // PID Sync (the server is frequently broadcasting running pids)
      function syncPids(data){
        // There should not be that many pids, so this iteration does the job
        Object.keys($scope.pids).forEach(label=>{
          if(!~data.indexOf(Number($scope.pids[label]))){
            console.warn(`The task "${label}" has ended`);
            delete $scope.pids[label];
          }
        });
      }
  }]
}))
.directive('packageManager',()=>({
  scope: {
    packages:  '='
    ,selected: '='
    ,pids:     '='
  }
  ,template: `
    {{packages[selected].name}}

      | Change ({{count}}):
      <select ng-model="selected" ng-options="name for name in names"></select>
      or

    add a package.json
    <input id="filepicker" type="file" style="display:none;" file-input="files" multiple/>

      | Location:
      <input type="text" ng-model="packages[selected].path" style="width:300px;"/>
      | Stdout & Stderr:
        <run-btn
          ng-if="packages[selected].logsPort"
          ng-click="openLogs()"
          command="''"
          title="start | stop >> {{'http://localhost:'+packages[selected].logsPort}}"
          label="'tail:std:'+packages[selected].logsPort"
          path="packages[selected].path"
          pids="pids"
        ></run-btn> port:
      <input type="text" ng-model="packages[selected].logsPort" style="width:50px;"/>
      | Open Viewer

  `
  ,controller: ['$scope',($scope)=>{

    // Watch the list of files changing. If it changes add the new files to the list of packages
    $scope.$watch('files',(now,was)=>{
      if(!now) return;

      // Every time we have new files, we add these to the already existing packages
      Array.from(now)
      .forEach(file=>{
        // Only package.json allowed
        if(file.name!=='package.json'){
          var msg = `Only "package.json" allowed. You provided "${file.name}"`;
          alert(msg);
          console.error(msg);
        }

        // Create a file reader for this file and add it to the list of packages in the scope
        const fileReader = new FileReader();
        fileReader.onload = e=>{
          // Use apply to sync properly with angular
          $scope.$apply(_=>{

            // Read the package and add it to the list of packages
            var package = JSON.parse(e.target.result);
            var name    = package.name||'missing-name';

            // JavaScript does not have a standard to access the filesystem path, so we need to make this manual and add it to the package for ease of coding
            package.path     = $scope.packages[name] && $scope.packages[name].path ? $scope.packages[name].path:         `C:/Users/USERNAME/workspace/${name}`;
            package.logsPort = $scope.packages[name] && $scope.packages[name].logsPort ? $scope.packages[name].logsPort: (61000 + Math.ceil(Math.random()*100));

            // Update the package object
            $scope.packages[name] = package;
            console.info(`Updated package "${name}"`);

            // Last loaded package is always selected as the current package
            $scope.currentPackage = package;
            $scope.selected       = name;

            // Store all of the available packages
            localStorage.setItem('packages',JSON.stringify($scope.packages));

            // Count packages
            $scope.updateTracking();
          });
        };
        fileReader.readAsText(file);
      });
    });

    // Changing the path will save the packages (this will trigger a save every time the path changes too... not ideal but its fine)
    $scope.$watch('packages[selected].path',(now,was)=>{
      if(now&&was) {
        localStorage.setItem('packages',JSON.stringify($scope.packages));
      }
    });

    // Changing the logsPort will save the packages (this will trigger a save every time the path changes too... not ideal but its fine)
    $scope.$watch('packages[selected].logsPort',(now,was)=>{
      if(now&&was) {
        localStorage.setItem('packages',JSON.stringify($scope.packages));
      }
    });

    // Load packages available in local storage
    var storedPackages = localStorage.getItem('packages');
    $scope.packages    = storedPackages ? JSON.parse(storedPackages) : {};

    // Updating the count and names of available packages
    $scope.updateTracking = _=>$scope.count = ($scope.names=Object.keys($scope.packages)).length;
    $scope.updateTracking();
  }]
}))
.directive('runBtn',()=>({
  scope: {
    label:    '='
    ,command: '='
    ,path:    '='
    ,pids:    '='
  }
  ,template: `<button ng-class="{'in-progress':loading||pid}" ng-disabled="loading" ng-click="run($event)" data-cmd="command">{{pid}}{{label}}</button>`
  ,controller: [
    '$scope'
    ,'$http'
    ,($scope, $http)=>{
      // Keep the pid in sync with the list of pids
      $scope.$watch('pids[label]',(now,was)=>{
        $scope.pid = now;
      });

      // Method to execute/stop a script
      $scope.run = (eve)=>{
        console.warn($scope.label, $scope.command, $scope.path);
        $scope.loading = true;

        // If we do not have a pid yet, then we need to start the process
        if(!$scope.pid){
          $http.get(`/run/${encodeURIComponent($scope.label)}/${encodeURIComponent($scope.path)}?${eve.ctrlKey?'stdwindow':''}`)
          .then(res=>{
            $scope.loading = false;
            var
              results = res.data
              ,pid    = results.pop() // The last result is the initiated pid
            ;
            $scope.pid = pid;
            $scope.pids[$scope.label] = pid; // Add the pid to the map of label:pid
            console.info(`Script "${$scope.label}" started with pid "${pid}"`);

            // This could be improved, but it might become more complex without much benifit (it can use channels for package names)
            window.socket.emit('started',{
              package: location.hash.replace('#','')
              ,label:  $scope.label
              ,pid:    $scope.pid
            });
          })
          .catch(res=>{
            $scope.loading = false;
            if(res.data&&res.data.message) alert(res.data.message);
            console.error(res.data);
          })
        }
        else {
          $http.get(`/kill/${$scope.pid}`)
          .then(res=>{
            $scope.loading = false;
            $scope.pid     = null;
            delete $scope.pids[$scope.label];
            console.info(`Script "${$scope.label}" with pid "${$scope.pid}" has been stopped`);
          })
          .catch(res=>{
            $scope.loading = false;
            if(res.data&&res.data.message) alert(res.data.message);
            console.error(res.data);
          })
        }
      }
    }
  ]
}))
.directive('npmInstaller',()=>({
  template: `
    <form id="npm-installer-form">

npm install

        <input id="package-name" placeholder="package name (optional)">

      <fieldset class="radios">
        Save
        <input type="radio" name="dependency" value="save">

        Save Dev
        <input type="radio" name="dependency" value="save-dev">

      </fieldset>
      <input type="submit" id="npm-installer-submit" value="Run">
  </form>
`
}))

.directive('fileInput', [
  '$parse'
  ,($parse)=>({
    restrict: 'A',
    link: (scope, element, attributes) =>
      element.bind('change',()=>{
        $parse(attributes.fileInput).assign(scope,element[0].files);
        scope.$digest();
      })
  })
])
;

window.socket = io.connect(`//${location.host}`);
window.socket.on('hi', function (data) {
  console.info(data);
});

angular.bootstrap(document.querySelector('app'),['app'],{strictDi:true});


text:
/*****************************************************************************\
 *  Dank Domain: the return of Hack & Slash                                  *
 *  TAVERN authored by: Robert Hurst <theflyingape@gmail.com>                *
\*****************************************************************************/

import $ = require('./runtime')
import db = require('../db')
import { Access, Coin, Weapon } from '../items'
import { bracket, carry, cat, display, news, vt } from '../lib'
import { PC } from '../pc'
import { elemental } from '../npc'
import { checkXP, input } from '../player'
import { cuss, dice, fs, int, pathTo, sprintf, uint, whole } from '../sys'
import Battle = require('./battle')
import Taxman = require('./taxman')

module Tavern {

    let tavern: choices = {
        'B': { description: 'Brawl another user' },
        'E': { description: 'Eavesdrop on the arguments' },
        'J': { description: 'Jump into the arguments' },
        'G': { description: 'Guzzle beer' },
        'L': { description: 'List user bounties' },
        'P': { description: 'Post your own bounty' },
        'S': { description: 'Swear at Tiny' },
        'T': { description: `Today's news` },
        'Y': { description: `Yesterday's news` }
    }

    const file = pathTo('users', 'arguments.json')
    const mantle = pathTo('files/tavern', 'trophy.json')

    export function menu(suppress = true) {
        if (checkXP($.online, menu)) return
        if ($.online.altered) PC.save()
        Taxman.bar()
        if ($.reason) vt.hangup()

        elemental.orders('Tavern')
        vt.form = {
            'menu': { cb: choice, cancel: 'q', enter: '?', eol: false }
        }

        let hints = ''
        if (!suppress) {
            if ($.player.coin.value)
                hints += '> Carrying extra money around here is only good for posting a bounty\n  on someone or buying drinks & tips from the barkeep.\n'
        }
        vt.form['menu'].prompt = display('tavern', vt.Yellow, vt.yellow, suppress, tavern, hints)
        input('menu')
    }

    function choice() {
        let js: argument[] = []
        let suppress = false
        let choice = vt.entry.toUpperCase()
        if (tavern[choice]?.description) {
            vt.outln(' - ', tavern[choice].description)
            suppress = $.player.expert
        }
        vt.outln()

        switch (choice) {

            case 'B':
                if (!$.access.roleplay) break
                if (!$.brawl) {
                    vt.outln('You have run out of brawls.')
                    break
                }
                $.online.bp = $.online.hp > 9 ? int($.online.hp / 10) : 1
                Battle.user('Brawl', (opponent: active) => {
                    if (opponent.user.id == '') {
                        menu(true)
                        return
                    }
                    vt.outln()
                    if (opponent.user.id == $.player.id) {
                        vt.outln('You want to hit yourself?')
                        menu(true)
                        return
                    }
                    if ($.player.level - opponent.user.level > 3) {
                        vt.outln('You can only brawl someone higher or up to three levels below you.')
                        menu(true)
                        return
                    }
                    vt.outln(vt.green, 'Name: ', vt.white, sprintf('%-22s      You:', opponent.user.handle))
                    vt.outln(vt.green, 'Level: ', vt.white, sprintf('%-22d     %-2d', opponent.user.level, $.player.level))
                    vt.outln(vt.green, 'Knock out points: ', vt.white, sprintf('%-15d %-3d', opponent.bp, $.online.bp))
                    if (!Access.name[opponent.user.access].roleplay) {
                        vt.outln('\nYou are allowed only to brawl other players.')
                        if (opponent.user.id[0] == '_') {
                            PC.adjust('cha', -2, -1)
                            $.player.coward = true
                        }
                        menu(true)
                        return
                    }
                    if (!db.lock(opponent.user.id)) {
                        vt.beep()
                        vt.outln(vt.cyan, vt.faint, `\n${PC.who(opponent).He}is currently engaged elsewhere and not available.`)
                        menu(true)
                        return
                    }

                    vt.action('ny')
                    vt.form = {
                        'brawl': {
                            cb: () => {
                                vt.outln('\n')
                                if (/Y/i.test(vt.entry)) {
                                    $.brawl--
                                    if (($.online.dex / 2 + dice($.online.dex / 2)) > (opponent.dex / 2 + dice(opponent.dex / 2))) {
                                        vt.outln('You get the first punch.')
                                        Battle.brawl($.online, opponent)
                                    }
                                    else
                                        vt.outln(`${PC.who(opponent).He}gets the first punch.`)
                                    if ($.online.bp > 0 && opponent.bp > 0)
                                        Battle.brawl(opponent, $.online)
                                    if ($.online.bp > 0 && opponent.bp > 0) {
                                        vt.action('brawl')
                                        input('punch', 2 * $.online.bp < opponent.bp ? 'p' : 'g')
                                    }
                                    else
                                        menu($.player.expert)
                                }
                                else
                                    menu($.player.expert)
                            }, prompt: 'Are you sure (Y/N)? ', cancel: 'N', enter: 'N', eol: false, match: /Y|N/i, max: 1, timeout: 10
                        },
                        'punch': {
                            cb: () => {
                                vt.outln()
                                if (/P/i.test(vt.entry)) {
                                    Battle.brawl($.online, opponent)
                                    if ($.online.bp > 0 && opponent.bp > 0)
                                        Battle.brawl(opponent, $.online)
                                }
                                if (/G/i.test(vt.entry)) {
                                    db.unlock($.player.id, true)
                                    vt.outln(`\nWe can't all be Rocky, eh?`)
                                    menu($.player.expert)
                                    return
                                }
                                if (/Y/i.test(vt.entry))
                                    vt.outln(`\nYour knock out points: ${$.online.bp}`)
                                if ($.online.bp > 0 && opponent.bp > 0)
                                    vt.refocus()
                                else {
                                    db.unlock($.player.id, true)
                                    menu($.player.expert)
                                }
                            }, prompt: vt.attr(bracket('P', false), vt.cyan, `unch ${PC.who(opponent).him}`, bracket('G', false), vt.cyan, 'ive it up, ', bracket('Y', false), vt.cyan, 'our status: ')
                            , cancel: 'G', enter: 'P', eol: false, match: /P|G|Y/i, timeout: 30
                        }
                    }
                    input('brawl', 'y')
                })
                return

            case 'E':
                try {
                    js = JSON.parse(fs.readFileSync(file).toString())
                }
                catch (err) {
                    js = [{ who: 'YOU', text: 'Feel free to jump in to post something!' }]
                }
                for (let argument in js) {
                    vt.outln()
                    vt.outln('    -=', bracket(js[argument].who, false), '=-')
                    vt.outln(+argument % 2 ? vt.lyellow : vt.lcyan, js[argument].text)
                }
                suppress = true
                break

            case 'G':
                vt.outln(`${$.barkeep.user.handle} pours you a beer.`, -500)

                vt.action('payment')
                vt.form = {
                    'tip': {
                        cb: () => {
                            vt.outln('\n')
                            let tip = (/=|max/i.test(vt.entry)) ? $.player.coin.value : new Coin(vt.entry).value
                            if (tip < $.player.coin.COPPER || tip > $.player.coin.value) {
                                vt.sound('oops')
                                vt.outln(`${$.barkeep.who.He}pours the beer on you and kicks you out of ${$.barkeep.who.his}bar.`)
                                $.brawl = 0
                                require('./menu').menu(true)
                                return
                            }

                            vt.beep()
                            vt.out(vt.yellow, PC.who($.barkeep).He, 'grunts and hands you your beer.')
                            if ($.player.emulation == 'XT') vt.out(' \u{1F37A}')
                            vt.outln(-1000)
                            $.online.altered = true
                            $.player.coin.value -= tip

                            vt.out(vt.green, PC.who($.barkeep).He, 'says, ', vt.white, '"', [
                                'More stamina will yield more hit points',
                                'More intellect will yield more spell power',
                                `You don't miss as often with higher agility`,
                                'You can sell items for more money with higher charisma',
                                'You can do more damage in battle with higher stamina',
                                `Spells don't fail as often with higher intellect`,
                                'Higher agility yields higher jousting ability',
                                'Fishing can get better results from higher charisma',
                                'Real Estate and Security help protect your investments',
                                'Dodging an attack is your ability to steal with dexterity',
                                'Higher baud rates yield faster screen displays',
                                'Crying will not change the world',
                                'Backstabs swish more than you wish',
                                'Dungeon maps fall more often into lucky hands',
                                `Higher intellect calculates opponent's hit points more accurately`,
                                `50+ Intellect points are needed to map where you've been walking.  Mostly.`,
                                'Resurrect works on ALL dead folk, not creatures',
                                `Death match if you take on your gang's leader in the Arena`,
                                'Blessed/Cursed does not carry over to the next day',
                                `Killing the town's barkeep will lose you favor with its folks`,
                                'Deeper dungeon portals is the key to victory',
                                `I'll have more hints tomorrow.  Maybe`
                            ][uint(<unknown>(tip % 22n))])
                            vt.outln('."', -1000)
                            menu()
                        }, prompt: 'How much will you tip? ', max: 8
                    },
                }
                input('tip', dice(22).toString())
                return

            case 'J':
                if (!$.argue) {
                    vt.outln(`\nYou've made your argument already -- go have a beer.`)
                    suppress = true
                    break
                }
                vt.action('freetext')
                vt.form = {
                    'argue': {
                        cb: () => {
                            vt.outln()
                            if (vt.entry.length && !cuss(vt.entry)) {
                                try { js = JSON.parse(fs.readFileSync(file).toString()) } catch { }
                                js = js.splice(+(js.length > 9), 9).concat(<argument>{ who: $.player.id, text: vt.entry })
                                fs.writeFileSync(file, JSON.stringify(js))
                                $.argue--
                            }
                            menu()
                        }, prompt: 'Enter your argument', lines: $.player.novice ? 2 : 6, timeout: 600
                    }
                }
                input('argue', '')
                return

            case 'L':
                vt.outln(vt.green, '        --=:)) ', vt.bright, 'Tavern Bounty List', vt.normal, ' ((:=--')
                vt.outln()
                let rs = db.query(`SELECT id,handle,bounty,who FROM Players WHERE bounty > 0 ORDER BY level DESC`)
                for (let i in rs) {
                    let adversary = <active>{ user: { id: rs[i].who } }
                    if (PC.load(adversary)) {
                        let bounty = new Coin(rs[i].bounty)
                        vt.outln(rs[i].handle, ' has a ', carry(bounty), ' bounty posted by ', vt.bright, adversary.user.handle)
                    }
                }
                vt.form = {
                    'pause': { cb: menu, pause: true }
                }
                input('pause', '')
                return

            case 'P':
                if (!$.access.roleplay) break
                if ($.player.coin.value < $.player.coin.COPPER) {
                    vt.outln(`You'll need some cash to post a bounty.`)
                    suppress = true
                    break
                }
                if ($.player.novice || $.player.level < 10) {
                    vt.sound('crowd')
                    vt.outln('The crowd laughs at your gesture.', -1000)
                    vt.outln(`${$.barkeep.user.handle} snorts, "Be for real."`)
                    suppress = true
                    break
                }
                Battle.user('Bounty', (opponent: active) => {
                    if (opponent.user.id == '' || opponent.user.id == $.player.id) {
                        menu()
                        return
                    }
                    vt.outln()
                    if (opponent.user.bounty.value) {
                        vt.outln(`${opponent.user.handle} already has a bounty posted.`)
                        menu()
                        return
                    }
                    let max = new Coin(10n * PC.money(opponent.user.level)).pick(1)
                    if (max.value > $.player.coin.value) max.value = $.player.coin.pick(1).value

                    vt.action('payment')
                    vt.form = {
                        'coin': {
                            cb: () => {
                                vt.outln()
                                if ((+vt.entry).toString() == vt.entry) vt.entry += 'c'
                                let post = /=|max/i.test(vt.entry) ? max.value : new Coin(vt.entry).value
                                if (post > 0 && post <= max.value) {
                                    $.player.coin.value -= post
                                    opponent.user.bounty = new Coin(post)
                                    opponent.user.who = $.player.id
                                    vt.beep()
                                    vt.outln(`\nYour bounty is posted for all to see.`, -500)
                                    news(`\tposted a bounty on ${opponent.user.handle}`)
                                    PC.save(opponent)
                                }
                                menu(true)
                            }, max: 6
                        }
                    }
                    vt.form['coin'].prompt = `Bounty [MAX=${carry(max)}]? `
                    input('coin', '=')
                    return
                })
                return

            case 'Q':
                require('./menu').menu($.player.expert)
                return

            case 'S':
                if (!$.access.roleplay) break
                vt.out('You cuss out loud, then ')
                $.tiny--
                switch ($.tiny) {
                    case 2:
                        vt.profile({
                            jpg: 'npc/barkeep', effect: 'fadeInRight'
                            , handle: $.barkeep.user.handle, level: $.barkeep.user.level, pc: $.barkeep.user.pc
                        })
                        vt.outln('mutter, "Freak."', -1000)
                        if ($.player.level < 60)
                            vt.outln('The barkeep stares off into empty space, ignoring your wimpy comment.')
                        else
                            vt.outln(`The barkeep points at ${$.barkeep.who.his}massive, flexed bicep and laughs at your jest.`)
                        suppress = true
                        break

                    case 1:
                        vt.profile({
                            jpg: 'npc/barkeep', effect: 'shakeX'
                            , handle: $.barkeep.user.handle, level: $.barkeep.user.level, pc: $.barkeep.user.pc
                        })
                        vt.outln('thumb your nose.', -1000)
                        if ($.player.level < 60)
                            vt.outln(`Annoyed, the barkeep looks down at ${$.barkeep.who.his}furry feet and counts, \"100, 99, 98,...\"`)
                        else
                            vt.outln(`The former Champion Ogre grunts to ${$.barkeep.who.self} "Not good for business."`)
                        suppress = true
                        break

                    default:
                        $.brawl = 0
                        vt.music()
                        vt.outln(`jest, "What you looking at, wart-face!"`, -1200)
                        vt.profile({
                            jpg: 'npc/barkeep', effect: 'shakeY'
                            , handle: $.barkeep.user.handle, level: $.barkeep.user.level, pc: $.barkeep.user.pc
                        })
                        vt.out('Uh, oh!')
                        vt.sound('ddd', 22)
                        vt.title(`${$.player.handle}: level ${$.player.level} ${$.player.pc} death match with ${$.barkeep.user.handle}`)
                        vt.out(`  Here comes the tavern's barkeep!`)
                        vt.sound('challenge', 12)
                        vt.outln(`  And ${PC.who($.barkeep).he}doesn't look friendly...\n`, -600)
                        vt.outln(vt.green, vt.bright, [
                            `"When I'm through with you, your mama won't be able to identify the remains."`,
                            `"I am getting too old for this."`,
                            `"Never rub another man\'s rhubarb!"`][dice(3, 0)], -3000)

                        PC.load($.barkeep)
                        let trophy = JSON.parse(fs.readFileSync(mantle).toString())
                        $.barkeep.user.toWC = uint($.barkeep.weapon.wc / 5)
                        if ($.barkeep.weapon.wc < Weapon.merchant.length)
                            $.barkeep.toWC += int((Weapon.merchant.length - $.barkeep.weapon.wc) / 10) + 1

                        vt.outln(`\n${$.barkeep.user.handle} towels ${PC.who($.barkeep).his}hands dry from washing the day\'s\nglasses, ${PC.who($.barkeep).he}warns,\n`)
                        vt.outln(vt.green, vt.bright, '"Another fool said something like that to me, once, and got all busted up."\n', -5000)
                        let fool = <active>{ user: { id: trophy.who, handle: 'a pirate', gender: 'M' } }
                        PC.load(fool)
                        vt.outln(vt.green, vt.bright, `"I think it was ${fool.user.handle}, and it took me a week to clean up the blood!"\n`, -4000)

                        vt.music('tiny')
                        vt.out(`${PC.who($.barkeep).He}points to a buffed weapon hanging over the mantlepiece and says, `
                            , vt.green, vt.bright, '"Lookee\n')
                        vt.outln(`there, ${PC.who(fool).he}tried to use that ${trophy.weapon}`, vt.green, vt.bright, `, but it wasn't enough\nto take me.\"\n`, -6000)
                        vt.out('The patrons move in closer to witness the forthcoming slaughter, except for\n')
                        vt.outln(`${$.taxman.user.handle} who is busy raiding the bar of its beer and nuts.`, -5000)
                        vt.outln(`\nYou hear a cry, "I'll pay fifteen-to-one on the challenger!"`, -4000)
                        vt.sound('crowd')
                        vt.out('The crowd roars with laughter... ', -3000)
                        vt.outln('you are not amused.', -2000)
                        vt.outln(`\n${$.barkeep.user.handle} removes ${PC.who($.barkeep).his}tunic to reveal a massive, but\nheavily scarred chest.`, -2500)
                        vt.out('\nYou look for an exit, but there is none to be found... ', -2500)
                        vt.outln()

                        $.player.coward = true
                        PC.save()
                        $.online.altered = true
                        Battle.engage('Tavern', $.online, $.barkeep, require('./menu').menu)
                        return
                }
                break

            case 'T':
                cat('tavern/today')
                suppress = true
                break

            case 'Y':
                cat('tavern/yesterday')
                suppress = true
                break

            default:
                vt.beep(true)
                suppress = false
        }
        menu(suppress)
    }

}

export = Tavern


text:
package main

import (
	"runtime"
)

// IServiceManager interface
type IServiceManager interface {
	Save(Project) error
	Start(Project) error
	Stop(Project) error
	Restart(Project) error
}

// InitServiceManager .
func InitServiceManager() IServiceManager {
	if runtime.GOOS == "windows" {
		return WindowsServiceManager{}
	}
	return SystemdServiceManager{}
}


text:
package com.netflix.spinnaker.orca.webhook.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Order
@Component
public class DefaultRestTemplateProvider implements RestTemplateProvider {
  private final RestTemplate restTemplate;

  @Autowired
  public DefaultRestTemplateProvider(RestTemplate restTemplate) {
    this.restTemplate = restTemplate;
  }

  @Override
  public boolean supports(String targetUrl) {
    return true;
  }

  @Override
  public RestTemplate getRestTemplate(String targetUrl) {
    return restTemplate;
  }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Sarfraz
 * Date: 8/15/2017
 * Time: 6:05 PM
 */

namespace Sarfraznawaz2005\Floyer\Commands;

use Sarfraznawaz2005\Floyer\Traits\Options;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

class Deploy extends Command
{
    use Options;

    protected $commandName = 'deploy';
    protected $commandDescription = "Starts deployment process.";

    // constants
    const CONFIG_FILE = 'config';
    const SYNC = 'sync';
    const ROLLBACK = 'rollback';
    const HISTORY = 'history';

    // required arguments
    protected $arguments = [
        self::CONFIG_FILE => 'Config file to use.',
    ];

    // our options
    protected $options = [
        self::SYNC => 'Synchronize last local revision id with remote revision file.',
        self::ROLLBACK => 'Rollback previous deployment.',
        self::HISTORY => 'List files deployed in previous deployment.',
    ];

    // vars
    protected $currentDirectory = '';

    /**
     * Configure Command
     */
    protected function configure()
    {
        $this->setName($this->commandName);
        $this->setDescription($this->commandDescription);

        // attach arguments
        foreach ($this->arguments as $name => $description) {
            $this->addArgument($name, InputArgument::OPTIONAL, $description);
        }

        // attach options
        foreach ($this->options as $name => $description) {
            $this->addOption($name, null, InputOption::VALUE_NONE, $description);
        }

        $this->init();
    }

    /**
     * Initialization stuff.
     */
    protected function init()
    {
        set_time_limit(0);

        $this->currentDirectory = getcwd();
    }

    /**
     * Execute console command.
     *
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int|null|void
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $configFile = '';

        $io = new SymfonyStyle($input, $output);

        if (!trim($input->getArgument(static::CONFIG_FILE))) {
            $defaultServer = $this->currentDirectory . DIRECTORY_SEPARATOR . 'floyer_default_server.txt';

            if (file_exists($defaultServer)) {
                $defaultConfigFile = file_get_contents($defaultServer);

                if (trim($defaultConfigFile)) {
                    $configFile = $this->currentDirectory . DIRECTORY_SEPARATOR . trim($defaultConfigFile);
                }
            }

        } else {
            $configFile = $this->currentDirectory . DIRECTORY_SEPARATOR . $input->getArgument(static::CONFIG_FILE);
        }

        if (!file_exists($configFile)) {
            $io->writeln("<fg=red>'$configFile' does not exist!</>");
            exit;
        }

        $this->floyer($output);

        $this->iniFile = $configFile;

        $options = $this->getOptions();

        $server = basename($configFile);
        $io->note("Server Used: $server");

        // check to make sure we are good to go
        $this->checkUp($options, $io);

        try {

            $driver = 'Sarfraznawaz2005\Floyer\Drivers\\' . $options['driver'];
            $connector = 'Sarfraznawaz2005\Floyer\Connectors\\' . $options['connector'];

            $driver = new $driver;
            $connector = new $connector;

            $connector->connect($options);
            $driver->setIO($io);
            $driver->init($connector, $options);

            $isSync = $input->getOption(static::SYNC);
            $isRollback = $input->getOption(static::ROLLBACK);
            $isHistory = $input->getOption(static::HISTORY);

            if ($isSync) {
                $driver->sync();
            } elseif ($isRollback) {
                $driver->rollback();
            } elseif ($isHistory) {
                $driver->history();
            } else {
                $driver->processDeployment();
            }

        } catch (\Exception $e) {
            $io->error($e->getMessage());
        }
    }

    /**
     * @param OutputInterface $output
     */
    protected function floyer(OutputInterface $output)
    {
        $output->writeln('<fg=black;bg=green>-------------------------------------------------</>');
        $output->writeln('<fg=black;bg=green>|                     Floyer                    |</>');
        $output->writeln('<fg=black;bg=green>-------------------------------------------------</>');
    }

    /**
     * Checks if everything is okay before we proceed
     *
     * @param $options
     * @param $io
     */
    protected function checkUp($options, $io)
    {
        if (!isset($options['driver'])) {
            $io->writeln("<fg=red>Driver is not specified in config file!</>");
            exit;
        }

        if (!isset($options['connector'])) {
            $io->writeln("<fg=red>Connector is not specified in config file!</>");
            exit;
        }

        if ($options['driver'] === 'Git') {
            if (!file_exists("{$this->currentDirectory}/.git")) {
                $io->writeln("<fg=red>'{$this->currentDirectory}' is not a Git repository.</>");
                exit;
            }
        } elseif ($options['driver'] === 'Svn') {
            if (!file_exists("{$this->currentDirectory}/.svn")) {
                $io->writeln("<fg=red>'{$this->currentDirectory}' is not a SVN repository.</>");
                exit;
            }
        }
    }
}


text:
from UIView import UIView
from FrontEnd import FrontEnd
from User import User
from Controller import Controller
from TimeContainer import TimeContainer
import argparse
"""
This class handles the Model-View-Controller.

"""

class SchwarzRadDemo():

    def __init__(self):
        print("Initialising game")
        self.View = UIView()
        self.FrontEnd = FrontEnd()
        self.FrontEnd.main()
        self.User = User()
        self.Time = TimeContainer()

        parser = argparse.ArgumentParser(description='Schwarzchild Radius')
        parser.add_argument('-g', action='store_false',
                                               help='Disables graphical user interface')
        args = parser.parse_args()

        print(args.g)

        if args.g:
            self.Controller = Controller(self.FrontEnd, self.User, self.Time)
        else:
            self.Controller = Controller(self.View, self.User, self.Time)

if __name__ == '__main__':
    demo = SchwarzRadDemo()


text:
    Level 1: .col-sm-9

        Level 2: .col-xs-8 .col-sm-6

        Level 2: .col-xs-4 .col-sm-6

To nest content add a new .row and set of .col-sm-* columns within an existing .col-sm-* column.
  Nested rows should include a set of columns that add up to 12 or less.

<uxd-snippet [content]="snippets.compiled.sampleHtml"></uxd-snippet>

Note: .show-grid is enabled below to only demonstrate this layout.
    .show-grid would not be enabled in production code.


text:
package mount

func MakePrivate(mountPoint string) error {
	mounted, err := Mounted(mountPoint)
	if err != nil {
		return err
	}

	if !mounted {
		if err := Mount(mountPoint, mountPoint, "none", "bind,rw"); err != nil {
			return err
		}
	}

	return ForceMount("", mountPoint, "none", "private")
}


text:
using Autofac;
using Autofac.Integration.Mvc;
using DapperCommon;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Compilation;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Autofac.Util;
using Model;
using BLL;
using DAL;
using DistanceTeaching.App.Controllers;

namespace DistanceTeaching.App
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            ContainerBuilder cb = new ContainerBuilder();
            cb.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();

            // 注册BLL与DAL
            var assemblys = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToList();
            cb.RegisterAssemblyTypes(assemblys.ToArray()).Where(t => t.Name.ToLower().EndsWith("bll")).AsSelf().SingleInstance();
            cb.RegisterAssemblyTypes(assemblys.ToArray()).Where(t => t.Name.ToLower().EndsWith("dal")).AsSelf().SingleInstance();

            var container = cb.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
    }
}


text:
package esiv2

/*
Top 100 rankings of pilots by number of kills from yesterday, last week and in total */
type GetFwLeaderboardsCharactersKills struct {
	/*
	 Top 100 ranking of pilots active in faction warfare by total kills. A pilot is considered \"active\" if they have participated in faction warfare in the past 14 days */
	ActiveTotal []GetFwLeaderboardsCharactersActiveTotalActiveTotal `json:"active_total,omitempty"`
	/*
	 Top 100 ranking of pilots by kills in the past week */
	LastWeek []GetFwLeaderboardsCharactersLastWeekLastWeek `json:"last_week,omitempty"`
	/*
	 Top 100 ranking of pilots by kills in the past day */
	Yesterday []GetFwLeaderboardsCharactersYesterdayYesterday `json:"yesterday,omitempty"`
}


text:
package de.tor.tribes.util;

import de.tor.tribes.php.json.JSONArray;
import de.tor.tribes.php.json.JSONException;
import de.tor.tribes.php.json.JSONObject;
import de.tor.tribes.ui.views.DSWorkbenchSettingsDialog;
import org.apache.log4j.Logger;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 *
 * @author Torridity
 */
public final class GithubVersionCheck {

    private static Logger LOGGER = Logger.getLogger("GithubVersionCheck");

    private static final String API_URL = "https://api.github.com/repos/torridity/dsworkbench/releases/latest";

    public static class UpdateInfo {

        private static UPDATE_STATUS status;
        private static String downloadUrl;

        public static UpdateInfo factoryUpdateAvailableInfo(String pDownloadUrl) {
            return new UpdateInfo(UPDATE_STATUS.UPDATE_AVAILABLE, pDownloadUrl);
        }

        public static UpdateInfo factoryNoUpdateAvailableInfo() {
            return new UpdateInfo(UPDATE_STATUS.NO_UPDATE_AVAILABLE, null);
        }

        public static UpdateInfo factoryUpdateCheckFailedInfo() {
            return new UpdateInfo(UPDATE_STATUS.CHECK_FAILED, null);
        }

        UpdateInfo(UPDATE_STATUS pStatus, String pDownloadUrl) {
            status = pStatus;
            downloadUrl = pDownloadUrl;
        }

        public UPDATE_STATUS getStatus() {
            return status;
        }

        public String getDownloadUrl() {
            return downloadUrl;
        }

    }

    public enum UPDATE_STATUS {

        UPDATE_AVAILABLE,
        NO_UPDATE_AVAILABLE,
        CHECK_FAILED

    }

    /**
     * Check on github whether there is an update for DS Workbench available.
     * Therefor, the last release tag is obtained and compared to the DS
     * Workbench version stored in {@link Constants}. The actual version
     * consists of {@link Constants#VERSION} and
     * {@link Constants#VERSION_ADDITION} where VERSION is a double value and
     * VERSION_ADDITION a string, e.g. 1.0beta. The returned UpdateInfo reflects
     * the result of the request. If the update check succeeds and an update is
     * available, the result also contains the download URL. If the update check
     * fails, e.g. due to missing internet connectivity or due to a GitHub API
     * change, the according enum will be used.
     *
     * @return The update information object including the status and download
     * URL, if available.
     */
    public static UpdateInfo getUpdateInformation() {
        try {
            URLConnection u = new URL(API_URL).openConnection(DSWorkbenchSettingsDialog.getSingleton().getWebProxy());
            InputStream in = u.getInputStream();
            int bytes = 0;
            byte[] data = new byte[1024];
            ByteArrayOutputStream result = new ByteArrayOutputStream();
            while ((bytes = in.read(data)) != -1) {
                result.write(data, 0, bytes);
            }

            JSONObject latestRelease = new JSONObject(new String(result.toByteArray()));
            String latestTagName = (String) latestRelease.get("tag_name");

            String ownVersion = Double.toString(Constants.VERSION) + Constants.VERSION_ADDITION;
            if (ownVersion.equals(latestTagName)) {
                //no update available
                return UpdateInfo.factoryNoUpdateAvailableInfo();
            }
            //update available...obtain download URL and return
            String downloadUrl = (String) ((JSONObject) ((JSONArray) latestRelease.get("assets")).get(0)).get("browser_download_url");
            return UpdateInfo.factoryUpdateAvailableInfo(downloadUrl);
        } catch (IOException | JSONException ex) {
            //failed to check update
            LOGGER.warn("Failed to check for update.", ex);
            return UpdateInfo.factoryUpdateCheckFailedInfo();
        }
    }

    public static void main(String[] args) {
        GithubVersionCheck.getUpdateInformation();
    }

}


text:
<?php

/**
 * Created by PhpStorm.
 * User: Hesk
 * Date: 14年8月6日
 * Time: 上午11:59
 */

defined('ABSPATH') || exit;

if (!class_exists('userRegister')) {
    class userRegister
    {
        private $reg_user, $vcoin_transaction, $titan;

        public function __construct()
        {

        }

        function __destruct()
        {
            $this->reg_user = NULL;
            $this->vcoin_transaction = NULL;
            gc_collect_cycles();
        }

        public static function user_reg()
        {
            add_action("user_register", array(__CLASS__, "new_user_reg"), 11, 1);
            add_action("delete_user", array(__CLASS__, "my_delete_user"), 11, 1);
        }

        public static function my_delete_user($user_id)
        {
            global $wpdb;
            $user_obj = get_userdata($user_id);
            $email = $user_obj->user_email;
            $headers = 'From: ' . get_bloginfo("name") . ' <' . get_bloginfo("admin_email") . '>' . "\r\n";
            wp_mail($email, 'You are being deleted, brah', 'Your account at ' . get_bloginfo("name") . ' is being deleted right now.', $headers);
            api_cms_server::enable_account($user_id, false);
        }

        /**
         * register action callback in here
         * @param $user_id
         * @internal param $ID
         */
        public static function new_user_reg($user_id)
        {
            $user = new WP_User($user_id);
            if (is_array($user->roles)) {
                if ($user->roles[0] == "appuser" || $user->roles == "appuser") {
                    if (get_user_meta($user_id, "uuid_key", true) == "") {
                        $re = new userRegister();
                        $re->admin_create_vcoin_key_user($user);
                    }
                }
            }
            $user = NULL;
        }

        /**
         * totally independent function to create new user from the admin panel
         * @param WP_User $user
         */
        public function admin_create_vcoin_key_user(WP_User $user)
        {
            $this->reg_user = $user;
            $this->create_vcoin_key_for_user();
        }

        /**
         * create a vcoin key for the user
         * and create an user for the application
         */
        private function create_vcoin_key_for_user()
        {
            $this->titan = TitanFramework::getInstance('vcoinset');
            $this->vcoin_transaction = new vcoinBase();
            $data = get_userdata($this->reg_user->ID);
            $bind_id = $this->vcoin_transaction->create_new_user($data->user_email);
            update_user_meta($this->reg_user->ID, "uuid_key", $bind_id);
            $free_v_coin = $this->titan->getOption("vcoin_registration");
            if (intval($free_v_coin) > 0) {
                $this->vcoin_transaction = new vcoinBase();
                $this->vcoin_transaction->setReceive($bind_id);
                $this->vcoin_transaction->setSender(IMUSIC_UUID);
                $this->vcoin_transaction->setAmount($free_v_coin);
                $this->vcoin_transaction->setTransactionReference("new account coins");
                $this->vcoin_transaction->CommitTransaction();
            }
            inno_log_db::log_vcoin_email(-1, 901201,
                "new free coin from opening account. added (v)" . $free_v_coin . " to the account user " . $this->reg_user->ID .
                " with trace_id" . $this->vcoin_transaction->get_tranaction_reference() . " and the uuid key is " . $bind_id
            );

        }

        /**
         * @param $login_name
         * @param $user_email
         * @param $role
         * @param array $extra_fields
         * @param $pwd
         * @throws Exception
         * @internal param array $extrafields
         */
        public function newUser($login_name, $user_email, $role, $extra_fields = array(), $pwd)
        {
            try {
                if ($role == "appuser") {
                    $extra_fields["birthday"] = "1/1/2000";
                    $extra_fields["country"] = "Hong Kong";
                    $extra_fields["countrycode"] = "HKG";
                    $extra_fields["setting_push_sms"] = "0";
                    $extra_fields["sms_number"] = "";
                    $extra_fields["gender"] = "M";
                    $extra_fields["uuid_key"] = "";
                    $extra_fields["app_token"] = "";
                    $extra_fields["password"] = $pwd;
                    $extra_fields["coin"] = 0;
                    $extra_fields["coin_update"] = "";
                    $extra_fields["profile_picture_uploaded"] = "";
                } else if ($role == "developer") {
                    $extra_fields["service_plan"] = 100;
                    $extra_fields["app_coins"] = 0;
                }
                //  inno_log_db::log_vcoin_login(-1, 101222, "new user create_user_account.");
                $this->reg_user = $this->create_user_account($login_name, $user_email, $role, $extra_fields, $pwd);
                if ($role == "appuser") {
                    //  inno_log_db::log_vcoin_login(-1, 101222, "new user and add uuid to the vcoin server.");
                    $this->create_vcoin_key_for_user();
                }
            } catch (Exception $e) {
                throw $e;
            }
        }

        /**
         * @param $login_name
         * @param $user_email
         * @param $role
         * @param array $extra_fields
         * @throws Exception
         */
        public function newUserRandomPass($login_name, $user_email, $role, $extra_fields = array())
        {
            try {
                $this->reg_user = $this->create_user_account($login_name, $user_email, $role, $extra_fields, wp_generate_password($length = 12, $include_standard_special_chars = TRUE));
                if ($role == "appuser") {
                    $this->create_vcoin_key_for_user();
                }
            } catch (Exception $e) {
                throw $e;
            }
        }
        /*
            public static function UpdateUserMeta($user_id, $data)
            {
                if (is_array($data)) {
                    foreach ($data as $key => $value) {
                        update_user_meta($user_id, $key, $value);
                    }
                }
            }

            public static function AddUserMeta($user_id, $data)
            {
                foreach ($data as $key => $value) {
                    add_user_meta($user_id, $key, $value);
                }
            }*/

        /**
         * @param $user_name
         * @return string
         */
        protected static function get_unique_new_username($user_name)
        {
            $returnUsername = '';
            $check_same_id = 0;
            if (!is_null(username_exists($user_name))) {
                $check_same_id++;
                $returnUsername = $user_name . $check_same_id;
            } else {
                $returnUsername = $user_name;
            }
            return $returnUsername;
        }

        /**
         * create a user account in here now
         * @param $login_name
         * @param $user_email
         * @param $role
         * @param array $extra_fields
         * @param $pwd
         * @throws Exception
         * @return WP_User
         */

        protected static function create_user_account($login_name, $user_email, $role, $extra_fields = array(), $pwd)
        {
            try {
                // $pwd = !$generate_password? wp_generate_password($length = 12, $include_standard_special_chars = TRUE);
                //  add_action("user_register", array(__CLASS__, "user_reg_action_cb"), 10, 1);
                remove_action("user_register", array(__CLASS__, "new_user_reg"));
                $namelist = explode(" ", $login_name);
                $login_name_final = $role . gformBase::gen_order_num() . join("_", $namelist);
                $user_id = wp_create_user($login_name_final, $pwd, $user_email);
                if (is_wp_error($user_id)) {
                    throw new Exception($user_id->get_error_message(), 10129);
                }
                add_action("user_register", array(__CLASS__, "new_user_reg"));
                //   remove_action("user_register", array(__CLASS__, "user_reg_action_cb"));
                $user = new WP_User($user_id);

                foreach ($extra_fields as $key => $val) {
                    // update_user_meta($user_id, $key, $val, false);
                    add_user_meta($user_id, $key, $val, false);
                }

                update_user_meta($user_id, 'display_name', $login_name);
                update_user_meta($user_id, "nickname", $login_name);
                update_user_meta($user_id, "first_name", $namelist[0]);
                update_user_meta($user_id, "last_name", $namelist[1]);

                //  debugoc::upload_bmap_log(print_r($args, true), 29291);
                //wp_insert_user($args);
                $user->remove_role('subscriber');
                $user->add_role($role);
                return $user;
            } catch (Exception $e) {
                throw $e;
            }
        }

        /**
         * Handles sending password retrieval email to user.
         *
         * @uses $wpdb WordPress Database object
         * @param string $user_login User Login or Email or User ID
         * @return bool true on success false on error
         */
        public static function retrieve_password($user_login)
        {
            global $wpdb, $current_site;
            if (empty($user_login)) {
                //
                return false;
            } else if (is_numeric($user_login)) {
                $user_data = get_user_by('id', $user_login);
            } else if (strpos($user_login, '@')) {
                $user_data = get_user_by('email', trim($user_login));
                if (empty($user_data))
                    return false;
            } else {
                $login = trim($user_login);
                $user_data = get_user_by('login', $login);
            }

            do_action('lostpassword_post');

            if (!$user_data)
                return false;

            // redefining user_login ensures we return the right case in the email
            $user_login = $user_data->user_login;
            $user_email = $user_data->user_email;

            //  do_action('retreive_password', $user_login);
            // Misspelled and deprecated
            do_action('retrieve_password', $user_login);

            $allow = apply_filters('allow_password_reset', true, $user_data->ID);

            if (!$allow)
                return false;
            else if (is_wp_error($allow))
                return false;

            $key = $wpdb->get_var($wpdb->prepare("SELECT user_activation_key FROM $wpdb->users WHERE user_login = %s", $user_login));
            if (empty($key)) {
                // Generate something random for a key...
                $key = wp_generate_password(20, false);
                do_action('retrieve_password_key', $user_login, $key);
                // Now insert the new md5 key into the db
                $wpdb->update($wpdb->users, array('user_activation_key' => $key), array('user_login' => $user_login));
            }
            $message = __('Someone requested that the password be reset for the following account:') . "\r\n\r\n";
            $message .= network_home_url('/') . "\r\n\r\n";
            $message .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n";
            $message .= __('If this was a mistake, just ignore this email and nothing will happen.') . "\r\n\r\n";
            $message .= __('To reset your password, visit the following address:') . "\r\n\r\n";
            $message .= '<' . network_site_url("wp-login.php?action=rp&key=$key&login=" . rawurlencode($user_login), 'login') . ">\r\n";

            if (is_multisite())
                $blogname = $GLOBALS['current_site']->site_name;
            else
                // The blogname option is escaped with esc_html on the way into the database in sanitize_option
                // we want to reverse this for the plain text arena of emails.
                $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);

            $title = sprintf(__('[%s] Password Reset'), $blogname);

            $title = apply_filters('retrieve_password_title', $title);
            $message = apply_filters('retrieve_password_message', $message, $key);

            if ($message && !wp_mail($user_email, $title, $message))
                wp_die(__('The e-mail could not be sent.') . "<br />\n" . __('Possible reason: your host may have disabled the mail() function...'));

            return true;
        }

    }
}


text:
package com.stnetix.cloudraid.api.exception;

/**
 * Exception on some action with CloudRaidAPI
 *
 * @author Cloudraid Dev Team (cloudraid.stnetix.com)
 */
public class CloudApiException extends Exception {
}


text:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConvertKitSharp.Entities
{
    public class ConvertKitSubscriberList
    {
        /// <summary>
        /// The current page of results.
        /// </summary>
        [JsonProperty("page")]
        public int Page { get; set; }

        /// <summary>
        /// The total number of available pages.
        /// </summary>
        [JsonProperty("total_pages")]
        public int TotalPages { get; set; }

        /// <summary>
        /// The total number of subscribers.
        /// </summary>
        [JsonProperty("total_subscribers")]
        public int TotalSubscribers { get; set; }

        /// <summary>
        /// An array of subscribers for the current page.
        /// </summary>
        [JsonProperty("subscribers")]
        public IEnumerable<ConvertKitSubscriber> Subscribers { get; set; }
    }
}


text:
NS_ASSUME_NONNULL_BEGIN

@interface NSString (CYLog)
- (NSString *)unicodeString;
@end

NS_ASSUME_NONNULL_END


text:
redirect_to: https://anvio.org/help/7/programs/anvi-get-sequences-for-gene-calls
---


text:
module Concurrent
  module Actor
    module Behaviour
      # Simply fails when message arrives here. It's usually the last behaviour.
      class ErrorsOnUnknownMessage < Abstract
        def on_envelope(envelope)
          raise UnknownMessage, envelope
        end
      end
    end
  end
end


text:
Run the following commands on your server
```bash
mysql -u root -p
```

```bash
CREATE DATABASE IF NOT EXISTS laravel_shop;
```

## Set up database config in project

Don't forget to setup your ".env" file

```ini
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_shop
DB_USERNAME=root
DB_PASSWORD=toor
```

## Installation

Run the following command and provide the latest stable version (e.g 1.0.4) :

```bash
composer require stdsync/laravel-shop
```

or add the following to your `composer.json` file :

```json
"stdsync/laravel-shop": "1.0.4"
```

Then register this service provider with Laravel :

```php
'stdsync\LaravelShop\LaravelShopServiceProvider',
```

### Laravel 5.2 :

Service provider should be :

```php
stdsync\LaravelShop\LaravelShopServiceProvider::class,
```

Publish needed assets (styles, views, config files) :

```bash
php artisan vendor:publish --provider="stdsync\LaravelShop\LaravelShopServiceProvider"
```
*Note:* Composer won't update them after `composer update`, you'll need to do it manually!

## Routes

Routes for this package are added in register of the package
See routes file on how do extend the shop
```php
app\Http\routes.php
```

## Database

## Run migrations

To set up the database run the migrations and/or migrations --seed

```php
php artisan migrate:refresh --seed
```

## Add Middleware

Add the following middleware to Kernel.php::$middlewareGroups

```php
'shop' => [
    \stdsync\LaravelShop\Middleware\ShopSessionMiddleware::class
]
```

All set!!!

Happy shop coding

### Todo
- use Facades
- create more helpers
- reconstruct the interfaces
- clean up big controllers (move into shop structure)
- set up more configs
- add form validations
- cleanup duplicate templates


text:
package com.chupacadabra.evolution;

import java.io.Serializable;

/**
 * Settings and policies for the differential evolution optimizer.
 *

 * Using the default constructor of this class will create a reasonable set of
 * default policies suitable for a wide variety of problems. In addition, all of
 * the default policies are safe for use by multiple threads.
 *

 * The setter methods throws {@link NullPointerException NullPointerExceptions}
 * if the the value is null.
 */
public final class DifferentialEvolutionSettings implements Serializable {

    /**
     * Default maximum generation: {@value}
     */
    public static final int DEFAULT_MAXIMUM_GENERATION = 201;

    /**
     * Default candidate pool size: {@value}
     */
    public static final int DEFAULT_CANDIDATE_POOL_SIZE = 128;

    /**
     * Default children per candidate: {@value}
     */
    public static final int DEFAULT_CHILDREN_PER_CANDIDATE = 4;

    /**
     * Serial ID.
     */
    private static final long serialVersionUID = 4738577104948484276L;

    /**
     * Maximum generation.
     */
    private int maximumGeneration;

    /**
     * The pool size.
     */
    private int candidatePoolSize;

    /**
     * Children to generate per candidate.
     */
    private int childrenPerCandidate;

    /**
     * Source of randomness.
     */
    private RandomSource randomSource;

    /**
     * Differentiation policy.
     */
    private DifferentiationPolicy differentiationPolicy;

    /**
     * Recombination policy.
     */
    private RecombinationPolicy recombinationPolicy;

    /**
     * Candidate selection policy.
     */
    private SelectionPolicy selectionPolicy;

    /**
     * Diversity policy.
     */
    private DiversityPolicy diversityPolicy;

    /**
     * Pool replacement.
     */
    private PoolReplacement poolReplacement;

    /**
     * Fairness policy when locking the candidate pools.
     */
    private LockFairness poolLockFairness;

    /**
     * Exception behavior.
     */
    private ExceptionBehavior exceptionBehavior;

    /**
     * Constructor.
     */
    public DifferentialEvolutionSettings() {
        maximumGeneration = DEFAULT_MAXIMUM_GENERATION;
        candidatePoolSize = DEFAULT_CANDIDATE_POOL_SIZE;
        childrenPerCandidate = DEFAULT_CHILDREN_PER_CANDIDATE;

        // these policies basically given the "classic" differential evolution
        // algorithm of Storn et al.
        differentiationPolicy = new BestDifferentiationPolicy();
        recombinationPolicy = new BinomialRecombinationPolicy();
        diversityPolicy = new NoDiversityPolicy();

        // the only selection policy we know about!
        selectionPolicy = new DebSelectionPolicy();

        // this generally results in faster convergence.
        poolReplacement = PoolReplacement.IMMEDIATELY;

        // any exceptions will terminate the optimization and be throw to the
        // invoker.
        exceptionBehavior = ExceptionBehavior.PROPOGATE;

        // use unfair locking because it should be faster.
        poolLockFairness = LockFairness.UNFAIR;

        // use the only implementation we know of.
        randomSource = new JavaUtilRandomSource();
    }

    /**
     * Get the maximum generation.
     *
     * @return The maximum generation.
     */
    public int getMaximumGeneration() {
        return maximumGeneration;
    }

    /**
     * Set the maximum generation.
     *
     * @param maximumGeneration The value.
     * @throws IllegalArgumentException If maximumGeneration is no
     *         strictly positive.
     */
    public void setMaximumGeneration(final int maximumGeneration) {
        if (maximumGeneration <= 0) {
            throw new IllegalArgumentException("maximumGeneration must be positive");
        }

        this.maximumGeneration = maximumGeneration;
    }

    /**
     * Get the candidate pool size.
     *
     * @return The pool size.
     */
    public int getCandidatePoolSize() {
        return candidatePoolSize;
    }

    /**
     * Set the candidate pool size.
     *
     * @param candidatePoolSize The new pool size.
     * @throws IllegalArgumentException If candidatePoolSize is
     *         less than 4.
     */
    public void setCandidatePoolSize(final int candidatePoolSize) {
        if (candidatePoolSize < 4) {
            throw new IllegalArgumentException("candidatePoolSize must be greater than 4");
        }

        this.candidatePoolSize = candidatePoolSize;
    }

    /**
     * Get the number of child to generate per candidate during each generation.
     *
     * @return The number of children.
     */
    public int getChildrenPerCandidate() {
        return childrenPerCandidate;
    }

    /**
     * Set the number of children to generate per candidate.
     *
     * @param childrenPerCandidate The new number of children.
     * @throws IllegalArgumentException If childrenPerCandidate is
     *         less than 1
     */
    public void setChildrenPerCandidate(final int childrenPerCandidate) {
        if (childrenPerCandidate < 1) {
            throw new IllegalArgumentException("childrenPerCandidate must be greater than 0");
        }

        this.childrenPerCandidate = childrenPerCandidate;
    }

    /**
     * Get the source of randomness to use.
     *
     * @return The source of randomness.
     */
    public RandomSource getRandomSource() {
        return randomSource;
    }

    /**
     * Set the source of randomness.
     *
     * @param randomSource The new source.
     * @throws NullPointerException If randomSource is
     *         null.
     */
    public void setRandomSource(final RandomSource randomSource) {
        if (randomSource == null) {
            throw new NullPointerException("randomSource");
        }

        this.randomSource = randomSource;
    }

    /**
     * Get the differentiation policy.
     *
     * @return The differentiation policy.
     */
    public DifferentiationPolicy getDifferentiationPolicy() {
        return differentiationPolicy;
    }

    /**
     * Set the differentiation policy.
     *
     * @param differentiationPolicy The new differentiation policy.
     */
    public void setDifferentiationPolicy(final DifferentiationPolicy differentiationPolicy) {
        if (differentiationPolicy == null) {
            throw new NullPointerException("differentiationPolicy");
        }

        this.differentiationPolicy = differentiationPolicy;
    }

    /**
     * Get the recombination policy.
     *
     * @return The recombinationPolicy The recombination policy.
     */
    public RecombinationPolicy getRecombinationPolicy() {
        return recombinationPolicy;
    }

    /**
     * Set the recombination policy.
     *
     * @param recombinationPolicy The new recombination policy.
     */
    public void setRecombinationPolicy(final RecombinationPolicy recombinationPolicy) {
        if (recombinationPolicy == null) {
            throw new NullPointerException("recombinatonPolicy");
        }

        this.recombinationPolicy = recombinationPolicy;
    }

    /**
     * Get the diversity policy.
     *
     * @return The diversity policy.
     */
    public DiversityPolicy getDiversityPolicy() {
        return diversityPolicy;
    }

    /**
     * Set the diversity policy.
     *
     * @param diversityPolicy The new diversity policy.
     */
    public void setDiversityPolicy(final DiversityPolicy diversityPolicy) {
        if (diversityPolicy == null) {
            throw new NullPointerException("diversityPolicy");
        }

        this.diversityPolicy = diversityPolicy;
    }

    /**
     * Set the selection policy.
     *
     * @return The selection policy.
     */
    public SelectionPolicy getSelectionPolicy() {
        return selectionPolicy;
    }

    /**
     * Set the selection policy.
     *
     * @param selectionPolicy The new selection policy.
     */
    public void setSelectionPolicy(final SelectionPolicy selectionPolicy) {
        this.selectionPolicy = selectionPolicy;
    }

    /**
     * Get the pool replacement type.
     *
     * @return The pool replacement.
     */
    public PoolReplacement getPoolReplacement() {
        return poolReplacement;
    }

    /**
     * Set the pool replacement type.
     *
     * @param poolReplacement The value.
     */
    public void setPoolReplacement(final PoolReplacement poolReplacement) {
        this.poolReplacement = poolReplacement;
    }

    /**
     * Get the exception behavior.
     *
     * @return The exception behavior.
     */
    public ExceptionBehavior getExceptionBehavior() {
        return exceptionBehavior;
    }

    /**
     * Set the exception behavior.
     *
     * @param exceptionBehavior The value.
     * @throws NullPointerException If exceptionBehavior is
     *         null.
     */
    public void setExceptionBehavior(final ExceptionBehavior exceptionBehavior) {
        if (exceptionBehavior == null) {
            throw new NullPointerException("exceptionBehavior");
        }

        this.exceptionBehavior = exceptionBehavior;
    }

    /**
     * Get the pool lock fairness.
     *
     * @return The pool lock fairness.
     */
    public LockFairness getPoolLockFairness() {
        return poolLockFairness;
    }

    /**
     * Set the pool lock fairness.
     *
     * @param poolLockFairness The value.
     */
    public void setPoolLockFairness(final LockFairness poolLockFairness) {
        if (poolLockFairness == null) {
            throw new NullPointerException("poolLockFairness");
        }

        this.poolLockFairness = poolLockFairness;
    }

}


text:
@interface POPLearningController ()<EditDataControllerDelegate>{
    UITextView*       _textTV;
    UIButton*         _editButton;
    NSString*         _filePath;
}

@end

@implementation POPLearningController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"POP学习";

    [self initUI];
    NSString* filePath;
    if ([[HQFileManager shareManager] copyFileFromBoundlePathToSand:POPLEARNINGFILE andNewPath:&filePath]) {
        _filePath = filePath;
    }else{
        _filePath = FILEPATH(POPLEARNINGFILE);
        _editButton.hidden = YES;
    }
    [self loadDataWithfilePath:_filePath];
}

- (void)initUI
{
    _textTV = [[UITextView alloc] initWithFrame:self.view.bounds];
    _textTV.hq_height = DeviceHeight - NaviBarHeight - StatusBarHeight;
    _textTV.editable = NO;
    _textTV.selectable = NO;
    _textTV.font = FONTXinWeiBase6(17);
    _textTV.textColor = COLOR(80, 80, 80);
    _textTV.textContainerInset = UIEdgeInsetsMake(5, 4, 10, 4);
    [self.view addSubview:_textTV];

    UIButton* rightButton = [UIButton createHQNavigationBarRedTextButtonWithText:@"编辑"];
    _editButton = rightButton;
    [rightButton addTarget:self action:@selector(editingData) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];

}

- (void)loadDataWithfilePath:(NSString* )filePath
{
    NSError* error;
    NSString* dataString = [NSString stringWithContentsOfFile:filePath
                                                     encoding:NSUTF8StringEncoding
                                                        error:&error];
    if (error) {
        dataString = @"数据加载失败~";
    }
    _textTV.text = dataString;
}

#pragma mark - private function
- (void)editingData
{
    EditDataController* desVC = [[EditDataController alloc] initWithFilePath:_filePath];
    desVC.delegate = self;
    RootNavigationController* naiVC = [[RootNavigationController alloc] initWithRootViewController:desVC];
    [self presentViewController:naiVC animated:YES completion:nil];

}

- (void)goBackNavigation
{
    self.type = TransitionTypeGravity;
    [super goBackNavigation];
}

#pragma mark - EditDataControllerDelegate
- (void)hasUpdateData:(NSString *)filePath
{
    [self loadDataWithfilePath:filePath];
}

@end


text:
@interface UIImage(UIBarButtonItem)

+ (UIImage *)imageFromSystemBarButton:(UIBarButtonSystemItem)systemItem;

@end


text:
package reactor.core.publisher;

import java.util.concurrent.atomic.AtomicInteger;

import org.junit.Test;

import reactor.test.subscriber.AssertSubscriber;

public class MonoDeferComposeTest {
    @Test
    public void perTrackable() {

        Mono<Integer> source = Mono.just(10).compose(f -> {
            AtomicInteger value = new AtomicInteger();
            return f.map(v -> v + value.incrementAndGet());
        });

        for (int i = 0; i < 10; i++) {
            AssertSubscriber<Integer> ts = AssertSubscriber.create();

            source.subscribe(ts);

            ts.assertValues(11)
            .assertComplete()
            .assertNoError();
        }
    }

    @Test
    public void composerThrows() {
        Mono<Integer> source = Mono.just(10).compose(f -> {
            throw new RuntimeException("Forced failure");
        });

        for (int i = 0; i < 10; i++) {
            AssertSubscriber<Integer> ts = AssertSubscriber.create();

            source.subscribe(ts);

            ts.assertNoValues()
            .assertNotComplete()
            .assertError(RuntimeException.class);
        }

    }

    @Test
    public void composerReturnsNull() {
        Mono<Integer> source = Mono.just(10).compose(f -> {
            return null;
        });

        for (int i = 0; i < 10; i++) {
            AssertSubscriber<Integer> ts = AssertSubscriber.create();

            source.subscribe(ts);

            ts.assertNoValues()
            .assertNotComplete()
            .assertError(NullPointerException.class);
        }

    }
}