text:
package uk.co.badgersinfoil.metaas.fixes;

import junit.framework.TestCase;
import uk.co.badgersinfoil.metaas.ActionScriptFactory;
import uk.co.badgersinfoil.metaas.ActionScriptParser;
import uk.co.badgersinfoil.metaas.dom.*;

import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * This tests check if the field access with namespace is parsed correctly.
 *
 * @author Alexander Eliseyev
 */
public class NamespaceFieldAccessTest extends TestCase {

    public void testFieldAccessExpression() {
        ActionScriptFactory fact = new ActionScriptFactory();
		ASCompilationUnit unit = loadSyntaxExample(fact);

        ASClassType classType = (ASClassType) unit.getType();
        ASMethod myFuncMethod = classType.getMethod("myFunc");

        Statement statement = (Statement) myFuncMethod.getStatementList().get(1);
        assertNotNull(statement);
        assertTrue(statement instanceof ASExpressionStatement);

        ASExpressionStatement expressionStatement = (ASExpressionStatement) statement;
        Expression expression = expressionStatement.getExpression();

        assertTrue(expression instanceof ASFieldAccessExpression);
        ASFieldAccessExpression fieldAccessExpression = (ASFieldAccessExpression) expression;

        assertEquals("stuff", fieldAccessExpression.getName());
        assertEquals("myns", fieldAccessExpression.getNamespace());
    }

    public void testFieldAccessExpression_emptyNS() {
        ActionScriptFactory fact = new ActionScriptFactory();
		ASCompilationUnit unit = loadSyntaxExample(fact);

        ASClassType classType = (ASClassType) unit.getType();
        ASMethod myFuncMethod = classType.getMethod("myFunc");

        Statement statement = (Statement) myFuncMethod.getStatementList().get(3);
        assertNotNull(statement);
        assertTrue(statement instanceof ASExpressionStatement);

        ASExpressionStatement expressionStatement = (ASExpressionStatement) statement;
        Expression expression = expressionStatement.getExpression();

        assertTrue(expression instanceof ASFieldAccessExpression);
        ASFieldAccessExpression fieldAccessExpression = (ASFieldAccessExpression) expression;

        assertEquals("stuff", fieldAccessExpression.getName());
        assertNull(fieldAccessExpression.getNamespace());
    }

    public void testSimpleNameExpression() {
		ActionScriptFactory fact = new ActionScriptFactory();
		ASCompilationUnit unit = loadSyntaxExample(fact);

        ASClassType classType = (ASClassType) unit.getType();
        ASMethod myFuncMethod = classType.getMethod("myFunc");

        Statement statement = (Statement) myFuncMethod.getStatementList().get(0);
        assertNotNull(statement);
        assertTrue(statement instanceof ASExpressionStatement);

        ASExpressionStatement expressionStatement = (ASExpressionStatement) statement;
        Expression expression = expressionStatement.getExpression();

        assert (expression instanceof ASSimpleNameExpression);
        ASSimpleNameExpression simpleNameExpression = (ASSimpleNameExpression) expression;
        assertEquals("stuff", simpleNameExpression.getName());
        assertEquals("myns", simpleNameExpression.getNamespace());
	}

    public void testSimpleNameExpression_emptyNS() {
		ActionScriptFactory fact = new ActionScriptFactory();
		ASCompilationUnit unit = loadSyntaxExample(fact);

        ASClassType classType = (ASClassType) unit.getType();
        ASMethod myFuncMethod = classType.getMethod("myFunc");

        Statement statement = (Statement) myFuncMethod.getStatementList().get(2);
        assertNotNull(statement);
        assertTrue(statement instanceof ASExpressionStatement);

        ASExpressionStatement expressionStatement = (ASExpressionStatement) statement;
        Expression expression = expressionStatement.getExpression();

        assertTrue(expression instanceof ASSimpleNameExpression);
        ASSimpleNameExpression simpleNameExpression = (ASSimpleNameExpression) expression;
        assertEquals("stuff", simpleNameExpression.getName());
        assertNull(simpleNameExpression.getNamespace());
	}

    private static void print(String str) {
        System.out.println(str);
    }

	private ASCompilationUnit loadSyntaxExample(ActionScriptFactory fact) {
		InputStream in = getClass().getClassLoader().getResourceAsStream("NamespaceFieldAccess.as");
		ActionScriptParser parser = fact.newParser();
		ASCompilationUnit unit = parser.parse(new InputStreamReader(in));
		return unit;
	}
}


text:
using namespace mesos;

ParametersPtr toParameters(ParameterPtr* parameters,
			   int pLen)
{
  ParametersPtr params = new Parameters();
  for (int i = 0; i < pLen; ++i)
    *params->add_parameter() = *parameters[i];
  return params;
}

void fromParameters(ParametersPtr params,
		    ParameterPtr** parameters,
		    int* pLen)
{
  *parameters = params->mutable_parameter()->mutable_data();
  *pLen = params->parameter_size();
}

void destroyParameters(ParametersPtr params)
{
  delete params;
}

redpajama_set_name: RedPajamaGithub


text:
module Azure::BatchAI::Mgmt::V2018_05_01
  module Models
    #
    # Unmanaged file system mounting configuration.
    #
    class UnmanagedFileSystemReference

      include MsRestAzure

      # @return [String] Mount command. Mount command line. Note, Batch AI will
      # append mount path to the command on its own.
      attr_accessor :mount_command

      # @return [String] Relative mount path. The relative path on the compute
      # node where the unmanaged file system will be mounted. Note that all
      # cluster level unmanaged file systems will be mounted under
      # $AZ_BATCHAI_MOUNT_ROOT location and all job level unmanaged file
      # systems will be mounted under $AZ_BATCHAI_JOB_MOUNT_ROOT.
      attr_accessor :relative_mount_path

      #
      # Mapper for UnmanagedFileSystemReference class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'UnmanagedFileSystemReference',
          type: {
            name: 'Composite',
            class_name: 'UnmanagedFileSystemReference',
            model_properties: {
              mount_command: {
                client_side_validation: true,
                required: true,
                serialized_name: 'mountCommand',
                type: {
                  name: 'String'
                }
              },
              relative_mount_path: {
                client_side_validation: true,
                required: true,
                serialized_name: 'relativeMountPath',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
    <meta charset="utf-8">
    <title>Kalender</title>

                Mitarbeiterübersicht

Kalender

                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Reise

                        <input type="hidden" name="entry-index" value="">
                        <input type="hidden" name="entry-user-index" value="">
                        <input type="hidden" name="entry-marked" value="">
                        <form class="form-horizontal">

                                Reiseziel

                                    <select id="entry-location" class="selectpicker" data-live-search="true" data-width="100%">
                                    </select>

                                    <select id="entry-location-supplement" class="selectpicker" data-width="auto">
                                        <option value=''>Kein Zusatz</option>
                                    </select>

                                Datum

                                        <input name="entry-start-date" type="text" class="form-control" value="2016-04-05">

                                Kommentar

                                    <input id="entry-comment" name="entry-comment" type="text" class="form-control">

                                    <input id="entry-processed" name="entry-processed" type="checkbox"  class="form-control" data-toggle="toggle" data-onstyle="success" data-on="erledigt" data-off="offen" data-width="100%"/>

                        </form>

                        <button type="button" class="btn btn-default" data-dismiss="modal">Abbrechen</button>
                        <button type="button" class="btn btn-danger" id="delete-entry">Löschen</button>
                        <button type="button" class="btn btn-success" id="save-entry">Speichern</button>


text:
package flags

import (
	"reflect"
	"strings"
	"syscall"
)

// Set the value of an option to the specified value. An error will be returned
// if the specified value could not be converted to the corresponding option
// value type.
func (option *Option) set(value *string) error {
	option.isSet = true

	if option.isFunc() {
		return option.call(value)
	} else if value != nil {
		return convert(*value, option.value, option.tag)
	}

	return convert("", option.value, option.tag)
}

func (option *Option) canCli() bool {
	return option.ShortName != 0 || len(option.LongName) != 0
}

func (option *Option) canArgument() bool {
	if u := option.isUnmarshaler(); u != nil {
		return true
	}

	return !option.isBool()
}

func (option *Option) emptyValue() reflect.Value {
	tp := option.value.Type()

	if tp.Kind() == reflect.Map {
		return reflect.MakeMap(tp)
	}

	return reflect.Zero(tp)
}

func (option *Option) empty() {
	if !option.isFunc() {
		option.value.Set(option.emptyValue())
	}
}

func (option *Option) clearDefault() {
	usedDefault := option.Default
	if envKey := option.EnvDefaultKey; envKey != "" {
		// os.Getenv() makes no distinction between undefined and
		// empty values, so we use syscall.Getenv()
		if value, ok := syscall.Getenv(envKey); ok {
			if option.EnvDefaultDelim != "" {
				usedDefault = strings.Split(value,
					option.EnvDefaultDelim)
			} else {
				usedDefault = []string{value}
			}
		}
	}

	if len(usedDefault) > 0 {
		option.empty()

		for _, d := range usedDefault {
			option.set(&d)
		}
	} else {
		tp := option.value.Type()

		switch tp.Kind() {
		case reflect.Map:
			if option.value.IsNil() {
				option.empty()
			}
		case reflect.Slice:
			if option.value.IsNil() {
				option.empty()
			}
		}
	}
}

func (option *Option) valueIsDefault() bool {
	// Check if the value of the option corresponds to its
	// default value
	emptyval := option.emptyValue()

	checkvalptr := reflect.New(emptyval.Type())
	checkval := reflect.Indirect(checkvalptr)

	checkval.Set(emptyval)

	if len(option.Default) != 0 {
		for _, v := range option.Default {
			convert(v, checkval, option.tag)
		}
	}

	return reflect.DeepEqual(option.value.Interface(), checkval.Interface())
}

func (option *Option) isUnmarshaler() Unmarshaler {
	v := option.value

	for {
		if !v.CanInterface() {
			break
		}

		i := v.Interface()

		if u, ok := i.(Unmarshaler); ok {
			return u
		}

		if !v.CanAddr() {
			break
		}

		v = v.Addr()
	}

	return nil
}

func (option *Option) isBool() bool {
	tp := option.value.Type()

	for {
		switch tp.Kind() {
		case reflect.Bool:
			return true
		case reflect.Slice:
			return (tp.Elem().Kind() == reflect.Bool)
		case reflect.Func:
			return tp.NumIn() == 0
		case reflect.Ptr:
			tp = tp.Elem()
		default:
			return false
		}
	}
}

func (option *Option) isFunc() bool {
	return option.value.Type().Kind() == reflect.Func
}

func (option *Option) call(value *string) error {
	var retval []reflect.Value

	if value == nil {
		retval = option.value.Call(nil)
	} else {
		tp := option.value.Type().In(0)

		val := reflect.New(tp)
		val = reflect.Indirect(val)

		if err := convert(*value, val, option.tag); err != nil {
			return err
		}

		retval = option.value.Call([]reflect.Value{val})
	}

	if len(retval) == 1 && retval[0].Type() == reflect.TypeOf((*error)(nil)).Elem() {
		if retval[0].Interface() == nil {
			return nil
		}

		return retval[0].Interface().(error)
	}

	return nil
}


text:
package com.gmail.leftiness.storm_demo.spout;

import org.apache.storm.testing.TestWordSpout;

public class WordSpout extends TestWordSpout {}


text:
Next you can update your site name, avatar and other options using the _config.yml file in the root of your repository (shown below).

The easiest way to make your first post is to edit this one. Go into /_posts/ and update the Hello World markdown file. For more instructions head over to the Jekyll Now repository on GitHub.


text:
package com.ctrip.xpipe.redis.proxy.integrate;

import com.ctrip.xpipe.AbstractTest;
import com.ctrip.xpipe.api.endpoint.Endpoint;
import com.ctrip.xpipe.api.foundation.FoundationService;
import com.ctrip.xpipe.proxy.ProxyEndpoint;
import com.ctrip.xpipe.redis.core.proxy.endpoint.DefaultProxyEndpointManager;
import com.ctrip.xpipe.redis.core.proxy.endpoint.EndpointHealthChecker;
import com.ctrip.xpipe.redis.core.proxy.endpoint.ProxyEndpointHealthChecker;
import com.ctrip.xpipe.redis.proxy.DefaultProxyServer;
import com.ctrip.xpipe.redis.proxy.ProxyServer;
import com.ctrip.xpipe.redis.proxy.Session;
import com.ctrip.xpipe.redis.proxy.TestProxyConfig;
import com.ctrip.xpipe.redis.proxy.monitor.DefaultTunnelMonitorManager;
import com.ctrip.xpipe.redis.proxy.monitor.stats.impl.DefaultPingStatsManager;
import com.ctrip.xpipe.redis.proxy.resource.TestResourceManager;
import com.ctrip.xpipe.redis.proxy.session.BackendSession;
import com.ctrip.xpipe.redis.proxy.session.FrontendSession;
import com.ctrip.xpipe.redis.proxy.tunnel.DefaultTunnelManager;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.junit.BeforeClass;

import java.nio.charset.Charset;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;

import static com.ctrip.xpipe.redis.proxy.monitor.session.DefaultSessionMonitor.SESSION_MONITOR_SHOULD_START;
import static io.netty.handler.codec.ByteToMessageDecoder.MERGE_CUMULATOR;
import static org.mockito.Mockito.*;

/**
 * @author chen.zhu
 * <p>
 * May 23, 2018
 */
public class AbstractProxyIntegrationTest extends AbstractTest {

    public static final int FIRST_PROXY_TCP_PORT = 8992, SEC_PROXY_TCP_PORT = 8993;

    public static final int FIRST_PROXY_TLS_PORT = 1443, SEC_PROXY_TLS_PORT = 2443;

    @BeforeClass
    public static void beforeAbstractProxyIntegrationTest() {
        System.setProperty(SESSION_MONITOR_SHOULD_START, "false");
    }

    protected void prepare(DefaultProxyServer server) {
        sameStuff(server);
    }

    protected void prepareTLS(DefaultProxyServer server) {
        sameStuff(server);
    }

    protected void sameStuff(DefaultProxyServer server) {
        FoundationService service = FoundationService.DEFAULT;
        service = spy(FoundationService.DEFAULT);
        doReturn("127.0.0.1").when(service).getLocalIp();
        DefaultProxyEndpointManager endpointManager = new DefaultProxyEndpointManager(()-> 180);
        endpointManager.setHealthChecker(new ProxyEndpointHealthChecker() {
            @Override
            public boolean checkConnectivity(ProxyEndpoint endpoint) {
                return true;
            }
        });
        TestResourceManager resourceManager = new TestResourceManager();
        resourceManager.setEndpointManager(endpointManager);
        resourceManager.setConfig(server.getConfig());
        server.setTunnelManager(new DefaultTunnelManager()
                .setConfig(server.getConfig()).setProxyResourceManager(resourceManager)
                .setTunnelMonitorManager(new DefaultTunnelMonitorManager(resourceManager)));
        server.setResourceManager(resourceManager);
        if(server.getPingStatsManager() != null) {
            ((DefaultPingStatsManager)server.getPingStatsManager()).setResourceManager(resourceManager)
                    .setEndpointManager(endpointManager);
        }
    }

    protected DefaultProxyServer startFirstProxy() throws Exception {
        // uncomment disable netty bytebuf test
//        ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.DISABLED);
        DefaultProxyServer server = new DefaultProxyServer().setConfig(new TestProxyConfig()
                .setFrontendTcpPort(FIRST_PROXY_TCP_PORT).setFrontendTlsPort(FIRST_PROXY_TLS_PORT).setStartMonitor(false))
                .setPingStatsManager(new DefaultPingStatsManager());
        prepare(server);
        ((TestProxyConfig)server.getResourceManager().getProxyConfig()).setStartMonitor(false);
        ((DefaultPingStatsManager)server.getPingStatsManager()).postConstruct();
        server.start();
        return server;
    }

    protected void startSecondaryProxy() throws Exception {
        DefaultProxyServer server = new DefaultProxyServer().setConfig(new TestProxyConfig()
                .setFrontendTcpPort(SEC_PROXY_TCP_PORT).setFrontendTlsPort(SEC_PROXY_TLS_PORT).setStartMonitor(false))
                .setPingStatsManager(new DefaultPingStatsManager());
        prepare(server);
        ((TestProxyConfig)server.getResourceManager().getProxyConfig()).setStartMonitor(false).startMonitor();
        ((DefaultPingStatsManager)server.getPingStatsManager()).postConstruct();
        server.start();
    }

    protected String generateSequncialString(int length) {
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < length; i++) {
            sb.append(i).append(' ');
            if(i != 0 && (i % 10) == 0) {
                sb.append("\r\n");
            }
        }
        return sb.toString();
    }

    protected void write(ChannelFuture future, String sendout)
            throws InterruptedException, ExecutionException, TimeoutException {
        if (!future.channel().isActive() && future.channel().isOpen()) {
            logger.info("[write] wait channel active before writeAndFlush, otherwise flush will be failed");
            future.get(3, TimeUnit.SECONDS);
        } else if (!future.channel().isOpen()) {
            logger.info("[write] channel already closed, write will be failed");
        }

        logger.info("[write] {}", sendout);
        future.channel().writeAndFlush(UnpooledByteBufAllocator.DEFAULT.buffer().writeBytes(sendout.getBytes()))
                .addListener(writeFuture -> {
                    if (writeFuture.isSuccess()) {
                        logger.info("[write][success] {}", sendout);
                    } else {
                        logger.info("[write][fail]", writeFuture.cause());
                    }
                });
    }

    public ChannelFuture startListenServer(int port) {
        return serverBootstrap().childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new AbstractProxyIntegrationTest.ListeningHandler());
            }
        }).bind(port);
    }

    public ChannelFuture startReceiveServer(int port, AtomicReference<ByteBuf> receivedBuf) {
        return serverBootstrap().childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new AbstractProxyIntegrationTest.ReceiveHandler(receivedBuf));
            }
        }).bind(port);
    }

    class ListeningHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ByteBuf byteBuf = (ByteBuf) msg;
            logger.info("[ListeningHandler][receive] {}", byteBuf.toString(Charset.defaultCharset()));
            super.channelRead(ctx, msg);
        }

        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            logger.info("[ListeningHandler][channel in-active");
            super.channelInactive(ctx);
        }

        @Override
        public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
            logger.info("[ListeningHandler][channel un-register");
            super.channelUnregistered(ctx);
        }
    }

    class ReceiveHandler extends ChannelInboundHandlerAdapter {

        private ByteToMessageDecoder.Cumulator cumulator = MERGE_CUMULATOR;

        private ByteBuf cumulation;

        private AtomicReference<ByteBuf> buffer;

        public ReceiveHandler(AtomicReference<ByteBuf> buffer) {
            this.buffer = buffer;
            cumulation = buffer.get();
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ByteBuf byteBuf = (ByteBuf) msg;
            byteBuf.retain();
            cumulator.cumulate(ctx.channel().alloc(), cumulation, byteBuf);
            buffer.set(cumulation);
            super.channelRead(ctx, msg);
        }

        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            logger.info("[ReceiveHandler][channel in-active");
            buffer.set(cumulation);
            super.channelInactive(ctx);
        }

        @Override
        public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
            logger.info("[ReceiveHandler][channel un-register");
            super.channelUnregistered(ctx);
        }
    }

    public Bootstrap clientBootstrap() {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.channel(NioSocketChannel.class)
                .group(new NioEventLoopGroup(1))
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new LoggingHandler(LogLevel.DEBUG));
                    }
                });
        return bootstrap;
    }

    public ServerBootstrap serverBootstrap() {
        ServerBootstrap b = new ServerBootstrap();
        b.channel(NioServerSocketChannel.class)
                .group(new NioEventLoopGroup(1), new NioEventLoopGroup(1))
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new LoggingHandler(LogLevel.DEBUG));
        return b;
    }

    protected static Session mockSession() {
        return mock(Session.class);
    }

    protected static FrontendSession mockFrontendSession() {
        return mock(FrontendSession.class);
    }

    protected static BackendSession mockBackendSession() {
        return mock(BackendSession.class);
    }

    protected static Channel mockChannel() {
        return mock(Channel.class);
    }
}


text:
'use strict'
var helper = require('../../helper');
var CustomsManager = require('../../../src/managers/garment-purchasing/customs-manager');
var poExternalManager = require('../../../src/managers/garment-purchasing/purchase-order-external-manager');

var codeGenerator = require('../../../src/utils/code-generator');
var deliveryOrderDataUtil = require('./delivery-order-data-util');
var ObjectId = require("mongodb").ObjectId;

class CustomsDataUtil {
    getNewData() {

        return helper
            .getManager(poExternalManager)
            .then(manager => {
                return Promise.all([deliveryOrderDataUtil.getNewTestData()])
                    .then(results => {
                        var dOrder = results[0];
                        var poExtId;
                        for(var data of dOrder.items){
                            poExtId = data.purchaseOrderExternalId;
                        }
                        return manager.getSingleByIdOrDefault(poExtId)
                            .then(dataPoExt => {
                                var code = codeGenerator();
                                var date = new Date();
                                var data = {
                                    no: `UT/Customs/${code}`,
                                    customsDate: date,
                                    validateDate: date,
                                    supplierId: dOrder.supplier._id,
                                    supplier: dOrder.supplier,
                                    amountOfPackaging: 10,
                                    packaging: 'BOX',
                                    bruto: 20,
                                    netto: 15,
                                    currencyId: dataPoExt.currency._id,
                                    currency: dataPoExt.currency,
                                    customsOrigin: '',
                                    customsType: 'BC 262',
                                    deliveryOrders: [dOrder]
                                };
                                return Promise.resolve(data);
                            });
                    });
            })
        }

    getNewTestData() {
        return helper
            .getManager(CustomsManager)
            .then((manager) => {
                return this.getNewData().then((data) => {
                    return manager.create(data)
                        .then((id) => manager.getSingleById(id));
                });
            });
    }

}

module.exports = new CustomsDataUtil();


text:
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.default =

pTimeout;  // A specialized version of `p-timeout` that does not touch globals.
// It does not throw on timeout.
function pTimeout(promise, ms, clearTimeout, setTimeout, onTimeout) {return new Promise((resolve, reject) => {const timer = setTimeout(() => resolve(onTimeout()), ms);promise.then(val => {
      clearTimeout(timer);
      resolve(val);
    },
    err => {
      clearTimeout(timer);
      reject(err);
    });

  });
}


text:
name: cljs.core/IEditableCollection
see also:
---

## Summary

## Details

## Examples


text:
package de.tudarmstadt.informatik.tk.assistance.sdk.model.api.module;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

/**
 * Error class for JSON response
 *
 * @author Wladimir Schmidt (wlsc.dev@gmail.com)
 * @date 14.07.2015
 */
public class ToggleModuleRequestDto {

    @SerializedName("module_id")
    @Expose
    private String moduleId;

    public ToggleModuleRequestDto() {
    }

    public ToggleModuleRequestDto(String moduleId) {
        this.moduleId = moduleId;
    }

    public String getModuleId() {
        return moduleId;
    }

    public void setModulePackageName(String moduleId) {
        this.moduleId = moduleId;
    }

    @Override
    public String toString() {
        return "ToggleModuleRequestDto{" +
                "moduleId='" + moduleId + '\'' +
                '}';
    }
}


text:
name             'windows_ad_test'
description      'Tests windows_ad'
version          '0.1.0'
depends          'windows_ad'


text:
"use strict";

/**
 * Gulp usage file for the whole project.
 */

var gulp = require("gulp");
var ts = require("gulp-typescript");
var eventStream = require("event-stream");
var tslint = require("gulp-tslint");
var sequence = require("run-sequence").use(gulp);
var babel = require("gulp-babel");
var path = require("path");
var merge = require("merge2");

var typeScriptSource = [
    "./typedefinitions/backend.d.ts",
    "./lib/**/*.ts"
];

// TYPESCRIPT COMPILATION
gulp.task("typescript", function() {
    var tsResult = gulp
        .src( typeScriptSource )
        // Pipe source to lint
        .pipe(tslint())
        .pipe(tslint.report("verbose"))
        // Push through to compiler
        .pipe(ts({
            typescript: require("typescript"),
            target: "es6",
            sourceMap: false,
            removeComments: false,
            declaration: true,
            noImplicitAny: true,
            failOnTypeErrors: false,
            suppressImplicitAnyIndexErrors: true
        }));

	return merge([
		tsResult.dts.pipe(gulp.dest("./lib")),
		tsResult.js.pipe(babel({
            comments: true,
            presets: [ "es2015" ]
        }))
        .pipe(gulp.dest("./lib"))
	]);
});

/**
 * Run with: 'gulp w'
 */
gulp.task("w", function() {
    gulp.watch(typeScriptSource, [ "typescript" ]);
});

/**
 * Run with: 'gulp' or 'gulp default'
 */
gulp.task("default", function() {
    return sequence([ "typescript" ]);
});


text:
<?php

use app\models\general\GeneralLabel;

use yii\helpers\Html;

/* @var $this yii\web\View */
/* @var $model app\models\RefBadanSukanAntarabangsa */

$this->title = GeneralLabel::updateTitle.' '.GeneralLabel::badan_sukan_antarabangsa.': ' . ' ' . $model->id;
$this->params['breadcrumbs'][] = ['label' => GeneralLabel::badan_sukan_antarabangsa, 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->id, 'url' => ['view', 'id' => $model->id]];
$this->params['breadcrumbs'][] = 'Update';
?>

<?= Html::encode($this->title) ?>

    <?= $this->render('_form', [
        'model' => $model,
    ]) ?>


text:
    <youtube-player width="100%"
                    keep-aspect-ratio
                    player-factory="FullscreenVideoPlayer"
                    video-id="ctrl.id"
                    ng-model="ctrl.player"
                    yt-fullscreen="ctrl.fullScreenCtrl"
                    >
    </youtube-player>

        <button ng-click="ctrl.player.playVideo()">Play</button>
        <button ng-click="ctrl.player.pauseVideo()">Pause</button>
        <button ng-show="ctrl.fullScreenCtrl.fullscreenEnabled()" ng-click="ctrl.fullScreenCtrl.requestFullscreen()">Full Screen</button>

        <input type="text" ng-model="ctrl.id"></input>


text:
#
# Cookbook Name:: resource_container_host_linux
# Recipe:: consul
#
# Copyright 2017, P. van der Velde
#

# Configure the service user under which consul will be run
poise_service_user node['consul']['service_user'] do
  group node['consul']['service_group']
end

#
# INSTALL CONSUL
#

# This installs consul as follows
# - Binaries: /usr/local/bin/consul
# - Configuration: /etc/consul/consul.json and /etc/consul/conf.d
include_recipe 'consul::default'

#
# ALLOW CONSUL THROUGH THE FIREWALL
#

firewall_rule 'consul-http' do
  command :allow
  description 'Allow Consul HTTP traffic'
  dest_port 8500
  direction :in
end

firewall_rule 'consul-dns' do
  command :allow
  description 'Allow Consul DNS traffic'
  dest_port 8600
  direction :in
  protocol :udp
end

firewall_rule 'consul-rpc' do
  command :allow
  description 'Allow Consul rpc LAN traffic'
  dest_port 8300
  direction :in
end

firewall_rule 'consul-serf-lan-tcp' do
  command :allow
  description 'Allow Consul serf LAN traffic on the TCP port'
  dest_port 8301
  direction :in
  protocol :tcp
end

firewall_rule 'consul-serf-lan-udp' do
  command :allow
  description 'Allow Consul serf LAN traffic on the UDP port'
  dest_port 8301
  direction :in
  protocol :udp
end

firewall_rule 'consul-serf-wan-tcp' do
  command :allow
  description 'Allow Consul serf WAN traffic on the TCP port'
  dest_port 8302
  direction :in
  protocol :tcp
end

firewall_rule 'consul-serf-wan-udp' do
  command :allow
  description 'Allow Consul serf WAN traffic on the UDP port'
  dest_port 8302
  direction :in
  protocol :udp
end


text:
<?php

abstract class PhabricatorOAuthServerController
  extends PhabricatorController {

  public function buildStandardPageResponse($view, array $data) {
    $user = $this->getRequest()->getUser();
    $page = $this->buildStandardPageView();
    $page->setApplicationName('OAuth Server');
    $page->setBaseURI('/oauthserver/');
    $page->setTitle(idx($data, 'title'));

    $nav = new AphrontSideNavFilterView();
    $nav->setBaseURI(new PhutilURI('/oauthserver/'));
    $nav->addLabel('Clients');
    $nav->addFilter('client/create',
                    'Create Client');
    foreach ($this->getExtraClientFilters() as $filter) {
      $nav->addFilter($filter['url'],
                      $filter['label']);
    }
    $nav->addFilter('client',
                    'My Clients');
    $nav->selectFilter($this->getFilter(),
                       'clientauthorization');

    $nav->appendChild($view);

    $page->appendChild($nav);

    $response = new AphrontWebpageResponse();
    return $response->setContent($page->render());
  }

  protected function getFilter() {
    return 'clientauthorization';
  }

  protected function getExtraClientFilters() {
    return array();
  }

  protected function getHighlightPHIDs() {
    $phids   = array();
    $request = $this->getRequest();
    $edited  = $request->getStr('edited');
    $new     = $request->getStr('new');
    if ($edited) {
      $phids[$edited] = $edited;
    }
    if ($new) {
      $phids[$new] = $new;
    }
    return $phids;
  }

  protected function buildErrorView($error_message) {
    $error = new AphrontErrorView();
    $error->setSeverity(AphrontErrorView::SEVERITY_ERROR);
    $error->setTitle($error_message);

    return $error;
  }
}


text:
/* eslint-disable max-len, quote-props, quotes */
export default [
  {
    "id": "app.buttons.add",
    "defaultMessage": "Add",
  },
  {
    "id": "app.buttons.cancel",
    "defaultMessage": "Cancel",
  },
  {
    "id": "app.buttons.delete",
    "defaultMessage": "Delete",
  },
  {
    "id": "app.buttons.dismiss",
    "defaultMessage": "Dismiss",
  },
  {
    "id": "app.buttons.edit",
    "defaultMessage": "Edit",
  },
  {
    "id": "app.buttons.save",
    "defaultMessage": "Save",
  },
  {
    "id": "app.buttons.signIn",
    "defaultMessage": "Sign In",
  },
  {
    "id": "app.buttons.signOut",
    "defaultMessage": "Sign Out",
  },
  {
    "id": "app.buttons.signUp",
    "defaultMessage": "Sign Up",
  },
  {
    "id": "app.buttons.submit",
    "defaultMessage": "Submit",
  },
  {
    "id": "app.confirm.areYouSure",
    "defaultMessage": "Are you sure?",
  },
  {
    "id": "app.confirm.unsavedChanges",
    "defaultMessage": "You have unsaved changes. Are you sure?",
  },
  {
    "id": "app.FieldError.required",
    "defaultMessage": "{prop, select, description {Please enter a description.} email {Please enter an email address.} name {Please enter a name.} password {Please enter a password.} other {You can't leave this empty.}}",
  },
  {
    "id": "app.links.fields",
    "defaultMessage": "Fields",
  },
  {
    "id": "app.links.home",
    "defaultMessage": "Home",
  },
  {
    "id": "app.links.intl",
    "defaultMessage": "Intl",
  },
  {
    "id": "app.links.me",
    "defaultMessage": "Me",
  },
  {
    "id": "app.links.notFound",
    "defaultMessage": "Page Not Found",
  },
  {
    "id": "app.links.offline",
    "defaultMessage": "Offline",
  },
  {
    "id": "app.links.profile",
    "defaultMessage": "Profile",
  },
  {
    "id": "app.links.settings",
    "defaultMessage": "Settings",
  },
  {
    "id": "app.links.signIn",
    "defaultMessage": "Sign in",
  },
  {
    "id": "app.links.todos",
    "defaultMessage": "Todos",
  },
  {
    "id": "app.links.users",
    "defaultMessage": "Users",
  },
  {
    "id": "auth.email.emailLegend",
    "defaultMessage": "Email",
  },
  {
    "id": "auth.email.emailPlaceholder",
    "defaultMessage": "your@email.com",
  },
  {
    "id": "auth.email.passwordForgotten",
    "defaultMessage": "Forgot Your Password?",
  },
  {
    "id": "auth.email.passwordPlaceholder",
    "defaultMessage": "password",
  },
  {
    "id": "auth.email.passwordRecoveryLegend",
    "defaultMessage": "Email Password Recovery",
  },
  {
    "id": "auth.email.recoveryEmailSent",
    "defaultMessage": "Recovery email has been sent.",
  },
  {
    "id": "auth.email.resetPassword",
    "defaultMessage": "Reset Password",
  },
  {
    "id": "auth.signInError.email",
    "defaultMessage": "Email address is not valid.",
  },
  {
    "id": "auth.signInError.required",
    "defaultMessage": "Please fill out {prop, select, email {email} password {password}}.",
  },
  {
    "id": "auth.signInError.simplePassword",
    "defaultMessage": "Password must contain at least {minLength} characters.",
  },
  {
    "id": "auth.social.facebookSignIn",
    "defaultMessage": "Login with Facebook",
  },
  {
    "id": "firebase.error.auth/network-request-failed",
    "defaultMessage": "No internet connection.",
  },
  {
    "id": "firebase.error.auth/too-many-requests",
    "defaultMessage": "Too many requests. Try it later, please.",
  },
  {
    "id": "firebase.error.auth/user-token-expired",
    "defaultMessage": "Your credential has expired. Please sign in.",
  },
  {
    "id": "firebase.error.EMAIL_TAKEN",
    "defaultMessage": "The new user account cannot be created because the\n      specified email address is already in use.",
  },
  {
    "id": "firebase.error.INVALID_EMAIL",
    "defaultMessage": "The specified email is not a valid email.",
  },
  {
    "id": "firebase.error.INVALID_PASSWORD",
    "defaultMessage": "The specified user account password is incorrect.",
  },
  {
    "id": "firebase.error.INVALID_USER",
    "defaultMessage": "The specified user account does not exist.",
  },
  {
    "id": "footer.madeByHtml",
    "defaultMessage": "Made with love by",
  },
  {
    "id": "intl.page.unreadCount",
    "defaultMessage": "{unreadCount, plural, one {message} other {messages}}",
  },
  {
    "id": "loading.loadingText",
    "defaultMessage": "Loading",
  },
  {
    "id": "loading.longLoadingText",
    "defaultMessage": "Still loading, please check your connection",
  },
  {
    "id": "notFound.continue",
    "defaultMessage": "Continue here please.",
  },
  {
    "id": "notFound.h1",
    "defaultMessage": "This page isn't available",
  },
  {
    "id": "notFound.p",
    "defaultMessage": "The link may be broken, or the page may have been removed.",
  },
  {
    "id": "todos.buttons.add100",
    "defaultMessage": "Add 100 Todos",
  },
  {
    "id": "todos.buttons.clearAll",
    "defaultMessage": "Clear All",
  },
  {
    "id": "todos.buttons.clearCompleted",
    "defaultMessage": "Clear Completed",
  },
  {
    "id": "todos.leftTodos",
    "defaultMessage": "{leftTodos, plural, =0 {Nothing, enjoy :-)} one {You have {leftTodos} task} other {You have {leftTodos} tasks}}",
  },
  {
    "id": "todos.newTodo.placeholder",
    "defaultMessage": "What needs to be done?",
  },
  {
    "id": "todos.todos.empty",
    "defaultMessage": "It's rather empty here...",
  },
];


text:
<?php
    $title = "Original | Chocolate Bars";
    $desc = "Giddy YoYo, Your source for the best in Organic foods, chocolate and sprouts. Our Cacao is 100% raw and brought all the way from Ecuador.";
    $can = "http://www.giddyyoyo.com/";
    $robots = "index, follow, noodp, noydir";
    $page = "Original";
    $background = "bars";

include('includes/header.php'); ?>

Original

                    <?php  include('includes/bar-menu.php'); ?>

CLASSIC!

If you desire a simple and pure chocolate, sweet but not too sweet, amazingly uplifting mind expansive delicious bar, the GY 76% ORIGINAL is for you. Our meticulous effort to use ONLY wild Ecuadorian Heirloom Arriba Nacional cacao puts us in a category of our own. This is not a marketing gimmick, this is the Truth. Try it and you'll understand.And if you don't understand it the first time keep trying it until you do. The Truth is inevitable.

Ingredients: Love & Gratitude, *Raw Arriba Nacional Cacao Paste, *Raw Unrefined Cane Juice Crystals, *Raw Arriba Nacional Cacao Butter. *Certified Organic by ECOCERT CANADA.

Create Heaven on Earth.

<?php include('includes/footer.php'); ?>


text:
module Raddocs
  class Parameters
    def initialize(params)
      @params = params
    end

    def parse
      extra_keys = @params.flat_map(&:keys).uniq - ["name", "description", "required", "scope"]

      {
        "extra_keys" => extra_keys,
        "data" => @params
      }
    end
  end
end


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

import {
  createAssignStateStatement,
  createBreakStatement,
  createCaseClause,
  createNumberLiteral
} from '../ParseTreeFactory.js';
import {parseStatement} from '../PlaceholderParser.js';

/**
 * A State in the generator state machine.
 *
 * The id in the state is unique across all machines in the function body.
 *
 * States are immutable.
 *
 * When knitting StateMachines together the states in one machine may need
 * renumbering in the new machine. replaceState() is used to create an
 * equivalent state with different state ids.
 */
export class State {
  /**
   * @param {number} id
   */
  constructor(id) {
    this.id = id;
  }

  /**
   * Transforms a state into a case clause during the final code generation pass
   * @param {FinallyState} enclosingFinally
   * @param {number} machineEndState
   * @param {ErrorReporter} reporter
   * @return {CaseClause}
   */
  transformMachineState(enclosingFinally, machineEndState, reporter) {
    return createCaseClause(createNumberLiteral(this.id),
        this.transform(enclosingFinally, machineEndState, reporter));
  }

  /**
   * @param {StringMap} labelSet
   * @param {number} breakState
   * @return {State}
   */
  transformBreak(labelSet, breakState) {
    return this;
  }

  /**
   * @param {StringMap} labelSet
   * @param {number=} breakState
   * @param {number=} continueState
   * @return {State}
   */
  transformBreakOrContinue(labelSet, breakState = undefined,
                           continueState = undefined) {
    return this;
  }
}

State.START_STATE = 0;
State.INVALID_STATE = -1;
State.END_STATE = -2;
State.RETHROW_STATE = -3;

/**
 * Returns a list of statements which jumps to a given destination state. If
 * transfering control to the destination state requires exiting a try of a
 * try/finally then the finally block must be executed along the way.
 *
 * @param {FinallyState} enclosingFinally
 * @param {number} fallThroughState
 * @return {Array.<ParseTree>}
 */
State.generateJump = function(enclosingFinally, fallThroughState) {
  return [
    ...State.generateAssignState(enclosingFinally, fallThroughState),
    createBreakStatement()
  ];
};

/**
 * @param {FinallyState} enclosingFinally
 * @param {number} fallThroughState
 * @return {Array.<ParseTree>}
 */
State.generateAssignState = function(enclosingFinally, fallThroughState) {
  let assignState;
  if (State.isFinallyExit(enclosingFinally, fallThroughState)) {
    assignState = generateAssignStateOutOfFinally(
        enclosingFinally,
        fallThroughState);
  } else {
    assignState = [createAssignStateStatement(fallThroughState)];
  }
  return assignState;
};

/**
 * @param {FinallyState} enclosingFinally
 * @param {number} fallThroughState
 * @return {boolean}
 */
State.isFinallyExit = function(enclosingFinally, destination) {
  return enclosingFinally != null &&
      enclosingFinally.tryStates.indexOf(destination) < 0;
};

/**
 * Generate code for a jump out of a finally block.
 * @param {FinallyState} enclosingFinally
 * @param {number} destination
 * @return {Array.<ParseTree>}
 */
function generateAssignStateOutOfFinally(enclosingFinally, destination) {
  let finallyState = enclosingFinally.finallyState;
  // $ctx.state = finallyState;
  // $fallThrough = destination;
  return [
    createAssignStateStatement(finallyState),
    parseStatement `$ctx.finallyFallThrough = ${destination}`
  ];
}

/**
 * Helper for replaceState.
 * @param {Array.<number>} oldStates
 * @param {number} oldState
 * @param {number} newState
 */
State.replaceStateList = function(oldStates, oldState,  newState) {
  let states = [];
  for (let i = 0; i < oldStates.length; i++) {
    states.push(State.replaceStateId(oldStates[i], oldState, newState));
  }
  return states;
};

/**
 * Helper for replaceState.
 * @param {number} current
 * @param {number} oldState
 * @param {number} newState
 */
State.replaceStateId = function(current, oldState, newState) {
  return current === oldState ? newState : current;
};

/**
 * Helper for replaceState.
 * @param {Array.<TryState>} exceptionBlocks
 * @param {number} oldState
 * @param {number} newState
 * @return {Array.<TryState>}
 */
State.replaceAllStates = function(exceptionBlocks, oldState, newState) {
  let result = [];
  for (let i = 0; i < exceptionBlocks.length; i++) {
    result.push(exceptionBlocks[i].replaceState(oldState, newState));
  }
  return result;
};


text:
/*
 * =====================================================================
 *          Verze:  1.0
 *      Vytvoreno:  04/22/2014 08:22:18 PM
 *          Autor:  Tomáš Coufal
 *          Login:  xcoufa09
 *        Projekt:  IJC - Projekt c. 2 - Priklad 1
 * =====================================================================
 */

/*
 * =====================================================================
 *                     Volna implementace fold v C
 * =====================================================================
 */
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include "io.h"

#define DEFAULT_LENGTH 80
#define WORDBUFFER 4096

struct params {
  bool stdinFile;
  char * fileName;
  long lineLength;
  long maxLength;
  bool cflag;
};

int fold (struct params * forMe);
void printErr(const char * msg);

/*   Main
 * ---------------------------------------------------------------------
 * - zpracovava argumenty vola funkci fold
 */
int main (int argc, char * argv[])
{
  struct params forFold = { true, .lineLength=DEFAULT_LENGTH, WORDBUFFER - 1, false };
  char * end;

  if (argc >= 1 && argc <= 5)
  {
    for (int i = 1; i < argc; i++)
    {
      if (strcmp("-w", argv[i]) == EXIT_SUCCESS && i + 1 < argc) // parametr -w
      {
        forFold.lineLength = strtol(argv[++i], &end, 0);  // dalsi paramet je cislo
        if (*end) { printErr("Number expected after -w."); return EXIT_FAILURE; }
      } else if (strcmp("-c", argv[i]) == EXIT_SUCCESS) // parametr -c
      {
        forFold.cflag = true;
      } else if ( i < argc - 1) // neznamy paramer a neni to parametr posledni
      {
        printErr("Unrecognized option, exiting.");
        return EXIT_FAILURE;
      } else // mam posledni parametr == jmeno souboru
      {
        forFold.fileName = argv[i];
        forFold.stdinFile = false;
      }
    }
  } else
  {
    printErr("Something went wrong. Please use valid syntax.");
    return EXIT_FAILURE;
  }

  return fold(&forFold);
}

/*   Skladani radku
 * ---------------------------------------------------------------------
 * - funkci fgetw z io.h cte slova a postupne je vypisjue na stdout tak,
 * - aby nedoslo k prekroceni zadane delky radku (implic. 80)
 * - respektuje volne radky (jako volne radky povazuji i radky, ktere
 *   obsahuji pouze mezery a jine oddelovace - vizualne jsou prazdne)
 * - v pripade dlouhych slov je zkrati (v pripade prepinace -c) a
 *   vypise na samostatny radek
 */
int fold (struct params * forMe)
{

  FILE * input;
  if (forMe->stdinFile) { input = stdin; }
  else if  ((input = fopen(forMe->fileName, "r")) == NULL) { printErr("Unable to open file"); return EXIT_FAILURE; }

// na zacatku souboru jsou volne radky
  int ch;
  while ((ch = fgetc(input)) != EOF && ch == '\n') {putchar(ch); }
  ungetc(ch, input);

// zpracovani souboru
  char word[WORDBUFFER];
  int wordLength;
  int lineCounter = 0;
  int enterCounter = 0;
  bool err = false;
  while (( wordLength = fgetw(word, forMe->maxLength, input)) != 0)
  {
    enterCounter = 0;
    if (( lineCounter + wordLength) >= forMe->lineLength && lineCounter != 0 ) { putchar('\n'); lineCounter = 0; }
    if (!err && wordLength >= forMe->lineLength) {printErr("Word longer than line!"); err = true;}
    if (lineCounter != 0) { putchar(' '); lineCounter++; }
    if (forMe->cflag) {word[forMe->lineLength] = '\0'; }
    printf("%s", word);
    lineCounter += wordLength;
    while ((ch = fgetc(input)) != EOF && isspace(ch))
    {
      if (ch == '\n') {enterCounter++; }
    }
    ungetc(ch, input);
    if (enterCounter == 1) {continue; }
    while (enterCounter > 0) { putchar('\n'); enterCounter--; lineCounter = 0; }
  }
  putchar('\n');
  fclose(input);
  return EXIT_SUCCESS;
}


text:
ActiveRecord::Schema.define(version: 20140625073732) do

  create_table "body_measurements", force: true do |t|
    t.date     "measurementDate"
    t.integer  "occurrence"
    t.float    "weight"
    t.float    "bodyFat"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "running_measurements", force: true do |t|
    t.float    "distance_miles"
    t.integer  "duration_seconds"
    t.float    "calories"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end


text:
IMPLEMENT_DYNCREATE(CRouterRunner, CWinThread)

CRouterRunner::CRouterRunner()
	:m_pDoc(NULL)
{
}

CRouterRunner::~CRouterRunner()
{
}

BOOL CRouterRunner::InitInstance()
{
	// TODO:    ÔÚ´ËÖ´ÐÐÈÎÒâÖðÏ̳߳õ'»¯
	return TRUE;
}

int CRouterRunner::ExitInstance()
{
	// TODO:    ÔÚ´ËÖ´ÐÐÈÎÒâÖðÏß³ÌÇåÀí
	return CWinThread::ExitInstance();
}

void CRouterRunner::SetDoc(CRouterSimulatorDoc * pDoc)
{
	m_pDoc = pDoc;
}

void CRouterRunner::OnStartDij(WPARAM wParam, LPARAM lParam)
{
	CRoadNet * pNet = m_pDoc->m_pRoadNet;
	pNet->m_pDijTable = new DijTable();
	pNet->m_pDijTable->Init(pNet->m_allDijNodes);

	int nDijCount = pNet->m_allDijNodes.GetSize();
	int nGroupSize = sqrt(nDijCount);
	for (int i = 0; i < nGroupSize; ++i)
	{
		for (int j = i; j < nDijCount; j+=nGroupSize)
		{
			pNet->m_pDijTable->RunDijOn(j);
			POSITION pos = m_pDoc->GetFirstViewPosition();
			while (pos != NULL)
			{
				CView* pView = m_pDoc->GetNextView(pos);
				pView->PostMessage(AFTERONEDIJNODE, j);
			}
		}
	}
	OnCreateHosts(m_pDoc->m_Cfg.m_nNodeCount + SERVER_NODE_COUNT, 10);
	OutputDebugString(_T("\nInit OK!!!"));
	POSITION pos = m_pDoc->GetFirstViewPosition();
	while (pos != NULL)
	{
		CView* pView = m_pDoc->GetNextView(pos);
		pView->PostMessage(MSG_ID_DATA_PREPARE_FINISHED);
	}
}

void CRouterRunner::OnCreateHosts(WPARAM wParam, LPARAM lParam)
{
	int nHostCount = wParam;
	int nTryMax = lParam;
	CreateHosts(nHostCount, nTryMax);
}

void CRouterRunner::CreateSocialRelation()
{

	int nHostCount = m_pDoc->m_pRoadNet->m_allHosts.GetSize();
	double fTrustRateBase = pow((double)nHostCount, (1.0 / 4.0));
	double fTrustInitValue = 0.9;
	for (int i = 0; i < nHostCount; ++i)
	{
		CMobileSocialNetworkHost * pHost = (CMobileSocialNetworkHost*)m_pDoc->m_pRoadNet->m_allHosts.GetAt(i);
		double fTrustValue = fTrustInitValue;
		int nLoopCount = fTrustRateBase + 0.5;
		for (int j = 0; j < nLoopCount; ++j)
		{
			CTrustValue fTrustValueTmp = 0;
			while (true)
			{
				int nSelect = rand() % nHostCount;
				if (pHost->FindTrust(nSelect, fTrustValueTmp))
				{
					continue;
				}
				pHost->AddTrust(nSelect, fTrustValue);
				break;
			}
		}
		fTrustValue *= fTrustInitValue;
		nLoopCount = fTrustRateBase * fTrustRateBase + 0.5;
		for (int j = 0; j < nLoopCount; ++j)
		{
			CTrustValue fTrustValueTmp = 0;
			while (true)
			{
				int nSelect = rand() % nHostCount;
				if (pHost->FindTrust(nSelect, fTrustValueTmp))
				{
					continue;
				}
				pHost->AddTrust(nSelect, fTrustValue);
				break;
			}
		}
		fTrustValue *= fTrustInitValue;
		nLoopCount = fTrustRateBase * fTrustRateBase * fTrustRateBase + 0.5;
		for (int j = 0; j < nLoopCount; ++j)
		{
			CTrustValue fTrustValueTmp = 0;
			while (true)
			{
				int nSelect = rand() % nHostCount;
				if (pHost->FindTrust(nSelect, fTrustValueTmp))
				{
					continue;
				}
				pHost->AddTrust(nSelect, fTrustValue);
				break;
			}
		}
	}
}

void CRouterRunner::CreateSocialEvenRelation()
{
	int nHostCount = m_pDoc->m_pRoadNet->m_allHosts.GetSize();
	for (int i = SERVER_NODE_COUNT; i < nHostCount; ++i)
	{
		CMobileSocialNetworkHost * pHost = (CMobileSocialNetworkHost*)m_pDoc->m_pRoadNet->m_allHosts.GetAt(i);
		for (int j = SERVER_NODE_COUNT; j < nHostCount; ++j)
		{
			int nRand = rand() % 101;
			if (nRand < DEFAULT_LOW_TRUST_VALUE)
			{
				continue;
			}
			pHost->AddTrust(j, nRand / 100.0);
		}
	}
}

void CRouterRunner::CreateHosts(int nHostCount, int nTryMax)
{
	m_pDoc->m_pRoadNet->m_allHosts.RemoveAll();
	CreateHostsWithFixedZero();
	unsigned int nSeed = time(NULL);
	CString strRand;
	strRand.Format(_T("\nRand (%d)"), nSeed);
	OutputDebugString(strRand);
	//srand(time(NULL));
	int nCreatedCount = 1;
	int nA, nB;
	int nPointCount = m_pDoc->m_pRoadNet->m_allPoints.GetSize();
	CHost * pHost = NULL;
	while (nCreatedCount < nHostCount)
	{
#if 0
		pHost = new CHost();
#else
		pHost = new CMobileSocialNetworkHost();
#endif
		if (nCreatedCount < nHostCount * 3 / 5 + 1)
		{
			pHost->SetSpeed(GenerateRandomSpeed(HOST_SPEED_PEDESTRIANS_MIN, HOST_SPEED_PEDESTRIANS_MAX));
		}
		else
		{
			pHost->SetSpeed(GenerateRandomSpeed(HOST_SPEED_CAR_MIN, HOST_SPEED_CAR_MAX));
		}
		int nTryTimes = 0;
		CHostRouteTable schedule1;
		while (!schedule1.IsScheduleAvailable())
		{
			++nTryTimes;
			if (nTryTimes > nTryMax)
			{
				return;
			}
			nA = rand() % nPointCount;
			nB = rand() % nPointCount;
			m_pDoc->m_pRoadNet->RouteTwoRoadPoints(*pHost, m_pDoc->m_pRoadNet->m_allPoints[nA], m_pDoc->m_pRoadNet->m_allPoints[nB], schedule1);
		}
		pHost->m_schedule = schedule1;

		nTryTimes = 0;
		CHostRouteTable schedule2;
		while (!schedule2.IsScheduleAvailable())
		{
			++nTryTimes;
			if (nTryTimes > nTryMax)
			{
				return;
			}
			nA = rand() % nPointCount;
			m_pDoc->m_pRoadNet->RouteTwoRoadPoints(*pHost, m_pDoc->m_pRoadNet->m_allPoints[nB], m_pDoc->m_pRoadNet->m_allPoints[nA], schedule2);
		}
		schedule2.m_fStartSecond = 15;
		pHost->m_schedule += schedule2;

		pHost->m_nId = nCreatedCount;
		m_pDoc->m_pRoadNet->m_allHosts.Add(pHost);
		++nCreatedCount;
	}
	if (nHostCount > 10000)
	{
		ASSERT(0);
	}
	else
	{
		CreateSocialEvenRelation();
	}
}

void CRouterRunner::CreateHostsWithFixedZero()
{
	int nPointCount = m_pDoc->m_pRoadNet->m_allInterSections.GetSize();
	CHost * pHost = new CMobileSocialNetworkHost();
	pHost->m_nId = 0;

	CDoublePoint mapcenter;
	m_pDoc->m_pRoadNet->GetMapCenter(mapcenter);

	int nTryTimes = 0;
	double fDistance = DBL_MAX;
	CHostRouteEntry zeroEntry;
	zeroEntry.m_lnSimTime = 0;
	for (int i = 0; i < 20; ++i)
	{
		int nZero = rand() % nPointCount;
		CDoublePoint zeroPoint = *m_pDoc->m_pRoadNet->m_allInterSections[nZero]->m_pPoint;
		double fDistanceTmp = CDoublePoint::GetDistance(zeroPoint, mapcenter);
		if (fDistanceTmp < fDistance)
		{
			fDistance = fDistanceTmp;
			zeroEntry.m_Position = zeroPoint;
		}
	}
	pHost->m_schedule.m_Entries.Add(zeroEntry);
	m_pDoc->m_pRoadNet->m_allHosts.Add(pHost);
}

double CRouterRunner::GenerateRandomSpeed(double fMin, double fMax)
{
	int range = (fMax - fMin) * 10;
	double speedincrease = rand() % range;
	double fRet = fMin + speedincrease / 10.0;
	return fRet;
}

BEGIN_MESSAGE_MAP(CRouterRunner, CWinThread)
	ON_THREAD_MESSAGE(MSG_ID_START_DIJ, OnStartDij)
	ON_THREAD_MESSAGE(MSG_ID_SET_HOSTS, OnCreateHosts)
END_MESSAGE_MAP()

// CRouterRunner ÏûÏ¢´¦Àí³ÌÐò


text:
package com.codebroker.redis.collections.builder.ranking;

import com.codebroker.redis.collections.Ranking;

public class RankingLong implements Ranking<Long> {

    private String name;

    private Long point;

    public RankingLong(String key, Long point) {
        this.name = key;
        this.point = point;
    }

    @Override
    public Long getPoints() {
        return point;
    }

    @Override
    public String getName() {
        return name;
    }

}


text:
{
  const EnergenieCore = require('./EnergenieCore');

  /** @type {Enum} Socket Actions */
  const SOCKET_ACTIONS = {
    SET_SOCK_STATE: { PATH: '/energenie.html', METHOD: 'POST' },
    GET_SOCKS: { PATH: '/status.html', METHOD: 'GET' }
  };
  /** EnergenieCore Class */
  let energenieCore;
  /** Power strip name */
  let name = '';
  /** Information about sockets on Energenie power strip. */
  let sockets = {};
  /** Options: host, password & port */
  let options = {};
  /** Class context */
  let that;

  /**
   * Converting JSON path to JS-Array
   *
   * @param {JSON} json json to convert to array.
   * @return {Array} json as array.
   */
  function json2array(json){
    var arr = [];
    var jKeys = Object.keys(json);
    for (let jCnt = 0; jCnt < jKeys.length; jCnt++)
      arr.push(json[jKeys[jCnt]]);

    return arr;
  }

  /**
   * Grabbing power strip name from header in body tag.
   *
   * @param {String} bodyData (.*)
   */
  function grabPowerStripName(bodyData) {
    let regexStripName = /

(.*?)<\/h2><\/div>/;
    let regexStripNameContent = regexStripName.exec(bodyData);
    if (regexStripNameContent != null)
      name = regexStripNameContent[1].trim();
  }

  /**
   * Grabbing names of sockets of power strip.
   *
   * @param {String} scriptData
   */
  function grabSockNames(scriptData) {
    let regexSockName = /var sock_names = \[(.*?)\];/;
    let sockNameContent = regexSockName.exec(scriptData);
    let sockNames = null;

    if (sockNameContent === null) {
      console.error(new Error('SOCKET_NAME_ARRAY_NOT_FOUND'));
      return null;
    }

    /** Adding found sock names */
    sockNames = sockNameContent[1].split(',');
    for (let i = 0; i < sockNames.length; i++) {
      let sockName = sockNames[i].trim();
      let key = 'cte' + (i+1);
      if (!sockets[key]) sockets[key] = {};
      sockets[key]['name'] =
        sockName.substr(1, sockName.length - 2).trim();
    }
  }

  /**
   * Grabbing states of sockets of power strip.
   *
   * @param {String} scriptData
   */
  function grabSockStates(scriptData) {
    let regexSock = /var ctl = \[(.*?)\];/;
    let sockContent = regexSock.exec(scriptData);
    if (sockContent === null) {
      console.error(new Error('SOCKET_ARRAY_NOT_FOUND'));
      return null;
    }

    /** Adding found key & state */
    let sockStates = sockContent[1].split(',');
    for (let i = 0; i < sockStates.length; i++) {
      let key = 'cte' + (i+1);
      if (!sockets[key]) sockets[key] = {};
      sockets[key]['key'] = 'cte' + (i+1);
      sockets[key]['state'] = (sockStates[i] === '1') ? true : false;
    }
  }

  /**
   * Energenie Magic Class.
   *
   * @author Michael Kolodziejczyk
   */
  class EnergeniePowerStrip {

    constructor(options_) {
      options = options_;
      energenieCore = new EnergenieCore(options);
      that = this;
    }

    /**
     * Setting sock state of Energenie plug stripe by using id and state.
     *
     * @param {String} id ID of the socket.
     * @param {boolean} state Future state of the socket.
     * @return {Promise} {boolean} Was changing the socket state, okay?
     */
    setSocketState(id, state) {
      return new Promise((resolve, reject) => {
        that.getSockets().then(() => {
          if (sockets[id]) {
            state = (state == true || state == '1') ? '1' : '0';
            let postscriptData = id  + '=' + state;
            energenieCore.sendPostRequest(
              SOCKET_ACTIONS.SET_SOCK_STATE, postscriptData)
              .then((val) => {
                console.info('Updating ' + id + ' to ' + state + ' finished.');
                resolve(true);
              }).catch((err) => {
                console.error('Updating ' + id + ' to ' + state + ' failed.');
                reject(new Error(err));
              });
          }
        });
      });
    }

    /**
     * Getting sock states. Reading response and searching via regex
     * inside the -tag for the states and the names
     * array.
     *
     * @return {Promise} Sockets of power strip.
     */
    getSockets() {
      return new Promise((resolve, reject) => {
        energenieCore.sendPostRequest(SOCKET_ACTIONS.GET_SOCKS, '')
          .then(function(res) {
            /** Script data of index.html */
            let scriptData = res.substring(
              res.indexOf(''));
            /** Body data of index.html */
            let bodyData = res.substring(
              res.indexOf('') + 6, res.indexOf('')
            );

            /* Grabbing information from request */
            grabSockStates(scriptData);
            grabSockNames(scriptData);
            grabPowerStripName(bodyData);

            let socks = {
              host: options.host,
              name: name,
              sockets: json2array(sockets)
            };

            resolve(socks);
          }).catch(function(err) {
            console.error('Getting Sockets failed...');
            console.error(err);
            reject(new Error(err));
          });
      });
    }
  }

  module.exports = EnergeniePowerStrip;
}


text:
struct Homura;

fn akemi(homura: Homura) {
    let Some(ref madoka) = Some(homura.kaname()); //~ ERROR no method named `kaname` found
    madoka.clone();
}

fn main() { }


text:
from config import *

from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker

engine = create_engine(SQLALCHEMY_DATABASE_URI)

def create_session():
    """ Create a scoped session -

    the scoped_session() function is provided which produces a thread-managed registry of Session objects.
    It is commonly used in web applications so that a single global variable can be used to safely
    represent transactional sessions with sets of objects, localized to a single thread.

    """
    session = scoped_session(sessionmaker())
    session.configure(bind=engine, autoflush=False, expire_on_commit=False, autocommit=False)
    return session

db = SQLAlchemy()

def query_to_list(query, include_field_names=True):
    """Turns a SQLAlchemy query into a list of data values."""
    column_names = []
    for i, obj in enumerate(query.all()):
        if i == 0:
            column_names = [c.name for c in obj.__table__.columns]
            if include_field_names:
                yield column_names
        yield obj_to_list(obj, column_names)

def obj_to_list(sa_obj, field_order):
    """Takes a SQLAlchemy object - returns a list of all its data"""
    return [getattr(sa_obj, field_name, None) for field_name in field_order]


text:
package net.groupbuy.controller.admin;

import java.util.HashSet;

import javax.annotation.Resource;

import net.groupbuy.Message;
import net.groupbuy.Pageable;
import net.groupbuy.entity.Admin;
import net.groupbuy.entity.Role;
import net.groupbuy.entity.BaseEntity.Save;
import net.groupbuy.service.AdminService;
import net.groupbuy.service.RoleService;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * Controller - 管理员
 *
 * @author SHOP++ Team
 * @version 3.0
 */
@Controller("adminAdminController")
@RequestMapping("/admin/admin")
public class AdminController extends BaseController {

	@Resource(name = "adminServiceImpl")
	private AdminService adminService;
	@Resource(name = "roleServiceImpl")
	private RoleService roleService;

	/**
	 * 检查用户名是否存在
	 */
	@RequestMapping(value = "/check_username", method = RequestMethod.GET)
	public @ResponseBody
	boolean checkUsername(String username) {
		if (StringUtils.isEmpty(username)) {
			return false;
		}
		if (adminService.usernameExists(username)) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 添加
	 */
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(ModelMap model) {
		model.addAttribute("roles", roleService.findAll());
		return "/admin/admin/add";
	}

	/**
	 * 保存
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String save(Admin admin, Long[] roleIds, RedirectAttributes redirectAttributes) {
		admin.setRoles(new HashSet<Role>(roleService.findList(roleIds)));
		if (!isValid(admin, Save.class)) {
			return ERROR_VIEW;
		}
		if (adminService.usernameExists(admin.getUsername())) {
			return ERROR_VIEW;
		}
		admin.setPassword(DigestUtils.md5Hex(admin.getPassword()));
		admin.setIsLocked(false);
		admin.setLoginFailureCount(0);
		admin.setLockedDate(null);
		admin.setLoginDate(null);
		admin.setLoginIp(null);
		admin.setOrders(null);
		adminService.save(admin);
		addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
		return "redirect:list.jhtml";
	}

	/**
	 * 编辑
	 */
	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	public String edit(Long id, ModelMap model) {
		model.addAttribute("roles", roleService.findAll());
		model.addAttribute("admin", adminService.find(id));
		return "/admin/admin/edit";
	}

	/**
	 * 更新
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String update(Admin admin, Long[] roleIds, RedirectAttributes redirectAttributes) {
		admin.setRoles(new HashSet<Role>(roleService.findList(roleIds)));
		if (!isValid(admin)) {
			return ERROR_VIEW;
		}
		Admin pAdmin = adminService.find(admin.getId());
		if (pAdmin == null) {
			return ERROR_VIEW;
		}
		if (StringUtils.isNotEmpty(admin.getPassword())) {
			admin.setPassword(DigestUtils.md5Hex(admin.getPassword()));
		} else {
			admin.setPassword(pAdmin.getPassword());
		}
		if (pAdmin.getIsLocked() && !admin.getIsLocked()) {
			admin.setLoginFailureCount(0);
			admin.setLockedDate(null);
		} else {
			admin.setIsLocked(pAdmin.getIsLocked());
			admin.setLoginFailureCount(pAdmin.getLoginFailureCount());
			admin.setLockedDate(pAdmin.getLockedDate());
		}
		adminService.update(admin, "username", "loginDate", "loginIp", "orders");
		addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
		return "redirect:list.jhtml";
	}

	/**
	 * 列表
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Pageable pageable, ModelMap model) {
		model.addAttribute("page", adminService.findPage(pageable));
		return "/admin/admin/list";
	}

	/**
	 * 删除
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public @ResponseBody
	Message delete(Long[] ids) {
		if (ids.length >= adminService.count()) {
			return Message.error("admin.common.deleteAllNotAllowed");
		}
		adminService.delete(ids);
		return SUCCESS_MESSAGE;
	}

}


text:
<Module>
	<Texture>BombBayNuclear_2x2</Texture>
	<SizeX>2</SizeX>
	<SizeY>2</SizeY>

	<ProductionCost>4</ProductionCost>
	<AlloyCost>8</AlloyCost>
	<CrystalCost>4</CrystalCost>

	<Health>220</Health>
	<Mass>4</Mass>
	<Power>8</Power>
	<RequiredCrew>6</RequiredCrew>

	<BombArmyDamage>6</BombArmyDamage>
	<BombStructureDamage>6</BombStructureDamage>
	<BombPopulationDamage>6</BombPopulationDamage>
	<BombPollution>16</BombPollution>
</Module>


text:
package host

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"runtime"
	"strconv"
	"strings"
	"sync/atomic"
	"time"

	"github.com/shirou/gopsutil/internal/common"
)

type LSB struct {
	ID          string
	Release     string
	Codename    string
	Description string
}

// from utmp.h
const USER_PROCESS = 7

func Info() (*InfoStat, error) {
	ret := &InfoStat{
		OS: runtime.GOOS,
	}

	hostname, err := os.Hostname()
	if err == nil {
		ret.Hostname = hostname
	}

	platform, family, version, err := PlatformInformation()
	if err == nil {
		ret.Platform = platform
		ret.PlatformFamily = family
		ret.PlatformVersion = version
	}
	kernelVersion, err := KernelVersion()
	if err == nil {
		ret.KernelVersion = kernelVersion
	}

	system, role, err := Virtualization()
	if err == nil {
		ret.VirtualizationSystem = system
		ret.VirtualizationRole = role
	}

	boot, err := BootTime()
	if err == nil {
		ret.BootTime = boot
		ret.Uptime = uptime(boot)
	}

	if numProcs, err := common.NumProcs(); err == nil {
		ret.Procs = numProcs
	}

	sysProductUUID := common.HostSys("class/dmi/id/product_uuid")
	switch {
	case common.PathExists(sysProductUUID):
		lines, err := common.ReadLines(sysProductUUID)
		if err == nil && len(lines) > 0 && lines[0] != "" {
			ret.HostID = strings.ToLower(lines[0])
			break
		}
		fallthrough
	default:
		values, err := common.DoSysctrl("kernel.random.boot_id")
		if err == nil && len(values) == 1 && values[0] != "" {
			ret.HostID = strings.ToLower(values[0])
		}
	}

	return ret, nil
}

// cachedBootTime must be accessed via atomic.Load/StoreUint64
var cachedBootTime uint64

// BootTime returns the system boot time expressed in seconds since the epoch.
func BootTime() (uint64, error) {
	t := atomic.LoadUint64(&cachedBootTime)
	if t != 0 {
		return t, nil
	}
	filename := common.HostProc("stat")
	lines, err := common.ReadLines(filename)
	if err != nil {
		return 0, err
	}
	for _, line := range lines {
		if strings.HasPrefix(line, "btime") {
			f := strings.Fields(line)
			if len(f) != 2 {
				return 0, fmt.Errorf("wrong btime format")
			}
			b, err := strconv.ParseInt(f[1], 10, 64)
			if err != nil {
				return 0, err
			}
			t = uint64(b)
			atomic.StoreUint64(&cachedBootTime, t)
			return t, nil
		}
	}

	return 0, fmt.Errorf("could not find btime")
}

func uptime(boot uint64) uint64 {
	return uint64(time.Now().Unix()) - boot
}

func Uptime() (uint64, error) {
	boot, err := BootTime()
	if err != nil {
		return 0, err
	}
	return uptime(boot), nil
}

func Users() ([]UserStat, error) {
	utmpfile := "/var/run/utmp"

	file, err := os.Open(utmpfile)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	buf, err := ioutil.ReadAll(file)
	if err != nil {
		return nil, err
	}

	count := len(buf) / sizeOfUtmp

	ret := make([]UserStat, 0, count)

	for i := 0; i < count; i++ {
		b := buf[i*sizeOfUtmp : (i+1)*sizeOfUtmp]

		var u utmp
		br := bytes.NewReader(b)
		err := binary.Read(br, binary.LittleEndian, &u)
		if err != nil {
			continue
		}
		if u.Type != USER_PROCESS {
			continue
		}
		user := UserStat{
			User:     common.IntToString(u.User[:]),
			Terminal: common.IntToString(u.Line[:]),
			Host:     common.IntToString(u.Host[:]),
			Started:  int(u.Tv.Sec),
		}
		ret = append(ret, user)
	}

	return ret, nil

}

func getOSRelease() (platform string, version string, err error) {
	contents, err := common.ReadLines(common.HostEtc("os-release"))
	if err != nil {
		return "", "", nil // return empty
	}
	for _, line := range contents {
		field := strings.Split(line, "=")
		if len(field) < 2 {
			continue
		}
		switch field[0] {
		case "ID": // use ID for lowercase
			platform = field[1]
		case "VERSION":
			version = field[1]
		}
	}
	return platform, version, nil
}

func getLSB() (*LSB, error) {
	ret := &LSB{}
	if common.PathExists(common.HostEtc("lsb-release")) {
		contents, err := common.ReadLines(common.HostEtc("lsb-release"))
		if err != nil {
			return ret, err // return empty
		}
		for _, line := range contents {
			field := strings.Split(line, "=")
			if len(field) < 2 {
				continue
			}
			switch field[0] {
			case "DISTRIB_ID":
				ret.ID = field[1]
			case "DISTRIB_RELEASE":
				ret.Release = field[1]
			case "DISTRIB_CODENAME":
				ret.Codename = field[1]
			case "DISTRIB_DESCRIPTION":
				ret.Description = field[1]
			}
		}
	} else if common.PathExists("/usr/bin/lsb_release") {
		lsb_release, err := exec.LookPath("/usr/bin/lsb_release")
		if err != nil {
			return ret, err
		}
		out, err := invoke.Command(lsb_release)
		if err != nil {
			return ret, err
		}
		for _, line := range strings.Split(string(out), "\n") {
			field := strings.Split(line, ":")
			if len(field) < 2 {
				continue
			}
			switch field[0] {
			case "Distributor ID":
				ret.ID = field[1]
			case "Release":
				ret.Release = field[1]
			case "Codename":
				ret.Codename = field[1]
			case "Description":
				ret.Description = field[1]
			}
		}

	}

	return ret, nil
}

func PlatformInformation() (platform string, family string, version string, err error) {

	lsb, err := getLSB()
	if err != nil {
		lsb = &LSB{}
	}

	if common.PathExists(common.HostEtc("oracle-release")) {
		platform = "oracle"
		contents, err := common.ReadLines(common.HostEtc("oracle-release"))
		if err == nil {
			version = getRedhatishVersion(contents)
		}

	} else if common.PathExists(common.HostEtc("enterprise-release")) {
		platform = "oracle"
		contents, err := common.ReadLines(common.HostEtc("enterprise-release"))
		if err == nil {
			version = getRedhatishVersion(contents)
		}
	} else if common.PathExists(common.HostEtc("debian_version")) {
		if lsb.ID == "Ubuntu" {
			platform = "ubuntu"
			version = lsb.Release
		} else if lsb.ID == "LinuxMint" {
			platform = "linuxmint"
			version = lsb.Release
		} else {
			if common.PathExists("/usr/bin/raspi-config") {
				platform = "raspbian"
			} else {
				platform = "debian"
			}
			contents, err := common.ReadLines(common.HostEtc("debian_version"))
			if err == nil {
				version = contents[0]
			}
		}
	} else if common.PathExists(common.HostEtc("redhat-release")) {
		contents, err := common.ReadLines(common.HostEtc("redhat-release"))
		if err == nil {
			version = getRedhatishVersion(contents)
			platform = getRedhatishPlatform(contents)
		}
	} else if common.PathExists(common.HostEtc("system-release")) {
		contents, err := common.ReadLines(common.HostEtc("system-release"))
		if err == nil {
			version = getRedhatishVersion(contents)
			platform = getRedhatishPlatform(contents)
		}
	} else if common.PathExists(common.HostEtc("gentoo-release")) {
		platform = "gentoo"
		contents, err := common.ReadLines(common.HostEtc("gentoo-release"))
		if err == nil {
			version = getRedhatishVersion(contents)
		}
	} else if common.PathExists(common.HostEtc("SuSE-release")) {
		contents, err := common.ReadLines(common.HostEtc("SuSE-release"))
		if err == nil {
			version = getSuseVersion(contents)
			platform = getSusePlatform(contents)
		}
		// TODO: slackware detecion
	} else if common.PathExists(common.HostEtc("arch-release")) {
		platform = "arch"
		version = lsb.Release
	} else if common.PathExists(common.HostEtc("alpine-release")) {
		platform = "alpine"
		contents, err := common.ReadLines(common.HostEtc("alpine-release"))
		if err == nil && len(contents) > 0 {
			version = contents[0]
		}
	} else if common.PathExists(common.HostEtc("os-release")) {
		p, v, err := getOSRelease()
		if err == nil {
			platform = p
			version = v
		}
	} else if lsb.ID == "RedHat" {
		platform = "redhat"
		version = lsb.Release
	} else if lsb.ID == "Amazon" {
		platform = "amazon"
		version = lsb.Release
	} else if lsb.ID == "ScientificSL" {
		platform = "scientific"
		version = lsb.Release
	} else if lsb.ID == "XenServer" {
		platform = "xenserver"
		version = lsb.Release
	} else if lsb.ID != "" {
		platform = strings.ToLower(lsb.ID)
		version = lsb.Release
	}

	switch platform {
	case "debian", "ubuntu", "linuxmint", "raspbian":
		family = "debian"
	case "fedora":
		family = "fedora"
	case "oracle", "centos", "redhat", "scientific", "enterpriseenterprise", "amazon", "xenserver", "cloudlinux", "ibm_powerkvm":
		family = "rhel"
	case "suse", "opensuse":
		family = "suse"
	case "gentoo":
		family = "gentoo"
	case "slackware":
		family = "slackware"
	case "arch":
		family = "arch"
	case "exherbo":
		family = "exherbo"
	case "alpine":
		family = "alpine"
	case "coreos":
		family = "coreos"
	}

	return platform, family, version, nil

}

func KernelVersion() (version string, err error) {
	filename := common.HostProc("sys/kernel/osrelease")
	if common.PathExists(filename) {
		contents, err := common.ReadLines(filename)
		if err != nil {
			return "", err
		}

		if len(contents) > 0 {
			version = contents[0]
		}
	}

	return version, nil
}

func getRedhatishVersion(contents []string) string {
	c := strings.ToLower(strings.Join(contents, ""))

	if strings.Contains(c, "rawhide") {
		return "rawhide"
	}
	if matches := regexp.MustCompile(`release (\d[\d.]*)`).FindStringSubmatch(c); matches != nil {
		return matches[1]
	}
	return ""
}

func getRedhatishPlatform(contents []string) string {
	c := strings.ToLower(strings.Join(contents, ""))

	if strings.Contains(c, "red hat") {
		return "redhat"
	}
	f := strings.Split(c, " ")

	return f[0]
}

func getSuseVersion(contents []string) string {
	version := ""
	for _, line := range contents {
		if matches := regexp.MustCompile(`VERSION = ([\d.]+)`).FindStringSubmatch(line); matches != nil {
			version = matches[1]
		} else if matches := regexp.MustCompile(`PATCHLEVEL = ([\d]+)`).FindStringSubmatch(line); matches != nil {
			version = version + "." + matches[1]
		}
	}
	return version
}

func getSusePlatform(contents []string) string {
	c := strings.ToLower(strings.Join(contents, ""))
	if strings.Contains(c, "opensuse") {
		return "opensuse"
	}
	return "suse"
}

func Virtualization() (string, string, error) {
	var system string
	var role string

	filename := common.HostProc("xen")
	if common.PathExists(filename) {
		system = "xen"
		role = "guest" // assume guest

		if common.PathExists(filepath.Join(filename, "capabilities")) {
			contents, err := common.ReadLines(filepath.Join(filename, "capabilities"))
			if err == nil {
				if common.StringsContains(contents, "control_d") {
					role = "host"
				}
			}
		}
	}

	filename = common.HostProc("modules")
	if common.PathExists(filename) {
		contents, err := common.ReadLines(filename)
		if err == nil {
			if common.StringsContains(contents, "kvm") {
				system = "kvm"
				role = "host"
			} else if common.StringsContains(contents, "vboxdrv") {
				system = "vbox"
				role = "host"
			} else if common.StringsContains(contents, "vboxguest") {
				system = "vbox"
				role = "guest"
			} else if common.StringsContains(contents, "vmware") {
				system = "vmware"
				role = "guest"
			}
		}
	}

	filename = common.HostProc("cpuinfo")
	if common.PathExists(filename) {
		contents, err := common.ReadLines(filename)
		if err == nil {
			if common.StringsContains(contents, "QEMU Virtual CPU") ||
				common.StringsContains(contents, "Common KVM processor") ||
				common.StringsContains(contents, "Common 32-bit KVM processor") {
				system = "kvm"
				role = "guest"
			}
		}
	}

	filename = common.HostProc()
	if common.PathExists(filepath.Join(filename, "bc", "0")) {
		system = "openvz"
		role = "host"
	} else if common.PathExists(filepath.Join(filename, "vz")) {
		system = "openvz"
		role = "guest"
	}

	// not use dmidecode because it requires root
	if common.PathExists(filepath.Join(filename, "self", "status")) {
		contents, err := common.ReadLines(filepath.Join(filename, "self", "status"))
		if err == nil {

			if common.StringsContains(contents, "s_context:") ||
				common.StringsContains(contents, "VxID:") {
				system = "linux-vserver"
			}
			// TODO: guest or host
		}
	}

	if common.PathExists(filepath.Join(filename, "self", "cgroup")) {
		contents, err := common.ReadLines(filepath.Join(filename, "self", "cgroup"))
		if err == nil {
			if common.StringsContains(contents, "lxc") {
				system = "lxc"
				role = "guest"
			} else if common.StringsContains(contents, "docker") {
				system = "docker"
				role = "guest"
			} else if common.StringsContains(contents, "machine-rkt") {
				system = "rkt"
				role = "guest"
			} else if common.PathExists("/usr/bin/lxc-version") {
				system = "lxc"
				role = "host"
			}
		}
	}

	if common.PathExists(common.HostEtc("os-release")) {
		p, _, err := getOSRelease()
		if err == nil && p == "coreos" {
			system = "rkt" // Is it true?
			role = "host"
		}
	}
	return system, role, nil
}

func SensorsTemperatures() ([]TemperatureStat, error) {
	var temperatures []TemperatureStat
	files, err := filepath.Glob(common.HostSys("/class/hwmon/hwmon*/temp*_*"))
	if err != nil {
		return temperatures, err
	}
	if len(files) == 0 {
		// CentOS has an intermediate /device directory:
		// https://github.com/giampaolo/psutil/issues/971
		files, err = filepath.Glob(common.HostSys("/class/hwmon/hwmon*/temp*_*"))
		if err != nil {
			return temperatures, err
		}
	}

	for _, match := range files {
		match = strings.Split(match, "_")[0]
		name, err := ioutil.ReadFile(filepath.Join(filepath.Dir(match), "name"))
		if err != nil {
			return temperatures, err
		}
		current, err := ioutil.ReadFile(match + "_input")
		if err != nil {
			return temperatures, err
		}
		temperature, err := strconv.ParseFloat(string(current), 64)
		if err != nil {
			continue
		}
		temperatures = append(temperatures, TemperatureStat{
			SensorKey:   string(name),
			Temperature: temperature / 1000.0,
		})
	}
	return temperatures, nil
}


text:
import sys
import os
import argparse
import json
from bounding_box import BoundingBox

# common functions

def load_tiles(tiles_spec_fname, bbox):
    relevant_tiles = []
    with open(tiles_spec_fname, 'r') as data_file:
        data = json.load(data_file)
    for tile in data:
        tile_bbox = BoundingBox.fromList(tile['bbox'])
        if bbox.overlap(tile_bbox):
            relevant_tiles.append(tile)
    return relevant_tiles

def filter_tiles(tiles_fname, out_fname, bbox):
    # parse the bounding box arguments
    bbox = BoundingBox.fromStr(bbox)

    # load all tiles from the tile-spec json file that are relevant to our bounding box
    relevant_tiles = load_tiles(tiles_fname, bbox)

    # Create a tile-spec file that includes all relevant tiles
    with open(out_fname, 'w') as outfile:
        json.dump(relevant_tiles, outfile, sort_keys=True, indent=4)

def main():
    # Command line parser
    parser = argparse.ArgumentParser(description='Takes a json file that contains many tiles with their bounding boxes (Tile-Spec format)\
        and a bounding box, and outputs a json file for each tile that is overlapping with the bounding box')
    parser.add_argument('tiles_fname', metavar='tiles_json', type=str,
                        help='a tile_spec file that contains all the images to be aligned in json format')
    parser.add_argument('-o', '--output_file', type=str,
                        help='an output tile_spec file, that will include only the relevant tiles (default: ./filtered.json)',
                        default='./filtered.json')
    # the default bounding box is as big as the image can be
    parser.add_argument('-b', '--bounding_box', type=str,
                        help='the bounding box of the part of image that needs to be aligned format: "from_x to_x from_y to_y" (default: all tiles)',
                        default='{0} {1} {2} {3}'.format((-sys.maxint - 1), sys.maxint, (-sys.maxint - 1), sys.maxint))

    args = parser.parse_args()

    #print args

    filter_tiles(args.tiles_fname, args.output_file, args.bounding_box)

if __name__ == '__main__':
    main()


text:
<?php
namespace Pimenta\Domain;

final class AggregateHistory extends DomainEvents
{
    /**
     * @var IdentifiesAggregate
     */
    private $aggregateId;

    public function __construct(IdentifiesAggregate $aggregateId, array $events)
    {
        /** @var $event DomainEvent */
        foreach ($events as $event) {
            if (!$event->getAggregateId()->equals($aggregateId)) {
                throw new CorruptAggregateHistory();
            }
        }
        parent::__construct($events);
        $this->aggregateId = $aggregateId;
    }

    /**
     * @return IdentifiesAggregate
     */
    public function getAggregateId()
    {
        return $this->aggregateId;
    }

    /**
     * @param  DomainEvent      $domainEvent
     * @return AggregateHistory
     */
    public function append(DomainEvent $domainEvent)
    {
        throw new \Exception("@todo  Implement append() method.");
    }
}