text:
package org.deeplearning4j.ui.model.stats.impl;

import lombok.Data;

import org.agrona.DirectBuffer;
import org.agrona.MutableDirectBuffer;
import org.agrona.concurrent.UnsafeBuffer;
import org.apache.commons.io.IOUtils;
import org.deeplearning4j.ui.model.stats.api.StatsInitializationReport;
import org.deeplearning4j.ui.model.stats.sbe.*;
import org.deeplearning4j.ui.model.storage.AgronaPersistable;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;

@Data
public class SbeStatsInitializationReport implements StatsInitializationReport, AgronaPersistable {

    private String sessionID;
    private String typeID;
    private String workerID;
    private long timeStamp;

    private boolean hasSoftwareInfo;
    private boolean hasHardwareInfo;
    private boolean hasModelInfo;

    private String swArch;
    private String swOsName;
    private String swJvmName;
    private String swJvmVersion;
    private String swJvmSpecVersion;
    private String swNd4jBackendClass;
    private String swNd4jDataTypeName;
    private String swHostName;
    private String swJvmUID;
    private Map<String, String> swEnvironmentInfo;

    private int hwJvmAvailableProcessors;
    private int hwNumDevices;
    private long hwJvmMaxMemory;
    private long hwOffHeapMaxMemory;
    private long[] hwDeviceTotalMemory;
    private String[] hwDeviceDescription;
    private String hwHardwareUID;

    private String modelClassName;
    private String modelConfigJson;
    private String[] modelParamNames;
    private int modelNumLayers;
    private long modelNumParams;

    @Override
    public void reportIDs(String sessionID, String typeID, String workerID, long timeStamp) {
        this.sessionID = sessionID;
        this.typeID = typeID;
        this.workerID = workerID;
        this.timeStamp = timeStamp;
    }

    @Override
    public void reportSoftwareInfo(String arch, String osName, String jvmName, String jvmVersion, String jvmSpecVersion,
                    String nd4jBackendClass, String nd4jDataTypeName, String hostname, String jvmUid,
                    Map<String, String> swEnvironmentInfo) {
        this.swArch = arch;
        this.swOsName = osName;
        this.swJvmName = jvmName;
        this.swJvmVersion = jvmVersion;
        this.swJvmSpecVersion = jvmSpecVersion;
        this.swNd4jBackendClass = nd4jBackendClass;
        this.swNd4jDataTypeName = nd4jDataTypeName;
        this.swHostName = hostname;
        this.swJvmUID = jvmUid;
        this.swEnvironmentInfo = swEnvironmentInfo;
        hasSoftwareInfo = true;
    }

    @Override
    public void reportHardwareInfo(int jvmAvailableProcessors, int numDevices, long jvmMaxMemory, long offHeapMaxMemory,
                    long[] deviceTotalMemory, String[] deviceDescription, String hardwareUID) {
        this.hwJvmAvailableProcessors = jvmAvailableProcessors;
        this.hwNumDevices = numDevices;
        this.hwJvmMaxMemory = jvmMaxMemory;
        this.hwOffHeapMaxMemory = offHeapMaxMemory;
        this.hwDeviceTotalMemory = deviceTotalMemory;
        this.hwDeviceDescription = deviceDescription;
        this.hwHardwareUID = hardwareUID;
        hasHardwareInfo = true;
    }

    @Override
    public void reportModelInfo(String modelClassName, String modelConfigJson, String[] modelParamNames, int numLayers,
                    long numParams) {
        this.modelClassName = modelClassName;
        this.modelConfigJson = modelConfigJson;
        this.modelParamNames = modelParamNames;
        this.modelNumLayers = numLayers;
        this.modelNumParams = numParams;
        hasModelInfo = true;
    }

    @Override
    public boolean hasSoftwareInfo() {
        return hasSoftwareInfo;
    }

    @Override
    public boolean hasHardwareInfo() {
        return hasHardwareInfo;
    }

    @Override
    public boolean hasModelInfo() {
        return hasModelInfo;
    }

    private void clearHwFields() {
        hwDeviceTotalMemory = null;
        hwDeviceDescription = null;
        hwHardwareUID = null;
    }

    private void clearSwFields() {
        swArch = null;
        swOsName = null;
        swJvmName = null;
        swJvmVersion = null;
        swJvmSpecVersion = null;
        swNd4jBackendClass = null;
        swNd4jDataTypeName = null;
        swHostName = null;
        swJvmUID = null;
    }

    private void clearModelFields() {
        modelClassName = null;
        modelConfigJson = null;
        modelParamNames = null;
    }

    @Override
    public String getSessionID() {
        return sessionID;
    }

    @Override
    public String getTypeID() {
        return typeID;
    }

    @Override
    public String getWorkerID() {
        return workerID;
    }

    @Override
    public long getTimeStamp() {
        return timeStamp;
    }

    @Override
    public int encodingLengthBytes() {
        //TODO reuse the byte[]s here, to avoid converting them twice...

        //First: need to determine how large a buffer to use.
        //Buffer is composed of:
        //(a) Header: 8 bytes (4x uint16 = 8 bytes)
        //(b) Fixed length entries length (sie.BlockLength())
        //(c) Group 1: Hardware devices (GPUs) max memory: 4 bytes header + nEntries * 8 (int64) + nEntries * variable length Strings (header + content)  = 4 + 8*n + content
        //(d) Group 2: Software device info: 4 bytes header + 2x variable length Strings for each
        //(d) Group 3: Parameter names: 4 bytes header + nEntries * variable length strings (header + content) = 4 + content
        //(e) Variable length fields: 15 String length fields. Size: 4 bytes header, plus content. 60 bytes header
        //Fixed length + repeating groups + variable length...
        StaticInfoEncoder sie = new StaticInfoEncoder();
        int bufferSize = 8 + sie.sbeBlockLength() + 4 + 4 + 60; //header + fixed values + group headers + variable length headers

        //For variable length field lengths: easist way is simply to convert to UTF-8
        //Of course, it is possible to calculate it first - but we might as well convert (1 pass), rather than count then convert (2 passes)
        byte[] bSessionId = SbeUtil.toBytes(true, sessionID);
        byte[] bTypeId = SbeUtil.toBytes(true, typeID);
        byte[] bWorkerId = SbeUtil.toBytes(true, workerID);

        byte[] bswArch = SbeUtil.toBytes(hasSoftwareInfo, swArch);
        byte[] bswOsName = SbeUtil.toBytes(hasSoftwareInfo, swOsName);
        byte[] bswJvmName = SbeUtil.toBytes(hasSoftwareInfo, swJvmName);
        byte[] bswJvmVersion = SbeUtil.toBytes(hasSoftwareInfo, swJvmVersion);
        byte[] bswJvmSpecVersion = SbeUtil.toBytes(hasSoftwareInfo, swJvmSpecVersion);
        byte[] bswNd4jBackendClass = SbeUtil.toBytes(hasSoftwareInfo, swNd4jBackendClass);
        byte[] bswNd4jDataTypeName = SbeUtil.toBytes(hasSoftwareInfo, swNd4jDataTypeName);
        byte[] bswHostname = SbeUtil.toBytes(hasSoftwareInfo, swHostName);
        byte[] bswJvmUID = SbeUtil.toBytes(hasSoftwareInfo, swJvmUID);
        byte[] bHwHardwareUID = SbeUtil.toBytes(hasHardwareInfo, hwHardwareUID);
        byte[] bmodelConfigClass = SbeUtil.toBytes(hasModelInfo, modelClassName);
        byte[] bmodelConfigJson = SbeUtil.toBytes(hasModelInfo, modelConfigJson);

        byte[][] bhwDeviceDescription = SbeUtil.toBytes(hasHardwareInfo, hwDeviceDescription);
        byte[][][] bswEnvInfo = SbeUtil.toBytes(swEnvironmentInfo);
        byte[][] bModelParamNames = SbeUtil.toBytes(hasModelInfo, modelParamNames);

        bufferSize += bSessionId.length + bTypeId.length + bWorkerId.length;

        bufferSize += 4; //swEnvironmentInfo group header (always present)
        if (hasSoftwareInfo) {
            bufferSize += SbeUtil.length(bswArch);
            bufferSize += SbeUtil.length(bswOsName);
            bufferSize += SbeUtil.length(bswJvmName);
            bufferSize += SbeUtil.length(bswJvmVersion);
            bufferSize += SbeUtil.length(bswJvmSpecVersion);
            bufferSize += SbeUtil.length(bswNd4jBackendClass);
            bufferSize += SbeUtil.length(bswNd4jDataTypeName);
            bufferSize += SbeUtil.length(bswHostname);
            bufferSize += SbeUtil.length(bswJvmUID);
            //For each entry: 2 variable-length headers (2x4 bytes each) + content
            int envCount = (bswEnvInfo != null ? bswEnvInfo.length : 0);
            bufferSize += envCount * 8;
            bufferSize += SbeUtil.length(bswEnvInfo);
        }
        int nHWDeviceStats = hwNumDevices;
        if (!hasHardwareInfo)
            nHWDeviceStats = 0;
        if (hasHardwareInfo) {
            //Device info group:
            bufferSize += hwNumDevices * 8; //fixed content in group: int64 -> 8 bytes. Encode an entry, even if hwDeviceTotalMemory is null
            bufferSize += hwNumDevices * 4; //uint32: 4 bytes per entry for var length header...; as above
            bufferSize += SbeUtil.length(bhwDeviceDescription);
            bufferSize += SbeUtil.length(bHwHardwareUID);
        }
        if (hasModelInfo) {
            bufferSize += SbeUtil.length(bmodelConfigClass);
            bufferSize += SbeUtil.length(bmodelConfigJson);
            bufferSize += SbeUtil.length(bModelParamNames);
            bufferSize += (bModelParamNames == null ? 0 : bModelParamNames.length * 4); //uint32: 4 bytes per entry for var length header...
        }

        return bufferSize;
    }

    @Override
    public byte[] encode() {
        byte[] bytes = new byte[encodingLengthBytes()];
        MutableDirectBuffer buffer = new UnsafeBuffer(bytes);
        encode(buffer);
        return bytes;
    }

    @Override
    public void encode(ByteBuffer buffer) {
        encode(new UnsafeBuffer(buffer));
    }

    @Override
    public void encode(MutableDirectBuffer buffer) {

        MessageHeaderEncoder enc = new MessageHeaderEncoder();
        StaticInfoEncoder sie = new StaticInfoEncoder();

        byte[] bSessionId = SbeUtil.toBytes(true, sessionID);
        byte[] bTypeId = SbeUtil.toBytes(true, typeID);
        byte[] bWorkerId = SbeUtil.toBytes(true, workerID);

        byte[] bswArch = SbeUtil.toBytes(hasSoftwareInfo, swArch);
        byte[] bswOsName = SbeUtil.toBytes(hasSoftwareInfo, swOsName);
        byte[] bswJvmName = SbeUtil.toBytes(hasSoftwareInfo, swJvmName);
        byte[] bswJvmVersion = SbeUtil.toBytes(hasSoftwareInfo, swJvmVersion);
        byte[] bswJvmSpecVersion = SbeUtil.toBytes(hasSoftwareInfo, swJvmSpecVersion);
        byte[] bswNd4jBackendClass = SbeUtil.toBytes(hasSoftwareInfo, swNd4jBackendClass);
        byte[] bswNd4jDataTypeName = SbeUtil.toBytes(hasSoftwareInfo, swNd4jDataTypeName);
        byte[] bswHostname = SbeUtil.toBytes(hasSoftwareInfo, swHostName);
        byte[] bswJvmUID = SbeUtil.toBytes(hasSoftwareInfo, swJvmUID);
        byte[] bHwHardwareUID = SbeUtil.toBytes(hasHardwareInfo, hwHardwareUID);
        byte[] bmodelConfigClass = SbeUtil.toBytes(hasModelInfo, modelClassName);
        byte[] bmodelConfigJson = SbeUtil.toBytes(hasModelInfo, modelConfigJson);

        byte[][] bhwDeviceDescription = SbeUtil.toBytes(hasHardwareInfo, hwDeviceDescription);
        byte[][][] bswEnvInfo = SbeUtil.toBytes(swEnvironmentInfo);
        byte[][] bModelParamNames = SbeUtil.toBytes(hasModelInfo, modelParamNames);

        enc.wrap(buffer, 0).blockLength(sie.sbeBlockLength()).templateId(sie.sbeTemplateId())
                        .schemaId(sie.sbeSchemaId()).version(sie.sbeSchemaVersion());

        int offset = enc.encodedLength(); //Expect 8 bytes...

        //Fixed length fields: always encoded, whether present or not.
        sie.wrap(buffer, offset).time(timeStamp).fieldsPresent().softwareInfo(hasSoftwareInfo)
                        .hardwareInfo(hasHardwareInfo).modelInfo(hasModelInfo);
        sie.hwJvmProcessors(hwJvmAvailableProcessors).hwNumDevices((short) hwNumDevices).hwJvmMaxMemory(hwJvmMaxMemory)
                        .hwOffheapMaxMemory(hwOffHeapMaxMemory).modelNumLayers(modelNumLayers)
                        .modelNumParams(modelNumParams);
        //Device info group...
        StaticInfoEncoder.HwDeviceInfoGroupEncoder hwdEnc = sie.hwDeviceInfoGroupCount(hwNumDevices);
        int nHWDeviceStats = (hasHardwareInfo ? hwNumDevices : 0);
        for (int i = 0; i < nHWDeviceStats; i++) {
            long maxMem = hwDeviceTotalMemory == null || hwDeviceTotalMemory.length <= i ? 0 : hwDeviceTotalMemory[i];
            byte[] descr = bhwDeviceDescription == null || bhwDeviceDescription.length <= i ? SbeUtil.EMPTY_BYTES
                            : bhwDeviceDescription[i];
            if (descr == null)
                descr = SbeUtil.EMPTY_BYTES;
            hwdEnc.next().deviceMemoryMax(maxMem).putDeviceDescription(descr, 0, descr.length);
        }

        //Environment info group
        int numEnvValues = (hasSoftwareInfo && swEnvironmentInfo != null ? swEnvironmentInfo.size() : 0);
        StaticInfoEncoder.SwEnvironmentInfoEncoder swEnv = sie.swEnvironmentInfoCount(numEnvValues);
        if (numEnvValues > 0) {
            byte[][][] mapAsBytes = SbeUtil.toBytes(swEnvironmentInfo);
            for (byte[][] entryBytes : mapAsBytes) {
                swEnv.next().putEnvKey(entryBytes[0], 0, entryBytes[0].length).putEnvValue(entryBytes[1], 0,
                                entryBytes[1].length);
            }
        }

        int nParamNames = modelParamNames == null ? 0 : modelParamNames.length;
        StaticInfoEncoder.ModelParamNamesEncoder mpnEnc = sie.modelParamNamesCount(nParamNames);
        for (int i = 0; i < nParamNames; i++) {
            mpnEnc.next().putModelParamNames(bModelParamNames[i], 0, bModelParamNames[i].length);
        }

        //In the case of !hasSoftwareInfo: these will all be empty byte arrays... still need to encode them (for 0 length) however
        sie.putSessionID(bSessionId, 0, bSessionId.length).putTypeID(bTypeId, 0, bTypeId.length)
                        .putWorkerID(bWorkerId, 0, bWorkerId.length).putSwArch(bswArch, 0, bswArch.length)
                        .putSwOsName(bswOsName, 0, bswOsName.length).putSwJvmName(bswJvmName, 0, bswJvmName.length)
                        .putSwJvmVersion(bswJvmVersion, 0, bswJvmVersion.length)
                        .putSwJvmSpecVersion(bswJvmSpecVersion, 0, bswJvmSpecVersion.length)
                        .putSwNd4jBackendClass(bswNd4jBackendClass, 0, bswNd4jBackendClass.length)
                        .putSwNd4jDataTypeName(bswNd4jDataTypeName, 0, bswNd4jDataTypeName.length)
                        .putSwHostName(bswHostname, 0, bswHostname.length).putSwJvmUID(bswJvmUID, 0, bswJvmUID.length)
                        .putHwHardwareUID(bHwHardwareUID, 0, bHwHardwareUID.length);
        //Similar: !hasModelInfo -> empty byte[]
        sie.putModelConfigClassName(bmodelConfigClass, 0, bmodelConfigClass.length).putModelConfigJson(bmodelConfigJson,
                        0, bmodelConfigJson.length);
    }

    @Override
    public void encode(OutputStream outputStream) throws IOException {
        //TODO there may be more efficient way of doing this
        outputStream.write(encode());
    }

    @Override
    public void decode(byte[] decode) {
        MutableDirectBuffer buffer = new UnsafeBuffer(decode);
        decode(buffer);
    }

    @Override
    public void decode(ByteBuffer buffer) {
        decode(new UnsafeBuffer(buffer));
    }

    @Override
    public void decode(DirectBuffer buffer) {
        //TODO we could do this much more efficiently, with buffer re-use, etc.
        MessageHeaderDecoder dec = new MessageHeaderDecoder();
        StaticInfoDecoder sid = new StaticInfoDecoder();
        dec.wrap(buffer, 0);

        final int blockLength = dec.blockLength();
        final int version = dec.version();

        final int headerLength = dec.encodedLength();
        //TODO: in general, we should check the header, version, schema etc. But we don't have any other versions yet.

        sid.wrap(buffer, headerLength, blockLength, version);
        timeStamp = sid.time();
        InitFieldsPresentDecoder fields = sid.fieldsPresent();
        hasSoftwareInfo = fields.softwareInfo();
        hasHardwareInfo = fields.hardwareInfo();
        hasModelInfo = fields.modelInfo();

        //These fields: always present, even if !hasHardwareInfo
        hwJvmAvailableProcessors = sid.hwJvmProcessors();
        hwNumDevices = sid.hwNumDevices();
        hwJvmMaxMemory = sid.hwJvmMaxMemory();
        hwOffHeapMaxMemory = sid.hwOffheapMaxMemory();
        modelNumLayers = sid.modelNumLayers();
        modelNumParams = sid.modelNumParams();

        //Hardware device info group
        StaticInfoDecoder.HwDeviceInfoGroupDecoder hwDeviceInfoGroupDecoder = sid.hwDeviceInfoGroup();
        int count = hwDeviceInfoGroupDecoder.count();
        if (count > 0) {
            hwDeviceTotalMemory = new long[count];
            hwDeviceDescription = new String[count];
        }
        int i = 0;
        for (StaticInfoDecoder.HwDeviceInfoGroupDecoder hw : hwDeviceInfoGroupDecoder) {
            hwDeviceTotalMemory[i] = hw.deviceMemoryMax();
            hwDeviceDescription[i++] = hw.deviceDescription();
        }

        //Environment info group
        i = 0;
        StaticInfoDecoder.SwEnvironmentInfoDecoder swEnvDecoder = sid.swEnvironmentInfo();
        if (swEnvDecoder.count() > 0) {
            swEnvironmentInfo = new HashMap<>();
        }
        for (StaticInfoDecoder.SwEnvironmentInfoDecoder env : swEnvDecoder) {
            String key = env.envKey();
            String value = env.envValue();
            swEnvironmentInfo.put(key, value);
        }

        i = 0;
        StaticInfoDecoder.ModelParamNamesDecoder mpdec = sid.modelParamNames();
        int mpnCount = mpdec.count();
        modelParamNames = new String[mpnCount];
        for (StaticInfoDecoder.ModelParamNamesDecoder mp : mpdec) {
            modelParamNames[i++] = mp.modelParamNames();
        }
        //Variable length data. Even if it is missing: still needs to be read, to advance buffer
        //Again, the exact order of these calls matters here
        sessionID = sid.sessionID();
        typeID = sid.typeID();
        workerID = sid.workerID();
        swArch = sid.swArch();
        swOsName = sid.swOsName();
        swJvmName = sid.swJvmName();
        swJvmVersion = sid.swJvmVersion();
        swJvmSpecVersion = sid.swJvmSpecVersion();
        swNd4jBackendClass = sid.swNd4jBackendClass();
        swNd4jDataTypeName = sid.swNd4jDataTypeName();
        swHostName = sid.swHostName();
        swJvmUID = sid.swJvmUID();
        if (!hasSoftwareInfo)
            clearSwFields();
        hwHardwareUID = sid.hwHardwareUID();
        if (!hasHardwareInfo)
            clearHwFields();
        modelClassName = sid.modelConfigClassName();
        modelConfigJson = sid.modelConfigJson();
        if (!hasModelInfo)
            clearModelFields();
    }

    @Override
    public void decode(InputStream inputStream) throws IOException {
        byte[] bytes = IOUtils.toByteArray(inputStream);
        decode(bytes);
    }
}


text:
// The MIT License (MIT)
//
// Copyright (c) 2015-2016 Rasmus Mikkelsen
// Copyright (c) 2015-2016 eBay Software Foundation
// https://github.com/rasmus/EventFlow
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using EventFlow.Queries;
using EventFlow.ReadStores.InMemory;
using EventFlow.TestHelpers.Aggregates.Entities;
using EventFlow.TestHelpers.Aggregates.Queries;
using EventFlow.Tests.IntegrationTests.ReadStores.ReadModels;

namespace EventFlow.Tests.IntegrationTests.ReadStores.QueryHandlers
{
    public class InMemoryThingyGetMessagesQueryHandler : IQueryHandler<ThingyGetMessagesQuery, IReadOnlyCollection<ThingyMessage>>
    {
        private readonly IInMemoryReadStore<InMemoryThingyMessageReadModel> _readStore;

        public InMemoryThingyGetMessagesQueryHandler(
            IInMemoryReadStore<InMemoryThingyMessageReadModel> readStore)
        {
            _readStore = readStore;
        }

        public async Task<IReadOnlyCollection<ThingyMessage>> ExecuteQueryAsync(ThingyGetMessagesQuery query, CancellationToken cancellationToken)
        {
            var readModels = await _readStore.FindAsync(rm => rm.ThingyId == query.ThingyId, cancellationToken).ConfigureAwait(false);
            return readModels
                .Select(rm => rm.ToThingyMessage())
                .ToList();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import { Component } from "@angular/core";
import { ApiDefinition } from "../../../components/api/api.component";

const exampleStandardTemplate = `

Example segment

    <sui-dimmer [(isDimmed)]="isDimmed" [isClickable]="isClickable">

I can have content too!

    </sui-dimmer>

Some random content for the example segment.

Some more content!.

<button class="ui primary button" (click)="isDimmed = !isDimmed">Toggle Dimmer</button>
<sui-checkbox [(ngModel)]="isClickable">Click to close?</sui-checkbox>
`;

const exampleVariationsTemplate = `

    <sui-dimmer class="page" [(isDimmed)]="pageDimmed">

            The page has been dimmed!

    </sui-dimmer>
    <sui-dimmer class="inverted" [(isDimmed)]="segmentDimmed">

Enables loading screens!

    </sui-dimmer>

Page dimmers and inverted dimmers are possible!

    <button class="ui primary button" (click)="pageDimmed = !pageDimmed">Dim Page</button>
    <button class="ui primary button" (click)="segmentDimmed = !segmentDimmed">Dim Segment</button>

`;

@Component({
    selector: "demo-page-dimmer",
    templateUrl: "./dimmer.page.html"
})
export class DimmerPage {
    public api:ApiDefinition = [
        {
            selector: "<sui-dimmer>",
            properties: [
                {
                    name: "isDimmed",
                    type: "boolean",
                    description: "Sets whether or not the dimmer is active.",
                    defaultValue: "false"
                },
                {
                    name: "isClickable",
                    type: "boolean",
                    description: "Sets whether or not clicking the dimmer will dismiss it.",
                    defaultValue: "true"
                },
                {
                    name: "transition",
                    type: "string",
                    description: "Sets the transition used when displaying the dimmer.",
                    defaultValue: "fade"
                },
                {
                    name: "transitionDuration",
                    type: "number",
                    description: "Sets the duration for the dimmer transition.",
                    defaultValue: "300"
                }
            ],
            events: [
                {
                    name: "isDimmedChange",
                    type: "boolean",
                    description: "Fires whenever the dimmer is toggled. " +
                                 "Use the [(isDimmed)] syntax to update when the user clicks out of the dimmer."
                }
            ]
        }
    ];
    public exampleStandardTemplate:string = exampleStandardTemplate;
    public exampleVariationsTemplate:string = exampleVariationsTemplate;
}

@Component({
    selector: "example-dimmer-standard",
    template: exampleStandardTemplate
})
export class DimmerExampleStandard {
    public isClickable:boolean = true;
    public isDimmed:boolean;
}

@Component({
    selector: "example-dimmer-variations",
    template: exampleVariationsTemplate
})
export class DimmerExampleVariations {
    public isClickable:boolean = true;
    public pageDimmed:boolean;
    public segmentDimmed:boolean;
}

export const DimmerPageComponents = [DimmerPage, DimmerExampleStandard, DimmerExampleVariations];


text:
package main

import (
    "net/http"
    "io/ioutil"
)

func GetHttpResource(URL string) string {
    resp, err := http.Get(URL)
    if err != nil {
        // Do something?
    }
    defer resp.Body.Close()

    rawBody, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        // Fine, fine, I'll do something
    }

    return string(rawBody)
}


text:
const JSON = 'json';
const CSV = 'csv';
const YAML = 'yaml';

export const IMAGE_HEADER = 'data:image/png;base64,';

export default {
  JSON,
  CSV,
  YAML
};


text:
var React = require('react');
var ReactDOM = require('react-dom');

//react router
var Router   = require('react-router').Router;
var Route    = require('react-router').Route;
var IndexRoute    = require('react-router').IndexRoute;
var Link     = require('react-router').Link;
var browserHistory = require('react-router').browserHistory;

//components
var GetAllUsers = require('./components/GetAllUsers.js');
var Main = require('./components/Main.js');
var GetUserPost = require('./components/GetUserPost.js');

//scss
require('../public/style.scss');

ReactDOM.render((
	<Router history={browserHistory}>
		<Route path="/" component={Main}>
			<IndexRoute component={GetAllUsers} />
			<Route path="/users/:userId" component={GetUserPost}/>
		</Route>
	</Router>
	),document.getElementById('app'),function(){
	console.log('react app rendered successfully onto the dom!');
});


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;

namespace Azure.AI.FormRecognizer.DocumentAnalysis
{
    public partial class DocumentWord
    {
        internal static DocumentWord DeserializeDocumentWord(JsonElement element)
        {
            string content = default;
            Optional<IReadOnlyList<float>> boundingBox = default;
            DocumentSpan span = default;
            float confidence = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("content"))
                {
                    content = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("boundingBox"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<float> array = new List<float>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(item.GetSingle());
                    }
                    boundingBox = array;
                    continue;
                }
                if (property.NameEquals("span"))
                {
                    span = DocumentSpan.DeserializeDocumentSpan(property.Value);
                    continue;
                }
                if (property.NameEquals("confidence"))
                {
                    confidence = property.Value.GetSingle();
                    continue;
                }
            }
            return new DocumentWord(content, Optional.ToList(boundingBox), span, confidence);
        }
    }
}


text:
<?php

namespace SuitTests\Model;

use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use SuitTests\TestCase;
use Suitcoda\Model\JobInspect;

class JobInspectTest extends TestCase
{
    use DatabaseTransactions;

    /**
     * Test Relationship JobInspect with Inspection
     *
     * @return void
     */
    public function testRelationshipWithInspection()
    {
        $job = new JobInspect;

        $this->assertInstanceOf(BelongsTo::class, $job->inspection());
    }

    /**
     * Test Relationship JobInspect with Scope
     *
     * @return void
     */
    public function testRelationshipWithScope()
    {
        $job = new JobInspect;

        $this->assertInstanceOf(BelongsTo::class, $job->scope());
    }

    /**
     * Test Relationship JobInspect with Url
     *
     * @return void
     */
    public function testRelationshipWithUrl()
    {
        $job = new JobInspect;

        $this->assertInstanceOf(BelongsTo::class, $job->url());
    }

    /**
     * Test Relationship JobInspect with Issues
     *
     * @return void
     */
    public function testRelationshipWithIssues()
    {
        $job = new JobInspect;

        $this->assertInstanceOf(HasMany::class, $job->issues());
    }

    /**
     * Test query scope of getUnhandledJob
     *
     * @return void
     */
    public function testScopeGetUnhandledJob()
    {
        $job = new JobInspect;

        $this->assertNull($job->getUnhandledJob()->first());
    }

    /**
     * Test query scope of completed job
     *
     * @return void
     */
    public function testScopeCompletedJob()
    {
        $jobFaker = factory(JobInspect::class)->create([
            'status' => 2
        ]);

        $this->assertInstanceOf(JobInspect::class, $jobFaker->completed()->first());
    }

    /**
     * Test scope a query to get job by category name.
     *
     * @return void
     */
    public function testScopeByCategoryName()
    {
        $jobFaker = factory(JobInspect::class)->create();

        $this->assertNull($jobFaker->byCategoryName('SEO')->first());
    }
}


text:
package org.knowm.xchange.bitflyer.dto.marketdata;

import com.fasterxml.jackson.annotation.JsonProperty;
import java.math.BigDecimal;
import java.util.List;

public class BitflyerOrderbook {
  private final BigDecimal mid_price;
  private final List<BitflyerOrderbookEntry> bids;
  private final List<BitflyerOrderbookEntry> asks;

  public BitflyerOrderbook(
      @JsonProperty("mid_price") BigDecimal mid_price,
      @JsonProperty("bids") List<BitflyerOrderbookEntry> bidsJson,
      @JsonProperty("asks") List<BitflyerOrderbookEntry> asksJson) {

    this.mid_price = mid_price;
    this.bids = bidsJson;
    this.asks = asksJson;
  }

  public BigDecimal getMidPrice() {
    return mid_price;
  }

  public List<BitflyerOrderbookEntry> getBids() {
    return bids;
  }

  public List<BitflyerOrderbookEntry> getAsks() {
    return asks;
  }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Puccinia hibisciatum Kellerm.

### Remarks
null


text:
//---------------------------------------------------------------------
//
// This source file is part of the Meta:Magical project.
//
// See LICENCE for licence information.
// See CONTRIBUTORS for the list of contributors to the project.
//
//---------------------------------------------------------------------

// --[ Dependencies ]--------------------------------------------------
const AST            = require('./ast');
const Refinable      = require('refinable');
const chalk          = require('chalk');
const marked         = require('marked');
const MarkedTerminal = require('marked-terminal');

// ---[ Initialisation ]-----------------------------------------------
marked.setOptions({
  renderer: new MarkedTerminal({
    reflowText: true,
    width: 72
  })
});

// --[ Helpers ]-------------------------------------------------------
function lines(text) {
  return text.split(/\r\n|\n\r|\n|\r/);
}

function repeat(string, times) {
  return Array(times + 1).join(string);
}

function indent(indentation, text) {
  return `${repeat(' ', indentation)}${text}`;
}

function clamp(n, min, max) {
  return Math.max(min, Math.min(n, max));
}

// --[ The renderer ]--------------------------------------------------

/*~
 * A display for Terminal interfaces.
 *
 * ---
 * isModule  : true
 * stability : experimental
 * category  : Displays
 */
const TerminalDisplay = Refinable.refine({
  formatting: {
    title: [
      (title) => chalk.green.bold([title, repeat('=', title.length)].join('\n')),
      (title) => chalk.bold([title, repeat('-', title.length)].join('\n')),
      chalk.green
    ],

    subtitle: [
      chalk.bold
    ],

    quote: chalk.grey.italic,
    code: chalk.yellow,
    strong: chalk.bold,
    emphasis: chalk.italic,
    good: chalk.green,
    error: chalk.red,
    warning: chalk.red.bold,
    detail: chalk.grey,
    label: chalk.bold,

    markdown: marked
  },

  formattingForLevel(type, level) {
    const levels = this.formatting[type];
    return levels[clamp(level - 1, 0, levels.length - 1)];
  },

  render(tree) {
    return tree.cata({
      Nil:  _          => '',
      Text: ({ text }) => text,

      Sequence: ({ items }) =>
        items.map(x => this.render(x)).join(''),

      Block: ({ indentation, items }) =>
        lines(items.map(v => this.render(v)).join('\n'))
          .map(line => indent(indentation, line))
          .join('\n'),

      Title: ({ level, content }) =>
        this.formattingForLevel('title', level)([
          repeat('#', level),
          ' ',
          this.render(content)
        ].join('')),

      Subtitle: ({ level, content }) =>
        this.formattingForLevel('subtitle', level)(
          this.render(content)
        ),

      Quote: ({ content }) =>
        this.formatting.quote(
          lines(this.render(content)).map(line => `> ${line}`)
                                     .join('\n')
        ),

      Code: ({ language, startAt=1, source }) =>
        this.formatting.code(
            lines(source.trimRight())
              .map(line => indent(4, line))
              .join('\n')
        ),

      List: ({ items }) =>
        '\n' + items.map(item => {
          const [first, ...rest] = lines(this.render(item));
          return [
            `    • ${first}`,
            ...rest.map(line => indent(3, line))
          ].join('\n')
        }).join('\n'),

      Table: ({ headings, rows }) =>
        '(Tables are not implemented yet.)',

      HorizontalLine: ({ size }) =>
        repeat('-', size),

      Strong: ({ content }) =>
        this.formatting.strong(this.render(content)),

      Emphasis: ({ content }) =>
        this.formatting.emphasis(this.render(content)),

      Good: ({ content }) =>
        this.formatting.good(this.render(content)),

      Error: ({ content }) =>
        this.formatting.error(this.render(content)),

      Warning: ({ content }) =>
        this.formatting.warning(this.render(content)),

      Detail: ({ content }) =>
        this.formatting.detail(this.render(content)),

      Label: ({ content }) =>
        this.formatting.label(this.render(content)),

      Markdown: ({ text }) =>
        this.formatting.markdown(text.trimRight()).trim()
    });
  },

  show(tree) {
    console.log(this.render(tree));
  }
});

// --[ Exports ]-------------------------------------------------------
module.exports = TerminalDisplay;


text:
from django.db import models
from django.contrib.postgres.fields import HStoreField
from django.conf import settings
import subprocess
import uuid
import logging
from docker import Client
from docker.tls import TLSConfig
from docker.utils import kwargs_from_env
import json
from . import parser
from autoslug import AutoSlugField
from django.db.models import Avg
from cacheback.decorators import cacheback

logger = logging.getLogger(__name__)

class Provider(models.Model):

    name = models.CharField(max_length=50)
    slug = AutoSlugField(populate_from="name")
    driver_name = models.CharField(max_length=40, unique=True)
    url = models.URLField(null=True)
    image = models.CharField(max_length=50)
    credentials = HStoreField()

    def __unicode__(self):
        return self.name

class Machine(models.Model):

    uuid = models.UUIDField(default=uuid.uuid4, editable=False)
    provider = models.ForeignKey("Provider", related_name="machines")
    name = models.CharField(max_length=50)
    ram = models.FloatField()
    cpu = models.IntegerField()
    disk = models.IntegerField(null=True)
    slug = AutoSlugField(populate_from="name")
    provider_opts = HStoreField()

    def __unicode__(self):
        return self.name

    def run_benchmarks(self):
        self.create_test_dir()
        self.io_benchmark()
        self.unixbench()
        self.mbw_benchmark()

    def _run(self, command):
        logger.debug("running " + " ".join(command))
        process = subprocess.Popen(command, stdout=subprocess.PIPE)
        out, err = process.communicate()
        process.wait()
        logger.debug(" ".join(command) + "returned with %s" % process.returncode + "out was: %s" % out, "err was: %s" % err)
        return process.returncode == 0, out, err, command

    def _run_benchmark(self, types, image, command, parser, extra_kwargs={}):

        client = self.docker_client
        if client:

            # pull create and start
            client.pull(repository=image)
            container = client.create_container(image=image, command=command, **extra_kwargs)
            client.start(container)

            output = ""
            for line in client.logs(container=container, stream=True):
                output += line

            datapoints = parser(output.strip())

            for benchmark_type, data in zip(types, datapoints):
                valid = data is not None
                Benchmark.objects.create(
                    raw=output,
                    benchmark_type=benchmark_type,
                    machine=self,
                    data=data,
                    valid=valid
                )

    @property
    def docker_client(self):
        inspect = self.inspect()
        if inspect != {}:
            base_url = "https://" + inspect["Driver"]["IPAddress"] + ":2376"
            tls = TLSConfig(
                client_cert=(
                    inspect["HostOptions"]["AuthOptions"]["ClientCertPath"],
                    inspect["HostOptions"]["AuthOptions"]["ClientKeyPath"]
                ),
                verify=inspect["HostOptions"]["AuthOptions"]["CaCertPath"],
                assert_hostname=False
            )
            return Client(base_url=base_url, tls=tls)
        return False

    def avg_unixbench(self):
        return cacheback(60*15)(avg_benchmark)(self.pk, Benchmark.UNIXBENCH)

    def avg_io_latency(self):
        return cacheback(60*15)(avg_benchmark)(self.pk, Benchmark.IO_LATENCY)

    def avg_io_seek_rate(self):
        return cacheback(60*15)(avg_benchmark)(self.pk, Benchmark.IO_SEEK)

    def avg_io_seq_speed(self):
        return cacheback(60*15)(avg_benchmark)(self.pk, Benchmark.IO_SEQ)

    def avg_io_raw_speed(self):
        return cacheback(60*15)(avg_benchmark)(self.pk, Benchmark.IO_RAW)

    def avg_mem_memcpy(self):
        return cacheback(60*15)(avg_benchmark)(self.pk, Benchmark.MEMORY_MEMCPY)

    def avg_mem_dumb(self):
        return cacheback(60*15)(avg_benchmark)(self.pk, Benchmark.MEMORY_DUMB)

    def avg_mem_mcblock(self):
        return cacheback(60*15)(avg_benchmark)(self.pk, Benchmark.MEMORY_MCBLOCK)

    def inspect(self):
        success, out, err, command = self._run(["/usr/local/bin/docker-machine", "inspect", str(self.uuid)])
        return json.loads(out) if success else {}

    def create_test_dir(self):
        return self._run(['/usr/local/bin/docker-machine', "ssh", str(self.uuid), "sudo mkdir -p /test"])

    def io_benchmark(self):
        volumes = {"volumes": "/test:/test"}
        # io latency
        self._run_benchmark(types=[Benchmark.IO_LATENCY],
                            image="jayfk/ioping", command="/usr/bin/ioping -c 10 -B /test",
                            parser=parser.io_latency, extra_kwargs=volumes)

        # disk seek rate
        self._run_benchmark(types=[Benchmark.IO_SEEK],
                            image="jayfk/ioping", command="/bin/sh -c 'for i in `seq 10`; do /usr/bin/ioping -R -B /test; done'",
                            parser=parser.io_disk_seek_rate, extra_kwargs=volumes)

        # disk seq speed
        self._run_benchmark(types=[Benchmark.IO_SEQ],
                            image="jayfk/ioping", command="/bin/sh -c 'for i in `seq 10`; do /usr/bin/ioping -RLB /test; done'",
                            parser=parser.io_disk_seq_speed, extra_kwargs=volumes)

        self._run_benchmark(types=[Benchmark.IO_RAW],
                            image="debian:jessie",
                            command="dd if=/dev/zero of=/test/none bs=1M count=1k conv=fdatasync",
                            parser=parser.dd, extra_kwargs=volumes)

    def unixbench(self):
        volumes = {"volumes": ["/test/testdir:/tmp/UnixBench/testdir", "/test/testdir:/tmp/UnixBench/tmp"]}
        self._run_benchmark(types=[Benchmark.UNIXBENCH],
                            image="jayfk/unixbench", command=None, parser=parser.unixbench, extra_kwargs=volumes)

    def mbw_benchmark(self):

        self._run_benchmark(types=[Benchmark.MEMORY_MEMCPY, Benchmark.MEMORY_DUMB, Benchmark.MEMORY_MCBLOCK],
                            image="jayfk/mbw", command="/usr/bin/mbw -n 300 200", parser=parser.mbw)

    def create_machine(self):

        def format(config, prefix):
            params = []

            for k, v in config.iteritems():

                # add a -- to the beginning and replace all underscores with dashes
                key = "--" + prefix + "-" + k.replace("_", "-")

                # if the value is a boolean and true we only add the key
                if isinstance(v, bool):
                    if v:
                        params.append(key)
                # otherwise we'll only add values that are not empty
                else:
                    if v not in [None, ""]:
                        params.append(key + "=" + str(v))
            return params

        command = ['/usr/local/bin/docker-machine', "create", str(self.uuid), "--driver={0}".format(self.provider.driver_name)]
        command.extend(format(self.provider.credentials, prefix=self.provider.driver_name))
        command.extend(format(self.provider_opts, prefix=self.provider.driver_name))

        return self._run(command)

    def remove_machine(self, force=False):
        """
        Remove a machine

        :param name: name of the machine
        :return: cli output
        """
        return self._run(['/usr/local/bin/docker-machine', "rm --force" if force else "rm", str(self.uuid)])

class Benchmark(models.Model):

    MEMORY_MEMCPY = 0
    MEMORY_DUMB = 1
    MEMORY_MCBLOCK = 2
    UNIXBENCH = 3
    IO_RAW = 4
    IO_SEQ = 5
    IO_SEEK = 6
    IO_LATENCY = 7

    TYPE_CHOICES = (
        (MEMORY_MEMCPY, "Memory MEMCPY"),
        (MEMORY_DUMB, "Memory DUMB"),
        (MEMORY_MCBLOCK, "Memory MCBLOCK"),
        (UNIXBENCH, "Unixbench"),
        (IO_RAW, "I/O Raw Speed"),
        (IO_SEQ, "I/O Seq Speed"),
        (IO_SEEK, "I/O Seek Rate"),
        (IO_LATENCY, "I/O Latency"),
    )

    created = models.DateTimeField(auto_now=True)
    valid = models.BooleanField(default=False)
    machine = models.ForeignKey("Machine", related_name="benchmarks")
    benchmark_type = models.SmallIntegerField(db_index=True)
    data = models.FloatField(null=True)
    raw = models.TextField(default="")

    def __unicode__(self):
        return self.name

    def name(self):
        for bench in Benchmark.TYPE_CHOICES:
            if bench[0] == self.benchmark_type:
                return bench[1]
        return "Unknown"

def avg_benchmark(machine, benchmark_type):
    return Benchmark.objects.filter(machine=machine, benchmark_type=benchmark_type, valid=True).aggregate(Avg("data"))["data__avg"]


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Lloyd Lib. Bot. 35: 193 (1936)

#### Original name
Secotium obtusum Lloyd

### Remarks
null


text:
CoralClient
===========

Frontend UI based on backbone, coffeescript and compass


text:
package org.spongepowered.common.mixin.api.minecraft.world.item.crafting;

import static org.spongepowered.common.inventory.util.InventoryUtil.toNativeInventory;

import net.minecraft.core.NonNullList;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.Container;
import net.minecraft.world.item.ItemStack;
import org.spongepowered.api.item.inventory.Inventory;
import org.spongepowered.api.item.inventory.ItemStackSnapshot;
import org.spongepowered.api.item.recipe.Recipe;
import org.spongepowered.api.item.recipe.RecipeType;
import org.spongepowered.api.item.recipe.crafting.Ingredient;
import org.spongepowered.api.world.server.ServerWorld;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.common.item.recipe.ingredient.IngredientUtil;
import org.spongepowered.common.item.util.ItemStackUtil;

import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Nonnull;

@Mixin(net.minecraft.world.item.crafting.Recipe.class)
public interface RecipeMixin_API<C extends Container> extends Recipe {

    // @formatter:off
    @Shadow ItemStack shadow$assemble(C inv);
    @Shadow net.minecraft.world.item.ItemStack shadow$getResultItem();
    @Shadow ResourceLocation shadow$getId();
    @Shadow boolean shadow$isSpecial();
    @Shadow boolean shadow$matches(C inv, net.minecraft.world.level.Level worldIn);
    @Shadow NonNullList<ItemStack> shadow$getRemainingItems(C inv);
    @Shadow net.minecraft.world.item.crafting.RecipeType<?> shadow$getType();
    @Shadow NonNullList<net.minecraft.world.item.crafting.Ingredient> shadow$getIngredients();
    // @formatter:on

    @Nonnull
    @Override
    default ItemStackSnapshot exemplaryResult() {
        return ItemStackUtil.snapshotOf(this.shadow$getResultItem());
    }

    @Override
    default boolean isValid(@Nonnull final Inventory inv, @Nonnull final ServerWorld world) {
        return this.shadow$matches(toNativeInventory(inv), (net.minecraft.world.level.Level) world);
    }

    @Nonnull
    @Override
    default ItemStackSnapshot result(@Nonnull final Inventory inv) {
        return ItemStackUtil.snapshotOf(this.shadow$assemble(toNativeInventory(inv)));
    }

    @Nonnull
    @Override
    default List<ItemStackSnapshot> remainingItems(@Nonnull final Inventory inv) {
        return this.shadow$getRemainingItems(toNativeInventory(inv)).stream()
                .map(ItemStackUtil::snapshotOf)
                .collect(Collectors.toList());
    }

    @Override
    default List<Ingredient> ingredients() {
        return this.shadow$getIngredients().stream().map(IngredientUtil::fromNative).collect(Collectors.toList());
    }

    @Override
    default boolean isDynamic() {
        return this.shadow$isSpecial();
    }

    @Override
    default RecipeType<? extends Recipe> type() {
        return (RecipeType) this.shadow$getType();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.gmail.htaihm.geoquiz.QuizActivity"
    >

    <TextView
        android:id="@+id/question_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:padding="24dp"
        />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical|center_horizontal"
        android:orientation="horizontal"
        >
        <Button
            android:id="@+id/true_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/true_button"
            />
        <Button
            android:id="@+id/false_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/false_button"
            />
    </LinearLayout>
    <ImageButton
        android:id="@+id/prev_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|left"
        android:src="@drawable/arrow_left"
        android:contentDescription="@string/prev_image_button"

        />
    <Button
        android:id="@+id/cheat_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center"
        android:text="@string/cheat_button"
        />
    <Button
        android:id="@+id/next_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|right"
        android:text="@string/next_button"
        android:drawableRight="@drawable/arrow_right"
        android:drawablePadding="4dp"/>
</FrameLayout>


text:
from __future__ import unicode_literals

import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import re

class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Match',
            fields=[
                ('match_id', models.BigIntegerField(primary_key=True, serialize=False)),
                ('match_seq_num', models.BigIntegerField(null=True)),
                ('radiant_win', models.BooleanField()),
                ('duration', models.IntegerField(null=True)),
                ('start_time', models.DateTimeField(null=True)),
                ('patch', models.CharField(max_length=255, null=True)),
                ('tower_status_radiant', models.IntegerField(null=True)),
                ('tower_status_dire', models.IntegerField(null=True)),
                ('barracks_status_radiant', models.IntegerField(null=True)),
                ('barracks_status_dire', models.IntegerField(null=True)),
                ('cluster', models.IntegerField(null=True)),
                ('first_blood_time', models.IntegerField(null=True)),
                ('lobby_type', models.CharField(max_length=255, null=True)),
                ('human_players', models.IntegerField(null=True)),
                ('leagueid', models.IntegerField(null=True)),
                ('game_mode', models.CharField(max_length=255, null=True)),
                ('flags', models.IntegerField(null=True)),
                ('engine', models.IntegerField(null=True)),
                ('radiant_score', models.IntegerField(null=True)),
                ('dire_score', models.IntegerField(null=True)),
            ],
        ),
        migrations.CreateModel(
            name='Slot',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('team', models.CharField(max_length=10)),
                ('account_id', models.BigIntegerField(null=True)),
                ('hero_id', models.IntegerField()),
                ('items', models.CharField(max_length=255, null=True, validators=[django.core.validators.RegexValidator(re.compile('^\\d+(?:\\,\\d+)*\\Z'), code='invalid', message='Enter only digits separated by commas.')])),
                ('kills', models.IntegerField(null=True)),
                ('deaths', models.IntegerField(null=True)),
                ('assists', models.IntegerField(null=True)),
                ('leaver_status', models.IntegerField(null=True)),
                ('last_hits', models.IntegerField(null=True)),
                ('denies', models.IntegerField(null=True)),
                ('gpm', models.IntegerField(null=True)),
                ('xpm', models.IntegerField(null=True)),
                ('level', models.IntegerField(null=True)),
                ('gold', models.IntegerField(null=True)),
                ('gold_spent', models.IntegerField(null=True)),
                ('hero_damage', models.IntegerField(null=True)),
                ('tower_damage', models.IntegerField(null=True)),
                ('hero_healing', models.IntegerField(null=True)),
                ('match', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='slots', to='app.Match')),
            ],
        ),
    ]


text:
<?php namespace estvoyage\risingsun\tests\units\time\clock\timestamp\unix;

require __DIR__ . '/../../../../../runner.php';

use estvoyage\risingsun\{ tests\units, comparison, block, time\duration\timestamp };
use mock\estvoyage\risingsun\{ time\duration\timestamp\unix as mockOfUnix, ofloat as mockOfOFloat };

class micro extends units\test
{
	function testClass()
	{
		$this->testedClass
			->implements('estvoyage\risingsun\time\clock')
		;
	}

	function test__construct()
	{
		$this->object($this->newTestedInstance)->isEqualTo($this->newTestedInstance(new timestamp\unix\micro\any));
	}

	function testRecipientOfMicroUnixTimestampIs()
	{
		$this
			->given(
				$template = new mockOfUnix\micro,
				$recipient = new mockOfUnix\micro\recipient,
				$now = microtime(true)
			)
			->if(
				$this->function->microtime = function($float) use ($now) {
					return $float ? $now : 0.145677877 . ' ' .  rand(0, PHP_INT_MAX);
				},
				$this->newTestedInstance($template)
			)
			->then
				->object($this->testedInstance->recipientOfMicroUnixTimestampIs($recipient))
					->isEqualTo($this->newTestedInstance($template))
				->mock($recipient)
					->receive('microUnixTimestampIs')
						->never

			->given(
				$timestamp = new mockOfUnix\micro
			)
			->if(
				$this->calling($template)->recipientOfOIntegerWithNIntegerIs = function($ninteger, $recipient) use ($now, $timestamp) {
					(new comparison\binary\equal)
						->recipientOfComparisonBetweenOperandAndReferenceIs(
							$ninteger,
							$now * 1000000,
							new comparison\recipient\functor\ok(
								function() use ($recipient, $timestamp)
								{
									$recipient->ointegerIs($timestamp);
								}
							)
						)
					;
				}
			)
			->then
				->object($this->testedInstance->recipientOfMicroUnixTimestampIs($recipient))
					->isEqualTo($this->newTestedInstance($template))
				->mock($recipient)
					->receive('microUnixTimestampIs')
						->withArguments($timestamp)
							->once
		;
	}
}


text:
<?php

namespace Sirena\relation\dataprovider;

use Sirena\relation\relation\RelationInterface;

interface DataProviderInterface {
	public function read(RelationInterface $relation);
}


text:
namespace rho
{
	using namespace apiGenerator;
	using namespace common;

	#undef DEFAULT_LOGCATEGORY
	#define DEFAULT_LOGCATEGORY "Device"

	class CDeviceSingletonImpl: public CDeviceSingletonBase
	{
	public:
		CDeviceSingletonImpl(): CDeviceSingletonBase()
		{

		}

		// calibrate - Carries out the screen calibration routine.
		virtual void calibrate(rho::apiGenerator::CMethodResult& oResult)
		{
			SetCallback(NULL);
			if (oResult.hasCallback())
			{
				DEBUGMSG(true, (L"Callback"));
				SetCallback(&oResult);
				//Calibrate the device with callback.
				CalibrateTheDeviceWithCallback();
			}
			else
			{
				//Calibrate the device without callback.
				CalibrateTheDevice();
			}
		}
		// suspend - Puts the device into suspend mode. On suspend, the device goes to hibernation mode. Callback is triggered only for 'failed' status.
		virtual void suspend(rho::apiGenerator::CMethodResult& oResult)
		{
			SetCallback(NULL);
			if (oResult.hasCallback())
			{
				DEBUGMSG(true, (L"Callback"));
				SetCallback(&oResult);
			}
			//Suspend the device.
			SuspendTheDevice();
		}
		// powerOff  - Puts the device into power off mode.  In this mode the device will draw no power. Only supported on SB1. Callback is triggered only for 'failed' status.
		virtual void powerOff(rho::apiGenerator::CMethodResult& oResult)
		{
			SetCallback(NULL);
			if (oResult.hasCallback())
			{
				DEBUGMSG(true, (L"Callback"));
				SetCallback(&oResult);
			}
			//PowerOff the device.
			PowerOffTheDevice();
		}
		// idle - Puts the device into idle mode. In this mode, the screen display is turned off. Callback is triggered only for 'failed' status.
        virtual void idle(rho::apiGenerator::CMethodResult& oResult)
		{
			SetCallback(NULL);
			if (oResult.hasCallback())
			{
				DEBUGMSG(true, (L"Callback"));
				SetCallback(&oResult);
			}
            //Idle the device.
            IdleTheDevice();
        }
		// wake - In WM/CE, wakes the device from idle state to active state. Callback is triggered only for 'failed' status. In Android, it will turn on the display, if it was off. The callback parameter is ignored in Android platform.
		virtual void wake(rho::apiGenerator::CMethodResult& oResult)
		{
			SetCallback(NULL);
			if (oResult.hasCallback())
			{
				DEBUGMSG(true, (L"Callback"));
				SetCallback(&oResult);
			}
			//Wake the device.
			WakeTheDevice();
		}
		// reboot - In WM/CE, reboots the terminal using either a Warm or Cold software boot (as specified). Note on CE6 devices a 'ColdCAD' boot is required to replicate the Coldboot key sequence, e.g. 1+9+Power on an MC3000. Callback is triggered only for 'failed' status. In Android, it will reboot the device. The callback parameter is ignored in Android platform.
		virtual void reboot( const rho::String& bootType, rho::apiGenerator::CMethodResult& oResult)
		{
			SetCallback(NULL);
			if (oResult.hasCallback())
			{
				DEBUGMSG(true, (L"Callback"));
				SetCallback(&oResult);
			}
			//Reboot the device.
			RebootTheDevice(convertToStringW(bootType).c_str());
		}

	};

	class CDeviceImpl : public CDeviceBase
	{
	public:
		CDeviceImpl(const rho::String& strID)
		{

		}
		virtual ~CDeviceImpl()
		{

		}
	};

	////////////////////////////////////////////////////////////////////////

	class CDeviceFactory: public CDeviceFactoryBase
	{
	public:
		CDeviceFactory()
		{

		}
		~CDeviceFactory()
		{

		}
		IDeviceSingleton* createModuleSingleton()
		{
			return new CDeviceSingletonImpl();
		}
	};

	extern "C" void Init_Device_extension()
	{
		CDeviceFactory::setInstance( new CDeviceFactory() );
		Init_Device_API();
	}
}


text:
package org.elasticsearch.xpack.core.async;

import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.stream.ByteBufferStreamInput;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.tasks.TaskId;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Base64;
import java.util.Objects;

/**
 * A class that contains all information related to a submitted async execution.
 */
public final class AsyncExecutionId {
    private final String docId;
    private final TaskId taskId;
    private final String encoded;

    public AsyncExecutionId(String docId, TaskId taskId) {
        this(docId, taskId, encode(docId, taskId));
    }

    private AsyncExecutionId(String docId, TaskId taskId, String encoded) {
        this.docId = docId;
        this.taskId = taskId;
        this.encoded = encoded;
    }

    /**
     * The document id of the response in the index if the task is not running.
     */
    public String getDocId() {
        return docId;
    }

    /**
     * The {@link TaskId} of the async execution in the task manager.
     */
    public TaskId getTaskId() {
        return taskId;
    }

    /**
     * Gets the encoded string that represents this execution.
     */
    public String getEncoded() {
        return encoded;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        AsyncExecutionId searchId = (AsyncExecutionId) o;
        return docId.equals(searchId.docId) &&
            taskId.equals(searchId.taskId);
    }

    @Override
    public int hashCode() {
        return Objects.hash(docId, taskId);
    }

    @Override
    public String toString() {
        return "AsyncExecutionId{" +
            "docId='" + docId + '\'' +
            ", taskId=" + taskId +
            '}';
    }

    /**
     * Encodes the informations needed to retrieve a async response
     * in a base64 encoded string.
     */
    public static String encode(String docId, TaskId taskId) {
        try (BytesStreamOutput out = new BytesStreamOutput()) {
            out.writeString(docId);
            out.writeString(taskId.toString());
            return Base64.getUrlEncoder().encodeToString(BytesReference.toBytes(out.bytes()));
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }
    }

    /**
     * Decodes a base64 encoded string into an {@link AsyncExecutionId} that can be used
     * to retrieve the response of an async execution.
     */
    public static AsyncExecutionId decode(String id) {
        final ByteBuffer byteBuffer;
        try {
            byteBuffer = ByteBuffer.wrap(Base64.getUrlDecoder().decode(id));
        } catch (Exception e) {
            throw new IllegalArgumentException("invalid id: [" + id + "]", e);
        }
        String docId;
        String taskId;
        try (StreamInput in = new ByteBufferStreamInput(byteBuffer)) {
            docId = in.readString();
            taskId = in.readString();
            if (in.available() > 0) {
                throw new IllegalArgumentException("invalid id: [" + id + "]");
            }
        } catch (IOException e) {
            throw new IllegalArgumentException("invalid id: [" + id + "]", e);
        }
        return new AsyncExecutionId(docId, new TaskId(taskId), id);
    }
}


text:
// Copyright 2011 Google Inc.
// see Purple/license.txt for BSD license
// johnjbarton@google.com

/*globals define console window*/

define(['editor/editorDelegator', 'compiler/traceuratops/compileFeatureByTraceur'],
function(       EditorDelegator,                               compilerByTraceur) {

  // -----------------------------------------------------------------------------------
  // Private impl

  function onSourceChange(name, src, startDamage, endDamage) {
    if (src) {
      var compiled = this.compiler.compile(name, src);
      if (compiled) {
        var value = eval(compiled);
        this.editor.showValue(value);
        // allow the caller to use the result
        return compiled;
      } else {
        var indicators = this.compiler.reporter.errorIndicators;
        var summary;
        indicators.forEach(function summarizeErrors(indicator) {
          if (!summary)  {
            summary = indicator;
          } else {
            if (summary.line === indicator.line) {
              if (indicator.join) {
                summary.token += indicator.token;
              } // else first one wins
            } else {
              this.editor.reportError(summary);
            }
          }
        }.bind(this));
        this.editor.reportError(summary);
      }
    }
    // else ignore empty buffers
  }

  function onLineRevealed(name, beginLine, endLine, tokenStyles) {
    var tokenRanges = this.compiler.getTokenRangesByLines(name, beginLine, endLine);
    this.editor.convertTokenTypes(tokenRanges, tokenStyles);
  }

  //---------------------------------------------------------------------

  function EditorCompilerAssembly(element) {
    this.editor = new EditorDelegator(element);
    this.compiler = compilerByTraceur;
    this.editor.addSourceChangeListener(onSourceChange.bind(this));
    this.editor.addLineRevealedListener(onLineRevealed.bind(this));
    this.open = this.editor.open.bind(this.editor);
  }

  //------------------------------------------------------------------------------------
  // API
  EditorCompilerAssembly.prototype = {

  };

  //------------------------

  EditorCompilerAssembly.prototype.saveFocus = function() {
    this.activeElement = window.document.activeElement;
  };

  EditorCompilerAssembly.prototype.restoreFocus = function() {
    if(this.activeElement) {
      this.activeElement.focus();
    }
    this.setFocus();
  };

  return EditorCompilerAssembly;
});


text:
package net.safedata.springboot.training.d02.s05.controller;

import net.safedata.spring.training.jpa.model.Product;
import net.safedata.springboot.training.d02.s05.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

/**
 * A Spring {@link RestController} used to showcase the modeling of a REST controller for CRUD operations
 *
 * @author bogdan.solga
 */
@RestController
@RequestMapping(
        path = "/product"
)
public class ProductController {

    private final ProductService productService; // database? web service? eMag? file?

    @Autowired
    public ProductController(final ProductService productService) {
        this.productService = productService;
    }

    @PostMapping
    public ResponseEntity<?> create(@RequestBody Product product) {
        productService.create(product);
        return ResponseEntity.ok(HttpStatus.OK);
    }

    @GetMapping("/{id}")
    public Product getProduct(@PathVariable final int id) {
        return productService.get(id);
    }

    @GetMapping("/async/{id}")
    public DeferredResult<Product> getProductAsync(@PathVariable final int id) {
        final CompletableFuture<Product> futureProduct = CompletableFuture.supplyAsync(() -> productService.get(id));

        final DeferredResult<Product> deferredResult = new DeferredResult<>();
        deferredResult.setResult(futureProduct.join());

        return deferredResult;
    }

    @GetMapping
    public List<Product> getAll() {
        return StreamSupport.stream(productService.getAll().spliterator(), false)
                             .collect(Collectors.toList());
    }

    @GetMapping(
            path = {
                    "/{pageNumber}/{resultsNumber}/{sortMode}",
                    "/{pageNumber}/{resultsNumber}"
            }
    )
    public Page<Product> getPage(@PathVariable final int pageNumber,
                                 @PathVariable final int resultsNumber,
                                 @PathVariable final Optional<String> sortMode) {
        return productService.getPage(pageNumber, resultsNumber, sortMode.orElse("asc"));
    }

    @PutMapping("/{id}")
    public ResponseEntity<?> update(@PathVariable final int id, @RequestBody Product product) {
        productService.update(id, product);
        return ResponseEntity.ok(HttpStatus.OK);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> delete(@PathVariable final int id) {
        productService.delete(id);
        return ResponseEntity.ok(HttpStatus.OK);
    }
}


text:
namespace Gu.Roslyn.Asserts
{
    /// <summary>
    /// Settings for how <see cref="AstWriter"/> serializes the tree.
    /// </summary>
    public sealed class AstWriterSettings
    {
        /// <summary>
        /// For dumping all the things in light format.
        /// </summary>
        public static readonly AstWriterSettings Default = new AstWriterSettings(AstFormat.Light, AstTrivia.Token, ignoreEmptyTrivia: false);

        /// <summary>
        /// For dumping all the things in JSON format.
        /// </summary>
        public static readonly AstWriterSettings DefaultJson = new AstWriterSettings(AstFormat.Json, AstTrivia.Token, ignoreEmptyTrivia: false);

        /// <summary>
        /// Initializes a new instance of the <see cref="AstWriterSettings"/> class.
        /// </summary>
        /// <param name="format">Specifies the format of the dump.</param>
        /// <param name="trivia">Specifies what trivia to include.</param>
        /// <param name="ignoreEmptyTrivia">Specifies if empty whitespace trivia should be ignored.</param>
        public AstWriterSettings(AstFormat format, AstTrivia trivia, bool ignoreEmptyTrivia)
        {
            this.Format = format;
            this.Trivia = trivia;
            this.IgnoreEmptyTrivia = ignoreEmptyTrivia;
        }

        /// <summary>
        /// Gets a value indicating the format of the dump <see cref="AstFormat"/>.
        /// </summary>
        public AstFormat Format { get; }

        /// <summary>
        /// Gets a value indicating what trivia to include <see cref="AstTrivia"/>.
        /// </summary>
        public AstTrivia Trivia { get; }

        /// <summary>
        /// Gets a value indicating whether empty whitespace trivia should be ignored.
        /// SyntaxFactory.Whitespace(string.Empty).
        /// </summary>
        public bool IgnoreEmptyTrivia { get; }
    }
}


text:
package com.microsoft.azure.management.compute.v2019_11_01;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Describes a Encryption Settings for a Disk.
 */
public class DiskEncryptionSettings {
    /**
     * Specifies the location of the disk encryption key, which is a Key Vault
     * Secret.
     */
    @JsonProperty(value = "diskEncryptionKey")
    private KeyVaultSecretReference diskEncryptionKey;

    /**
     * Specifies the location of the key encryption key in Key Vault.
     */
    @JsonProperty(value = "keyEncryptionKey")
    private KeyVaultKeyReference keyEncryptionKey;

    /**
     * Specifies whether disk encryption should be enabled on the virtual
     * machine.
     */
    @JsonProperty(value = "enabled")
    private Boolean enabled;

    /**
     * Get specifies the location of the disk encryption key, which is a Key Vault Secret.
     *
     * @return the diskEncryptionKey value
     */
    public KeyVaultSecretReference diskEncryptionKey() {
        return this.diskEncryptionKey;
    }

    /**
     * Set specifies the location of the disk encryption key, which is a Key Vault Secret.
     *
     * @param diskEncryptionKey the diskEncryptionKey value to set
     * @return the DiskEncryptionSettings object itself.
     */
    public DiskEncryptionSettings withDiskEncryptionKey(KeyVaultSecretReference diskEncryptionKey) {
        this.diskEncryptionKey = diskEncryptionKey;
        return this;
    }

    /**
     * Get specifies the location of the key encryption key in Key Vault.
     *
     * @return the keyEncryptionKey value
     */
    public KeyVaultKeyReference keyEncryptionKey() {
        return this.keyEncryptionKey;
    }

    /**
     * Set specifies the location of the key encryption key in Key Vault.
     *
     * @param keyEncryptionKey the keyEncryptionKey value to set
     * @return the DiskEncryptionSettings object itself.
     */
    public DiskEncryptionSettings withKeyEncryptionKey(KeyVaultKeyReference keyEncryptionKey) {
        this.keyEncryptionKey = keyEncryptionKey;
        return this;
    }

    /**
     * Get specifies whether disk encryption should be enabled on the virtual machine.
     *
     * @return the enabled value
     */
    public Boolean enabled() {
        return this.enabled;
    }

    /**
     * Set specifies whether disk encryption should be enabled on the virtual machine.
     *
     * @param enabled the enabled value to set
     * @return the DiskEncryptionSettings object itself.
     */
    public DiskEncryptionSettings withEnabled(Boolean enabled) {
        this.enabled = enabled;
        return this;
    }

}


text:
"use strict";

WScript.Echo(ScriptEngineMajorVersion() + "." + ScriptEngineMinorVersion() + "." + ScriptEngineBuildVersion());


text:
namespace SupersonicSound.LowLevel
{
    public struct DspBufferConfiguration
    {
        public uint BufferLength { get; private set; }

        public int NumBuffers { get; private set; }

        public DspBufferConfiguration(uint length, int count)
            :this()
        {
            BufferLength = length;
            NumBuffers = count;
        }
    }
}


text:
package test

import (
	"os"
	"testing"

	"github.com/tsuru/config"
	"launchpad.net/gocheck"

	"github.com/wiliamsouza/apollo/db"
)

func Test(t *testing.T) { gocheck.TestingT(t) }

type S struct{}

var _ = gocheck.Suite(&S{})

func (s *S) SetUpSuite(c *gocheck.C) {
	err := config.ReadConfigFile("../etc/apollod.conf")
	c.Check(err, gocheck.IsNil)
	if os.Getenv("MONGODB_URL") != "" {
		config.Set("database:url", os.Getenv("MONGODB_URL"))
	} else {
		config.Set("database:url", "127.0.0.1:27017")
	}
	config.Set("database:name", "apollo_test_tests")
	db.Connect()
}

func (s *S) TearDownSuite(c *gocheck.C) {
	db.Session.DB.DropDatabase()
}

func (s *S) TestNewCicle(c *gocheck.C) {
	cicle := Cicle{Name: "Test maguro", Device: "maguro",
		Packages: []string{"bluetooth.jar", "wifi.jar"}}
	test, err := NewCicle(cicle)
	c.Assert(err, gocheck.IsNil)
	defer db.Session.Cicle().RemoveId(test.Id)
	var cicleDb Cicle
	err = db.Session.Cicle().FindId(test.Id).One(&cicleDb)
	c.Assert(err, gocheck.IsNil)
	c.Assert(cicleDb, gocheck.DeepEquals, test)
}

func (s *S) TestListCicles(c *gocheck.C) {
	cicle1 := Cicle{Name: "Test maguro", Device: "maguro",
		Packages: []string{"bluetooth.jar", "wifi.jar"}}
	cicle2 := Cicle{Name: "Test yakju", Device: "yakju",
		Packages: []string{"bluetooth.jar", "wifi.jar"}}
	test1, err := NewCicle(cicle1)
	c.Assert(err, gocheck.IsNil)
	test2, err := NewCicle(cicle2)
	c.Assert(err, gocheck.IsNil)
	defer db.Session.Cicle().RemoveId(test1.Id)
	defer db.Session.Cicle().RemoveId(test2.Id)
	cicleList := CicleList{test1, test2}
	cicleListDb, err := ListCicles()
	c.Assert(err, gocheck.IsNil)
	c.Assert(cicleListDb, gocheck.DeepEquals, cicleList)
}

func (s *S) TestDetailCicle(c *gocheck.C) {
	cicle := Cicle{Name: "Test maguro", Device: "maguro",
		Packages: []string{"bluetooth.jar", "wifi.jar"}}
	test, err := NewCicle(cicle)
	c.Assert(err, gocheck.IsNil)
	defer db.Session.Cicle().RemoveId(test.Id)
	cicleDb, err := DetailCicle(test.Id.Hex())
	c.Assert(err, gocheck.IsNil)
	c.Assert(cicleDb, gocheck.DeepEquals, test)
}

func (s *S) TestmodifyCicle(c *gocheck.C) {
	cicle1 := Cicle{Name: "Test maguro", Device: "maguro",
		Packages: []string{"bluetooth.jar", "wifi.jar"}}
	test, err := NewCicle(cicle1)
	cicle2 := Cicle{Id: test.Id, Name: "Test yakju", Device: "yakju",
		Packages: []string{"bluetooth.jar", "wifi.jar"}}
	c.Assert(err, gocheck.IsNil)
	defer db.Session.Cicle().RemoveId(test.Id)
	err = ModifyCicle(test.Id.Hex(), cicle2)
	c.Assert(err, gocheck.IsNil)
	var cicleDb Cicle
	err = db.Session.Cicle().FindId(test.Id).One(&cicleDb)
	c.Assert(err, gocheck.IsNil)
	c.Assert(cicleDb, gocheck.DeepEquals, cicle2)
}

func (s *S) TestRemoveCicle(c *gocheck.C) {
	cicle := Cicle{Name: "Test maguro", Device: "maguro",
		Packages: []string{"bluetooth.jar", "wifi.jar"}}
	test, err := NewCicle(cicle)
	c.Assert(err, gocheck.IsNil)
	err = RemoveCicle(test.Id.Hex())
	c.Assert(err, gocheck.IsNil)
	lenght, err := db.Session.Cicle().FindId(test.Id).Count()
	c.Assert(err, gocheck.IsNil)
	c.Assert(lenght, gocheck.Equals, 0)
}


text:
package examples.stateful;

import java.util.List;

import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;

@Stateful
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public class EmployeeQueryBean implements EmployeeQuery {
    @PersistenceContext(type=PersistenceContextType.EXTENDED,
                        unitName="EmployeeService")
    EntityManager em;

    public List findAll() {
        return em.createQuery("SELECT e FROM Employee e")
                 .getResultList();
    }

    @Remove
    public void finished() {
    }
}


text:
#ifndef _CX3D_APPEARANCENODE_H_
#define _CX3D_APPEARANCENODE_H_

#include <cybergarage/x3d/VRML97Fields.h>
#include <cybergarage/x3d/Node.h>
#include <cybergarage/x3d/MaterialNode.h>
#include <cybergarage/x3d/TextureTransformNode.h>

namespace CyberX3D {

class AppearanceNode : public Node {

	SFNode *materialField;
	SFNode *textureField;
	SFNode *texTransformField;
	SFNode *linePropertiesField;
	SFNode *fillPropertiesField;

public:

	AppearanceNode();
	virtual ~AppearanceNode();

	////////////////////////////////////////////////
	//	SFNode Field
	////////////////////////////////////////////////

	SFNode *getMaterialField() const;
	SFNode *getTextureField() const ;
	SFNode *getTextureTransformField() const;
	SFNode *getLinePropertiesField() const;
	SFNode *getFillPropertiesField() const;

	////////////////////////////////////////////////
	//	List
	////////////////////////////////////////////////

	AppearanceNode *next() const;
	AppearanceNode *nextTraversal() const;

	////////////////////////////////////////////////
	//	virtual functions
	////////////////////////////////////////////////

	bool isChildNodeType(Node *node) const;
	void initialize();
	void uninitialize();
	void update();
	void outputContext(std::ostream &printStream, const char *indentString) const;
};

}

#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ExternalStorageConfigurationManager" enabled="true" />
  <component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="jbr-17" project-jdk-type="JavaSDK">
    <output url="file://$PROJECT_DIR$/out" />
  </component>
</project>


text:
package iht.forms.validators

import play.api.data.format.Formatter
import play.api.data.{FormError, Forms}

object OptionalCurrency extends Currency {
  /**
    * @param errorLengthKey                 if length > 10
    * @param errorInvalidCharsKey           e.g. $%^GG^,  AAbc
    * @param errorInvalidPenceKey           e.g. 6.898 or 885.50.60
    * @param errorInvalidSpacesKey          e.g. 33 45
    * @param errorInvalidCommaPositionKey   if comma in wrong place
    */
  private def optionalCurrencyFormatter(errorLengthKey: String,
                                        errorInvalidCharsKey: String,
                                        errorInvalidPenceKey: String,
                                        errorInvalidSpacesKey: String,
                                        errorInvalidCommaPositionKey: String) = new Formatter[Option[BigDecimal]] {
    override def bind(key: String, data: Map[String, String]): Either[Seq[FormError], Option[BigDecimal]] =
      data.get(key).fold("")(identity) match {
        case v if v.trim.isEmpty => Right(None)
        case v =>
          validationErrors(key, v, errorLengthKey, errorInvalidCharsKey, errorInvalidPenceKey,
                                    errorInvalidSpacesKey, errorInvalidCommaPositionKey: String) match {
            case Some(s) => Left(s)
            case None => Right(Option(BigDecimal(cleanMoneyString(v))))
          }
      }

    override def unbind(key: String, value: Option[BigDecimal]): Map[String, String] =
      Map(key -> value.getOrElse("").toString)
  }

  def apply(errorLengthKey: String = "error.estateReport.value.giveLessThanEleven",
            errorInvalidCharsKey: String = "error.estateReport.value.giveValueUsingNumbers",
            errorInvalidPenceKey: String = "error.estateReport.value.giveCorrectNumberOfPence",
            errorInvalidSpacesKey: String = "error.estateReport.value.giveWithNoSpaces",
            errorInvalidCommaPositionKey: String  = "error.estateReport.value.giveWithCorrectComma") =
    Forms.of(optionalCurrencyFormatter(errorLengthKey,
                                      errorInvalidCharsKey,
                                      errorInvalidPenceKey,
                                      errorInvalidSpacesKey,
                                      errorInvalidCommaPositionKey))
}


text:
module.exports = function(init, done) {
  task.helper('prompt', {}, [
    // Prompt for these values.
    task.helper('prompt_for', 'name'),
    task.helper('prompt_for', 'description'),
    task.helper('prompt_for', 'version'),
    task.helper('prompt_for', 'repository'),
    task.helper('prompt_for', 'homepage'),
    task.helper('prompt_for', 'bugs'),
    task.helper('prompt_for', 'licenses'),
    task.helper('prompt_for', 'author_name'),
    task.helper('prompt_for', 'author_email'),
    task.helper('prompt_for', 'author_url'),
    task.helper('prompt_for', 'node_version'),
    task.helper('prompt_for', 'node_main'),
    task.helper('prompt_for', 'node_test')
  ], function(err, props) {
    // Files to copy (and process).
    var files = [
      {src: 'grunt.js'},
      {src: 'README.md'},
      {src: 'lib/name.js', dest: 'lib/' + props.name + '.js'},
      {src: 'test/name_test.js', dest: 'test/' + props.name + '_test.js'}
    ];
    // Add properly-named license files.
    init.addLicenseFiles(files, props.licenses);
    // Actually copy (and process). files.
    init.copyAndProcess(files, props);

    // Generate package.json file.
    init.writePackage('package.json', props);

    // All done!
    done();
  });
};


text:
#region License Header
//
#endregion
namespace ProCenter.Infrastructure.Tests.Service.ReadSideService
{
    #region

    using System.Data;
    using System.Data.SqlClient;
    using System.Linq;
    using Common;
    using Infrastructure.Domain.Repositories;
    using Infrastructure.EventStore;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    using NEventStore.Dispatcher;

    using Pillar.Common.InversionOfControl;
    using Pillar.Common.Tests;

    using ProCenter.Domain.OrganizationModule;
    using ProCenter.Domain.PatientModule;
    using ProCenter.ReadSideService;

    #endregion

    [TestClass]
    public class HandleMessageTests
    {
        [TestMethod]
        public void IHandlerMessagesInheritsIHandlerMessage()
        {
            var commonInterface = typeof (IHandleMessages<>).GetInterfaces().FirstOrDefault(i => i == typeof (IHandleMessage));
            Assert.IsNotNull(commonInterface);
        }

        [TestMethod]
        public void CanRegisterAllEventsAndHandlers()
        {
            using (var serviceLocatorFixture = new ServiceLocatorFixture())
            {
                //Arrange
                SetServiceLocatorFixture(serviceLocatorFixture);

                var readSidePersistenceDispatcher = new ReadSidePersistenceDispatcher(IoC.CurrentContainer);

                //Act
                readSidePersistenceDispatcher.Execute();
                //var eventUpdaters = readSidePersistenceDispatcher.GetEventUpdaters;

                ////Assert
                //Assert.IsNotNull(eventUpdaters.FirstOrDefault(e => e.Key == typeof(AssessmentDefinitionCreatedEvent)));
                //Assert.IsNotNull(eventUpdaters.FirstOrDefault(e => e.Key == typeof(AssessmentCreatedEvent)));
                //Assert.IsNotNull(eventUpdaters.FirstOrDefault(e => e.Key == typeof(ItemUpdatedEvent)));
                //Assert.IsNotNull(eventUpdaters.FirstOrDefault(e => e.Key == typeof(AssessmentSubmittedEvent)));
                //Assert.IsNotNull(eventUpdaters.FirstOrDefault(e => e.Key == typeof(PatientCreatedEvent)));
                //Assert.IsNotNull(eventUpdaters.FirstOrDefault(e => e.Key == typeof(PatientChangedEvent)));
                //Assert.IsNotNull(eventUpdaters.FirstOrDefault(e => e.Key == typeof(RoleCreatedEvent)));
                //Assert.IsNotNull(eventUpdaters.FirstOrDefault(e => e.Key == typeof(RoleNameRevisedEvent)));
                //Assert.IsNotNull(eventUpdaters.FirstOrDefault(e => e.Key == typeof(StaffCreatedEvent)));
                //Assert.IsNotNull(eventUpdaters.FirstOrDefault(e => e.Key == typeof(StaffChangedEvent)));
                //Assert.IsNotNull(eventUpdaters.FirstOrDefault(e => e.Key == typeof(TeamCreatedEvent)));
                //Assert.IsNotNull(eventUpdaters.FirstOrDefault(e => e.Key == typeof(StaffAddedToTeamEvent)));
                //Assert.IsNotNull(eventUpdaters.FirstOrDefault(e => e.Key == typeof(PatientAddedToTeamEvent)));
                //Assert.IsNotNull(eventUpdaters.FirstOrDefault(e => e.Key == typeof(StaffRemovedFromTeamEvent)));
                //Assert.IsNotNull(eventUpdaters.FirstOrDefault(e => e.Key == typeof(PatientRemovedFromTeamEvent)));
            }
        }

        private static void SetServiceLocatorFixture(ServiceLocatorFixture serviceLocatorFixture)
        {
            serviceLocatorFixture.StructureMapContainer.Configure(c => c.For<IUnitOfWork>().Use<UnitOfWork>());
            serviceLocatorFixture.StructureMapContainer.Configure(c => c.For<IUnitOfWorkProvider>().Use<UnitOfWorkProvider>());
            serviceLocatorFixture.StructureMapContainer.Configure(c => c.For<IEventStoreFactory>().Use<EventStoreFactory>());
            serviceLocatorFixture.StructureMapContainer.Configure(c => c.For<IEventStoreRepository>().Use<EventStoreRepository>());
            serviceLocatorFixture.StructureMapContainer.Configure(c => c.For<IDetectConflicts>().Use<EmptyConflictDetector>());

            serviceLocatorFixture.StructureMapContainer.Configure(c => c.For<IDbConnectionFactory>().Use<FakeSqlConnectionFactory>());
            serviceLocatorFixture.StructureMapContainer.Configure(c => c.For<IStaffRepository>().Use<StaffRepository>());
            serviceLocatorFixture.StructureMapContainer.Configure(c => c.For<IPatientRepository>().Use<PatientRepository>());
            serviceLocatorFixture.StructureMapContainer.Configure(c => c.Scan(scanner =>
                {
                    scanner.AssembliesFromApplicationBaseDirectory(p => (p.FullName == null) ? false : p.FullName.Contains("ProCenter."));
                    scanner.AddAllTypesOf<IDispatchCommits>();
                    scanner.WithDefaultConventions();
                    scanner.AddAllTypesOf<IHandleMessage>();
                }));
        }
    }

    public class FakeSqlConnectionFactory : IDbConnectionFactory
    {
        public IDbConnection CreateConnection()
        {
            var sqlConnection = new SqlConnection();
            return sqlConnection;
        }
    }
}


text:
// Plato.NET
// Copyright (c) 2017 ReflectSoftware Inc.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

namespace Plato.Messaging.Interfaces
{
    /// <summary>
    ///
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public interface IMessageConnectionFactory<T> where T : class
    {
        /// <summary>
        /// Declares the connection.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        T CreateConnection(string name);
    }
}


text:
package com.netflix.spinnaker.halyard.cli.command.v1.config.canary.prometheus;

import com.beust.jcommander.Parameters;
import com.netflix.spinnaker.halyard.cli.command.v1.config.AbstractConfigCommand;
import com.netflix.spinnaker.halyard.cli.command.v1.config.canary.EnableDisableCanaryServiceIntegrationCommandBuilder;
import com.netflix.spinnaker.halyard.cli.command.v1.config.canary.prometheus.account.PrometheusCanaryAccountCommand;
import com.netflix.spinnaker.halyard.cli.services.v1.Daemon;
import com.netflix.spinnaker.halyard.cli.services.v1.OperationHandler;
import com.netflix.spinnaker.halyard.cli.ui.v1.AnsiFormatUtils;
import com.netflix.spinnaker.halyard.config.model.v1.canary.Canary;
import com.netflix.spinnaker.halyard.config.model.v1.canary.prometheus.PrometheusCanaryServiceIntegration;
import lombok.Data;
import lombok.EqualsAndHashCode;

@Parameters(separators = "=")
@Data
@EqualsAndHashCode(callSuper = false)
public class CanaryPrometheusCommand extends AbstractConfigCommand {

  String commandName = PrometheusCanaryServiceIntegration.NAME;

  String shortDescription =
      "Configure your canary analysis Prometheus service integration settings for Spinnaker.";

  public CanaryPrometheusCommand() {
    registerSubcommand(new EditCanaryPrometheusCommand());
    registerSubcommand(
        new EnableDisableCanaryServiceIntegrationCommandBuilder()
            .setName("Prometheus")
            .setEnable(true)
            .build());
    registerSubcommand(
        new EnableDisableCanaryServiceIntegrationCommandBuilder()
            .setName("Prometheus")
            .setEnable(false)
            .build());
    registerSubcommand(new PrometheusCanaryAccountCommand());
  }

  @Override
  protected void executeThis() {
    String currentDeployment = getCurrentDeployment();

    new OperationHandler<Canary>()
        .setOperation(Daemon.getCanary(currentDeployment, !noValidate))
        .setFailureMesssage("Failed to load canary settings.")
        .setSuccessMessage("Configured canary settings: ")
        .setFormat(AnsiFormatUtils.Format.STRING)
        .setUserFormatted(true)
        .get();
  }
}


text:
package me.chanjar.weixin.cp.api.impl;

import com.google.inject.Inject;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.ApiTestModule;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.oa.WxCpOaSchedule;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;

import java.util.Arrays;
import java.util.Collections;

/**
 * 单元测试类.
 *
 * @author Binary Wang created on  2020-12-25
 */
@Test
@Guice(modules = ApiTestModule.class)
public class WxCpOaScheduleServiceImplTest {
  /**
   * The Wx service.
   */
  @Inject
  protected WxCpService wxService;

  /**
   * Test add.
   *
   * @throws WxErrorException the wx error exception
   */
  @Test
  public void testAdd() throws WxErrorException {
    this.wxService.getOaScheduleService().add(new WxCpOaSchedule().setOrganizer("userid1")
      .setDescription("description").setStartTime(111111111111L).setEndTime(222222222222L)
      .setSummary("summary"), null);
  }

  /**
   * Test update.
   *
   * @throws WxErrorException the wx error exception
   */
  @Test
  public void testUpdate() throws WxErrorException {
    this.wxService.getOaScheduleService().update(new WxCpOaSchedule().setScheduleId("2222").setOrganizer("userid1")
      .setDescription("description").setStartTime(111111111111L).setEndTime(222222222222L)
      .setSummary("summary"));
  }

  /**
   * Test get details.
   *
   * @throws WxErrorException the wx error exception
   */
  @Test
  public void testGetDetails() throws WxErrorException {
    this.wxService.getOaScheduleService().getDetails(Collections.singletonList("11111"));
  }

  /**
   * Test delete.
   *
   * @throws WxErrorException the wx error exception
   */
  @Test
  public void testDelete() throws WxErrorException {
    this.wxService.getOaScheduleService().delete("111");
  }

  /**
   * Test list by calendar.
   *
   * @throws WxErrorException the wx error exception
   */
  @Test
  public void testListByCalendar() throws WxErrorException {
    this.wxService.getOaScheduleService().listByCalendar("111", null, null);
  }
}


text:
from prometheus_client import Gauge, start_http_server
import re
import logging

logger = logging.getLogger()

# pip install prometheus_client
# Docs at https://github.com/prometheus/client_python
class prometheus(object):
    def __init__(self, config, appname):
        try:
            port = int(config['prometheus'][appname]['server_port'])
        except (ValueError, KeyError):
            logger.warning('prometheus server_port not present in config. running without metrics.')
            self.enable_metrics = False
            return

        self.gauges = {}

        # per docs, app name in metric prefix needs to be one word
        self.appname = re.sub('[^a-zA-Z0-9]+', '', appname)

        logger.info('Starting prometheus metrics web server at %s', port)
        start_http_server(port)
        self.enable_metrics = True

    def send_metrics(self, metrics):
        if not self.enable_metrics:
            return
        for metric, value in metrics.iteritems():
            if metric not in self.gauges:
                self.gauges[metric] = Gauge(self.appname + '_' + metric, '')
            logger.info('Setting metrics gauge %s to %s', metric, value)
            self.gauges[metric].set_to_current_time()
            self.gauges[metric].set(value)