text:
package fieldmaskpb_test

import (
	"testing"

	"github.com/google/go-cmp/cmp"
	"github.com/google/go-cmp/cmp/cmpopts"
	"google.golang.org/protobuf/proto"

	testpb "google.golang.org/protobuf/internal/testprotos/test"
	fmpb "google.golang.org/protobuf/types/known/fieldmaskpb"
)

func TestAppend(t *testing.T) {
	tests := []struct {
		inMessage proto.Message
		inPaths   []string
		wantPaths []string
		wantError error
	}{{
		inMessage: (*fmpb.FieldMask)(nil),
		inPaths:   []string{},
		wantPaths: []string{},
	}, {
		inMessage: (*fmpb.FieldMask)(nil),
		inPaths:   []string{"paths", "paths"},
		wantPaths: []string{"paths", "paths"},
	}, {
		inMessage: (*fmpb.FieldMask)(nil),
		inPaths:   []string{"paths", "<INVALID>", "paths"},
		wantPaths: []string{"paths"},
		wantError: cmpopts.AnyError,
	}, {
		inMessage: (*testpb.TestAllTypes)(nil),
		inPaths:   []string{"optional_int32", "OptionalGroup.optional_nested_message", "map_uint32_uint32", "map_string_nested_message.corecursive", "oneof_bool"},
		wantPaths: []string{"optional_int32", "OptionalGroup.optional_nested_message", "map_uint32_uint32"},
		wantError: cmpopts.AnyError,
	}, {
		inMessage: (*testpb.TestAllTypes)(nil),
		inPaths:   []string{"optional_nested_message", "optional_nested_message.corecursive", "optional_nested_message.corecursive.optional_nested_message", "optional_nested_message.corecursive.optional_nested_message.corecursive"},
		wantPaths: []string{"optional_nested_message", "optional_nested_message.corecursive", "optional_nested_message.corecursive.optional_nested_message", "optional_nested_message.corecursive.optional_nested_message.corecursive"},
	}, {
		inMessage: (*testpb.TestAllTypes)(nil),
		inPaths:   []string{"optional_int32", "optional_nested_message.corecursive.optional_int64", "optional_nested_message.corecursive.<INVALID>", "optional_int64"},
		wantPaths: []string{"optional_int32", "optional_nested_message.corecursive.optional_int64"},
		wantError: cmpopts.AnyError,
	}, {
		inMessage: (*testpb.TestAllTypes)(nil),
		inPaths:   []string{"optional_int32", "optional_nested_message.corecursive.oneof_uint32", "optional_nested_message.oneof_field", "optional_int64"},
		wantPaths: []string{"optional_int32", "optional_nested_message.corecursive.oneof_uint32"},
		wantError: cmpopts.AnyError,
	}}

	for _, tt := range tests {
		t.Run("", func(t *testing.T) {
			var mask fmpb.FieldMask
			gotError := mask.Append(tt.inMessage, tt.inPaths...)
			gotPaths := mask.GetPaths()
			if diff := cmp.Diff(tt.wantPaths, gotPaths, cmpopts.EquateEmpty()); diff != "" {
				t.Errorf("Append() paths mismatch (-want +got):\n%s", diff)
			}
			if diff := cmp.Diff(tt.wantError, gotError, cmpopts.EquateErrors()); diff != "" {
				t.Errorf("Append() error mismatch (-want +got):\n%s", diff)
			}
		})
	}
}

func TestCombine(t *testing.T) {
	tests := []struct {
		in            [][]string
		wantUnion     []string
		wantIntersect []string
	}{{
		in: [][]string{
			{},
			{},
		},
		wantUnion:     []string{},
		wantIntersect: []string{},
	}, {
		in: [][]string{
			{"a"},
			{},
		},
		wantUnion:     []string{"a"},
		wantIntersect: []string{},
	}, {
		in: [][]string{
			{"a"},
			{"a"},
		},
		wantUnion:     []string{"a"},
		wantIntersect: []string{"a"},
	}, {
		in: [][]string{
			{"a"},
			{"b"},
			{"c"},
		},
		wantUnion:     []string{"a", "b", "c"},
		wantIntersect: []string{},
	}, {
		in: [][]string{
			{"a", "b"},
			{"b.b"},
			{"b"},
			{"b", "a.A"},
			{"b", "c", "c.a", "c.b"},
		},
		wantUnion:     []string{"a", "b", "c"},
		wantIntersect: []string{"b.b"},
	}, {
		in: [][]string{
			{"a.b", "a.c.d"},
			{"a"},
		},
		wantUnion:     []string{"a"},
		wantIntersect: []string{"a.b", "a.c.d"},
	}, {
		in: [][]string{
			{},
			{"a.b", "a.c", "d"},
		},
		wantUnion:     []string{"a.b", "a.c", "d"},
		wantIntersect: []string{},
	}}

	for _, tt := range tests {
		t.Run("", func(t *testing.T) {
			var masks []*fmpb.FieldMask
			for _, paths := range tt.in {
				masks = append(masks, &fmpb.FieldMask{Paths: paths})
			}

			union := fmpb.Union(masks[0], masks[1], masks[2:]...)
			gotUnion := union.GetPaths()
			if diff := cmp.Diff(tt.wantUnion, gotUnion, cmpopts.EquateEmpty()); diff != "" {
				t.Errorf("Union() mismatch (-want +got):\n%s", diff)
			}

			intersect := fmpb.Intersect(masks[0], masks[1], masks[2:]...)
			gotIntersect := intersect.GetPaths()
			if diff := cmp.Diff(tt.wantIntersect, gotIntersect, cmpopts.EquateEmpty()); diff != "" {
				t.Errorf("Intersect() mismatch (-want +got):\n%s", diff)
			}
		})
	}
}

func TestNormalize(t *testing.T) {
	tests := []struct {
		in   []string
		want []string
	}{{
		in:   []string{},
		want: []string{},
	}, {
		in:   []string{"a"},
		want: []string{"a"},
	}, {
		in:   []string{"foo", "foo.bar", "foo.baz"},
		want: []string{"foo"},
	}, {
		in:   []string{"foo.bar", "foo.baz"},
		want: []string{"foo.bar", "foo.baz"},
	}, {
		in:   []string{"", "a.", ".b", "a.b", ".", "", "a.", ".b", "a.b", "."},
		want: []string{"", "a.", "a.b"},
	}, {
		in:   []string{"e.a", "e.b", "e.c", "e.d", "e.f", "e.g", "e.b.a", "e$c", "e.b.c"},
		want: []string{"e.a", "e.b", "e.c", "e.d", "e.f", "e.g", "e$c"},
	}, {
		in:   []string{"a", "aa", "aaa", "a$", "AAA", "aA.a", "a.a", "a", "aa", "aaa", "a$", "AAA", "aA.a"},
		want: []string{"AAA", "a", "aA.a", "aa", "aaa", "a$"},
	}, {
		in:   []string{"a.b", "aa.bb.cc", ".", "a$b", "aa", "a.", "a", "b.c.d", ".a", "", "a$", "a$", "a.b", "a", "a.bb", ""},
		want: []string{"", "a", "aa", "a$", "a$b", "b.c.d"},
	}}

	for _, tt := range tests {
		t.Run("", func(t *testing.T) {
			mask := &fmpb.FieldMask{
				Paths: append([]string(nil), tt.in...),
			}
			mask.Normalize()
			got := mask.GetPaths()
			if diff := cmp.Diff(tt.want, got, cmpopts.EquateEmpty()); diff != "" {
				t.Errorf("Normalize() mismatch (-want +got):\n%s", diff)
			}
		})
	}
}

func TestIsValid(t *testing.T) {
	tests := []struct {
		message proto.Message
		paths   []string
		want    bool
	}{{
		message: (*testpb.TestAllTypes)(nil),
		paths:   []string{"no_such_field"},
		want:    false,
	}, {
		message: (*testpb.TestAllTypes)(nil),
		paths:   []string{""},
		want:    false,
	}, {
		message: (*testpb.TestAllTypes)(nil),
		paths: []string{
			"optional_int32",
			"optional_int32",
			"optional_int64",
			"optional_uint32",
			"optional_uint64",
			"optional_sint32",
			"optional_sint64",
			"optional_fixed32",
			"optional_fixed64",
			"optional_sfixed32",
			"optional_sfixed64",
			"optional_float",
			"optional_double",
			"optional_bool",
			"optional_string",
			"optional_bytes",
			"OptionalGroup",
			"optional_nested_message",
			"optional_foreign_message",
			"optional_import_message",
			"optional_nested_enum",
			"optional_foreign_enum",
			"optional_import_enum",
			"repeated_int32",
			"repeated_int64",
			"repeated_uint32",
			"repeated_uint64",
			"repeated_sint32",
			"repeated_sint64",
			"repeated_fixed32",
			"repeated_fixed64",
			"repeated_sfixed32",
			"repeated_sfixed64",
			"repeated_float",
			"repeated_double",
			"repeated_bool",
			"repeated_string",
			"repeated_bytes",
			"RepeatedGroup",
			"repeated_nested_message",
			"repeated_foreign_message",
			"repeated_importmessage",
			"repeated_nested_enum",
			"repeated_foreign_enum",
			"repeated_importenum",
			"map_int32_int32",
			"map_int64_int64",
			"map_uint32_uint32",
			"map_uint64_uint64",
			"map_sint32_sint32",
			"map_sint64_sint64",
			"map_fixed32_fixed32",
			"map_fixed64_fixed64",
			"map_sfixed32_sfixed32",
			"map_sfixed64_sfixed64",
			"map_int32_float",
			"map_int32_double",
			"map_bool_bool",
			"map_string_string",
			"map_string_bytes",
			"map_string_nested_message",
			"map_string_nested_enum",
			"oneof_uint32",
			"oneof_nested_message",
			"oneof_string",
			"oneof_bytes",
			"oneof_bool",
			"oneof_uint64",
			"oneof_float",
			"oneof_double",
			"oneof_enum",
			"OneofGroup",
		},
		want: true,
	}, {
		message: (*testpb.TestAllTypes)(nil),
		paths: []string{
			"optional_nested_message.a",
			"optional_nested_message.corecursive",
			"optional_nested_message.corecursive.optional_int32",
			"optional_nested_message.corecursive.optional_nested_message.corecursive.optional_nested_message.a",
			"OptionalGroup.a",
			"OptionalGroup.optional_nested_message",
			"OptionalGroup.optional_nested_message.corecursive",
			"oneof_nested_message.a",
			"oneof_nested_message.corecursive",
		},
		want: true,
	}, {
		message: (*testpb.TestAllTypes)(nil),
		paths:   []string{"repeated_nested_message.a"},
		want:    false,
	}, {
		message: (*testpb.TestAllTypes)(nil),
		paths:   []string{"repeated_nested_message[0]"},
		want:    false,
	}, {
		message: (*testpb.TestAllTypes)(nil),
		paths:   []string{"repeated_nested_message[0].a"},
		want:    false,
	}, {
		message: (*testpb.TestAllTypes)(nil),
		paths:   []string{"map_string_nested_message.a"},
		want:    false,
	}, {
		message: (*testpb.TestAllTypes)(nil),
		paths:   []string{`map_string_nested_message["key"]`},
		want:    false,
	}, {
		message: (*testpb.TestAllExtensions)(nil),
		paths:   []string{"nested_string_extension"},
		want:    false,
	}}

	for _, tt := range tests {
		t.Run("", func(t *testing.T) {
			mask := &fmpb.FieldMask{Paths: tt.paths}
			got := mask.IsValid(tt.message)
			if got != tt.want {
				t.Errorf("IsValid() returns %v want %v", got, tt.want)
			}
		})
	}
}


text:
package org.motechproject.mds.domain;

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

/**
 * The TypeSettingOption contains a single setting option for the given type setting.
 * This class is related with table in database with the same name.
 */
@PersistenceCapable(identityType = IdentityType.DATASTORE, detachable = "true")
public class TypeSettingOption {

    @Persistent(valueStrategy = IdGeneratorStrategy.NATIVE)
    @PrimaryKey
    private Long id;

    @Persistent
    private String name;

    public TypeSettingOption(String name) {
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>
<html>
  <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">
      <meta name="apple-mobile-web-app-capable" content="yes">
      <meta name="apple-touch-fullscreen" content="yes">
      <meta name="apple-mobile-web-app-status-bar-style" content="black">
      <link rel="stylesheet" type="text/css" href="styles/normalize.css">
      <link rel="stylesheet" type="text/css" href="styles/foundation.css">
      <link rel="stylesheet" type="text/css" href="styles/ionicons.css">
      <link rel="stylesheet" type="text/css" href="styles/style.css">
  </head>
  <body>
    <div id="app"/>
  </body>
  <script src="scripts/bundle.js"></script>
</html>


text:
package async.net.callback;

import java.io.IOException;

import async.net.http.HttpRequest;
import async.net.http.HttpResponse;

public interface HttpCallback {
	void call(HttpRequest request, HttpResponse response) throws IOException;

}


text:
import {LitElement, html} from "lit";
import LitUtils from "../../commons/utils/lit-utils.js";
import "../../commons/forms/data-form.js";

export default class VariantInterpreterGridConfig extends LitElement {

    constructor() {
        super();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            // FIXME Temporary object used to check CellBase version and hide RefSeq filter
            opencgaSession: {
                type: Object
            },
            config: {
                type: Object
            }
        };
    }

    connectedCallback() {
        super.connectedCallback();
    }

    update(changedProperties) {
        super.update(changedProperties);
    }

    onFieldChange(e) {
        switch (e.detail.param) {
            case "genotype.type":
                this.config.genotype.type = e.detail.value;
                break;
            case "showHgvs":
                this.config.showHgvs = e.detail.value;
                break;
            case "geneSet.ensembl":
            case "geneSet.refseq":
            case "consequenceType.all":
            case "consequenceType.maneTranscript":
            case "consequenceType.ensemblCanonicalTranscript":
            case "consequenceType.gencodeBasicTranscript":
            case "consequenceType.ccdsTranscript":
            case "consequenceType.lrgTranscript":
            case "consequenceType.ensemblTslTranscript":
            case "consequenceType.illuminaTSO500Transcript":
            case "consequenceType.eglhHaemoncTranscript":
            case "consequenceType.proteinCodingTranscript":
            case "consequenceType.highImpactConsequenceTypeTranscript":
            case "consequenceType.showNegativeConsequenceTypes":
            case "populationFrequenciesConfig.displayMode":
                const fields = e.detail.param.split(".");
                if (!this.config[fields[0]]) {
                    this.config[fields[0]] = {};
                }
                this.config[fields[0]][fields[1]] = e.detail.value;

                if (e.detail.param === "consequenceType.all") {
                    // we need to refresh the form to display disabled checkboxes
                    this.requestUpdate();
                }
                break;
            case "activeHighlights":
                this.config.activeHighlights = (e.detail.value || "").split(",").filter(v => v.length > 0);
                break;
        }

        LitUtils.dispatchCustomEvent(this, "configChange", this.config);
    }

    render() {
        return html`
            <data-form
                .data="${this.config}"
                .config="${this.getConfigForm()}"
                @fieldChange="${e => this.onFieldChange(e)}">
            </data-form>
        `;
    }

    getConfigForm() {
        return {
            id: "interpreter-grid-config",
            title: "",
            icon: "fas fa-user-md",
            type: "pills",
            validation: {
                validate: data => {
                    return data.geneSet?.ensembl || data.geneSet?.refseq;
                }
            },
            display: {
                width: 10,
                titleVisible: false,
                titleAlign: "left",
                titleWidth: 4,
                defaultLayout: "vertical",
                buttonsVisible: false
            },
            sections: [
                {
                    id: "gt",
                    title: "General Settings",
                    description: "Select some general options",
                    display: {
                        titleHeader: "h4",
                        titleStyle: "margin: 5px 5px",
                        descriptionClassName: "help-block",
                        descriptionStyle: "margin: 0px 10px",
                        visible: () => !!this.config?.genotype?.type
                    },
                    elements: [
                        {
                            title: "Select how genotypes are displayed",
                            field: "genotype.type",
                            type: "select",
                            allowedValues: ["ALLELES", "VCF_CALL", "ZYGOSITY", "VAF", "ALLELE_FREQUENCY", "ALLELE_FREQUENCY_BAR", "CIRCLE"],
                            display: {
                                width: 6,
                            }
                        },
                        {
                            title: "Show HGVS column",
                            field: "showHgvs",
                            type: "checkbox",
                            text: "Show HGVS",
                            display: {
                                width: 6,
                            }
                        }
                    ]
                },
                {
                    title: "Transcript Filter",
                    // description: "Select which transcripts and consequence types are displayed in the variant grid",
                    display: {
                        titleHeader: "h4",
                        titleStyle: "margin: 5px 5px",
                        descriptionClassName: "help-block",
                        descriptionStyle: "margin: 0px 10px"
                    },
                    elements: [
                        {
                            type: "text",
                            text: "Select the Gene Set to be displayed",
                            display: {
                                containerStyle: "margin: 5px 5px 5px 0px",
                                visible: () => this.opencgaSession?.project?.cellbase?.version.startsWith("v5")
                            }
                        },
                        {
                            field: "geneSet.ensembl",
                            type: "checkbox",
                            text: "Ensembl",
                            display: {
                                containerStyle: "margin: 10px 5px",
                                visible: () => this.opencgaSession?.project?.cellbase?.version.startsWith("v5")
                            }
                        },
                        {
                            field: "geneSet.refseq",
                            type: "checkbox",
                            text: "RefSeq",
                            display: {
                                containerStyle: "margin: 10px 5px",
                                visible: () => this.opencgaSession?.project?.cellbase?.version.startsWith("v5")
                            }
                        },
                        {
                            type: "text",
                            text: "Select which transcripts and consequence types are displayed in the variant grid",
                            display: {
                                containerStyle: "margin: 20px 5px 5px 0px"
                            }
                        },
                        {
                            field: "consequenceType.all",
                            type: "checkbox",
                            text: "Include All Transcripts",
                            display: {
                                containerStyle: "margin: 10px 5px",
                            }
                        },
                        {
                            type: "separator",
                            display: {
                                style: "margin: 5px 20px"
                            }
                        },
                        {
                            field: "consequenceType.maneTranscript",
                            type: "checkbox",
                            text: "Include MANE Select and Plus Clinical transcripts",
                            display: {
                                containerStyle: "margin: 10px 5px",
                                disabled: () => this.config?.consequenceType?.all
                            }
                        },
                        {
                            field: "consequenceType.ensemblCanonicalTranscript",
                            type: "checkbox",
                            text: "Include Ensembl Canonical transcripts",
                            display: {
                                containerStyle: "margin: 10px 5px",
                                disabled: () => this.config?.consequenceType?.all
                            }
                        },
                        {
                            field: "consequenceType.gencodeBasicTranscript",
                            type: "checkbox",
                            text: "Include GENCODE Basic transcripts",
                            display: {
                                containerStyle: "margin: 10px 5px",
                                disabled: () => this.config?.consequenceType?.all
                            }
                        },
                        {
                            field: "consequenceType.ccdsTranscript",
                            type: "checkbox",
                            text: "Include CCDS transcripts",
                            display: {
                                containerStyle: "margin: 10px 5px",
                                disabled: () => this.config?.consequenceType?.all
                            }
                        },
                        {
                            field: "consequenceType.lrgTranscript",
                            type: "checkbox",
                            text: "Include LRG transcripts",
                            display: {
                                containerStyle: "margin: 10px 5px",
                                disabled: () => this.config?.consequenceType?.all
                            }
                        },
                        {
                            field: "consequenceType.ensemblTslTranscript",
                            type: "checkbox",
                            text: "Include Ensembl TSL:1 transcripts",
                            display: {
                                containerStyle: "margin: 10px 5px",
                                disabled: () => this.config?.consequenceType?.all
                            }
                        },
                        {
                            field: "consequenceType.illuminaTSO500Transcript",
                            type: "checkbox",
                            text: "Include Illumina TSO500 transcripts",
                            display: {
                                containerStyle: "margin: 10px 5px",
                                disabled: () => this.config?.consequenceType?.all
                            }
                        },
                        {
                            field: "consequenceType.eglhHaemoncTranscript",
                            type: "checkbox",
                            text: "Include EGLH HaemOnc transcripts",
                            display: {
                                containerStyle: "margin: 10px 5px",
                                disabled: () => this.config?.consequenceType?.all
                            }
                        },
                        {
                            field: "consequenceType.proteinCodingTranscript",
                            type: "checkbox",
                            text: "Include protein coding transcripts",
                            display: {
                                containerStyle: "margin: 10px 5px",
                                disabled: () => this.config?.consequenceType?.all
                            }
                        },
                        {
                            field: "consequenceType.highImpactConsequenceTypeTranscript",
                            type: "checkbox",
                            text: "Include transcripts with high impact consequence types",
                            display: {
                                containerStyle: "margin: 10px 5px",
                                disabled: () => this.config?.consequenceType?.all
                            }
                        }
                    ]
                },
                {
                    title: "Population Frequencies",
                    // description: "Select which transcripts and consequence types are displayed in the variant grid",
                    display: {
                        titleHeader: "h4",
                        titleStyle: "margin: 5px 5px",
                        descriptionClassName: "help-block",
                        descriptionStyle: "margin: 0px 10px",
                        visible: true
                    },
                    elements: [
                        {
                            title: "Select the display mode of the population frequencies",
                            field: "populationFrequenciesConfig.displayMode",
                            type: "select",
                            multiple: false,
                            allowedValues: ["FREQUENCY_BOX", "FREQUENCY_NUMBER"],
                            display: {
                            },
                        },
                    ]
                },
                {
                    title: "Variant Highlight",
                    display: {
                        titleHeader: "h4",
                        titleStyle: "margin: 5px 5px",
                    },
                    elements: [
                        {
                            title: "Configure the highlight to apply to displayed variant rows",
                            field: "activeHighlights",
                            type: "select",
                            multiple: true,
                            allowedValues: this.config?.highlights?.map(highlight => highlight.id) || [],
                            display: {
                                visible: () => (this.config?.highlights || []).length > 0,
                            },
                        },
                        {
                            type: "notification",
                            text: "No highlight conditions defined.",
                            display: {
                                notificationType: "warning",
                                visible: () => (this.config?.highlights || []).length === 0,
                            },
                        },
                    ],
                },
            ]
        };
    }

}

customElements.define("variant-interpreter-grid-config", VariantInterpreterGridConfig);


text:
	<title>Travel</title>
	<link rel ="stylesheet" type="text/css" href="sample.css" />

Travel

	<?php
		$destination = $_POST['destination'];
		$numTravelers = $_POST['numTravelers'];
		$numNights = $_POST['numNights'];

		$tickets =
		$hotel =
		$totalCost = $tickets + $hotel;

		print("
Destination: $destination
");
		print("Number of people: $numTravelers
");
		print("Number of nights: $numNights
");
		print("Airline Tickets: $".number_format($tickets, 2)."
");
		print("Hotel Charges: $".number_format($hotel, 2)."
");
		print("
TOTAL COST: $".number_format($totalCost, 2)."
");

	?>


text:
using Benchmark._3._2._1;
using Benchmark.HashParser;
using BenchmarkDotNet.Attributes;
#pragma warning disable 1591

namespace BCrypt.Net.Benchmarks
{
    [MemoryDiagnoser]
    [RPlotExporter, RankColumn]
    [KeepBenchmarkFiles]
    public class InterrogateHashBenchmarks
    {

        [Benchmark(Baseline = true)]
        [Arguments("$2a$12$k42ZFHFWqBp3vWli.nIn8uYyIkbvYRvodzbfbK18SSsY.CsIQPlxO")]
        [Arguments( "$2a$10$fVH8e28OQRj9tqiDXs1e1uxpsjN0c7II7YPKXua2NAKYvM6iQk7dq")]
        public void InterrogateHashUsingRegex(string hash)
        {
            BaseLine.BCrypt.InterrogateHash(hash);
        }

        [Benchmark()]
        [Arguments("$2a$12$k42ZFHFWqBp3vWli.nIn8uYyIkbvYRvodzbfbK18SSsY.CsIQPlxO")]
        [Arguments( "$2a$10$fVH8e28OQRj9tqiDXs1e1uxpsjN0c7II7YPKXua2NAKYvM6iQk7dq")]
        public void InterrogateHashUsingParser(string hash)
        {
            Decoder.GetHashInformation(hash);
        }

    }
}


text:
class RenameResponsesToReplies < ActiveRecord::Migration
  def up
    # Responses Table
    rename_column :responses, :response_state_cd, :reply_state_cd
    remove_index :responses, :discussion_id

    rename_table :responses, :replies
    add_index :replies, :discussion_id

    # Discussion Table
    rename_column :discussions, :allows_title_responses, :allows_title_replies
    rename_column :discussions, :allows_url_responses, :allows_url_replies
    rename_column :discussions, :allows_text_responses, :allows_text_replies
    rename_column :discussions, :responses_open, :replies_open
  end

  def down
    # Replies Table
    rename_column :replies, :reply_state_cd, :response_state_cd
    remove_index :replies, :discussion_id

    rename_table :replies, :responses
    add_index :responses, :discussion_id

    # Discussion Table
    rename_column :discussions, :allows_title_replies, :allows_title_responses
    rename_column :discussions, :allows_url_replies, :allows_url_responses
    rename_column :discussions, :allows_text_replies, :allows_text_responses
    rename_column :discussions, :replies_open, :responses_open
  end
end


text:
<template name="siteHeader">

    {{>loginButtons}}

      Weeks

        {{#each weeks}}
          Week {{this}}
        {{/each}}

    {{#if isAdmin currentUser}}

          Reset Password

    {{/if}}

</template>


text:
<?php
require_once("/etc/apache2/capstone-mysql/encrypted-config.php");
require_once("question.php");
$pdo = connectToEncryptedMySQL("/etc/apache2/data-design/jfindley2.ini");

$question = new Question(null, 1, 2, "Huh?", null);
$question->insert($pdo);
$question->setQuestionText("What?");
$question->update($pdo);
$question->delete($pdo);


text:
Wreath of Blades

**School** abjuration; **Level** magus 4, sorcerer/wizard 5, summoner 5, witch 5

**Casting Time** 1 standard action

**Components** V, S, F (four mithral daggers, each worth at least 502 gp each)

**Range** personal

**Target** you

**Area** 5-foot-radius emanation centered on you

**Duration** 1 round/level

**Saving Throw** Reflex half (special, see below); **Spell Resistance** no (special, see below)

The daggers serving as focus of this spell take on a deadly sharpness as they animate and spin around you, creating a 5-foot-radius emanation of spinning mithral blades that moves with you. Any creature that starts its turn within the area of the spinning blades takes 1d4 points of damage for every two caster levels (maximum 10d4 at 20th level) and the damage bypasses DR/silver.

Furthermore, the daggers ward off some attacks, in a way similar to the _ [warding weapon](wardingWeapon#_warding-weapon)_ spell. While subject to this spell, you do not provoke attacks of opportunity for casting spells, even from creatures with the [Disruptive](feats#_disruptive) feat. Creatures with the [Spellbreaker](feats#_spellbreaker) feat can easily bypass this defensive property, though they still take damage from the spell. Your casting (even failing to cast defensively) still provokes attacks of opportunity from creatures with that feat.

Lastly, the blades that serve as the focus for this spell can be enchanted for greater effect. When all of the blades share the same enhancement bonus and special weapon qualities, a creature that is damaged by this spell is also treated as if hit by one of these weapons. For example, if a 12th-level magus casts this spell using four _+1 [frost](magicItems/weapons#_weapons-frost) mithral daggers_ as focus, the damage dealt by the blades would be 6d4+1 plus 1d6 cold damage, as long as the daggers were commanded to be sheathed in ice. No matter the modifications made to the focus weapons, they must always be mithral daggers. No other type of weapons can serve as a focus for this spell.


text:
var fs = require('fs'),
    vows = require('vows'),
    assert = require('assert'),

    common = require('../common.js'),
    immortal = require(common.immortal);

common.reset();

var outputFile = common.temp('output.txt');
var pidFile = common.temp('daemon.txt');

if (common.existsSync(outputFile)) fs.unlinkSync(outputFile);
if (common.existsSync(pidFile)) fs.unlinkSync(pidFile);

// null pid object
var pidInfo = {
  daemon: null,
  monitor: null,
  process: null
};

vows.describe('testing default monitor with pidFile:null').addBatch({

  'when starting immortal': {
    topic: function () {
      var self = this;

      // open file watchers
      immortal.start(common.fixture('pingping.js'), {
        strategy: 'development',
        options: {
          output: outputFile,
          pidFile: null
        }
      }, function (error) {
        setTimeout(function () {
          self.callback(error, null);
        }, 500);
      });
    },

    'no errors should exist': function (error, dum) {
      assert.ifError(error);
      assert.isNull(dum);
    },

    'a output file should exist': function () {
      assert.isTrue(common.existsSync(outputFile));
    },

    'a pid file should not exist': function () {
      assert.isFalse(common.existsSync(pidFile));
    },
  }

}).addBatch({

  'the content of the output file': {
    topic: function () {
      var self = this;

      fs.readFile(outputFile, 'utf8', function (error, content) {
        if (error) return self.callback(error, null);

        // parse lines
        var lines = content.split('\n');
        var pids = lines
          .filter(function (line) {
            return (line.indexOf('#') !== -1);
          })
          .map(function (line) {
            return parseInt( (line).match(/#([0-9]+)/)[1], 10);
          });

        pidInfo.monitor = pids[0];
        pidInfo.process = pids[1];

        self.callback(null, lines);
      });
    },

    'output should contain monitor output': function (error, lines) {
      assert.ifError(error);

      // A better test exists in monitor-default.js
      assert.equal(lines[0].indexOf('==='), 0);
      assert.equal(lines[1].indexOf('==='), 0);
      assert.equal(lines[2].indexOf('==='), 0);
      assert.equal(lines[3].indexOf('==='), 0);
    }
  }

}).addBatch({

  'cleanup: when trying to kill all pids': {
    topic: function () {
      var self = this;

        // Seriouse attempt to kill the immortal group
        // Should you really want that in production, please do it by
        // the session id (posix), the process tree (windows) or use monitor.shoutdown()
        var pidCache = pidInfo;
        var i = 3;
        while(i--) {
          try { process.kill(pidCache.monitor); } catch (e) {}
          try { process.kill(pidCache.process); } catch (e) {}
        }

        // Assume that every thing is killed after 500 ms
        setTimeout(function () {
          self.callback(null, pidCache);
        }, 500);
    },

    'all processors should be dead': function (error, pidCache) {
      assert.ifError(error);

      assert.isNull(pidCache.daemon);

      assert.isNumber(pidCache.monitor);
      assert.isFalse(common.isAlive(pidCache.monitor));

      assert.isNumber(pidCache.process);
      assert.isFalse(common.isAlive(pidCache.process));
    }
  }

}).exportTo(module);


text:
[![Build Status](https://travis-ci.org/protobuf-c/protobuf-c-text.png?branch=master)](https://travis-ci.org/protobuf-c/protobuf-c-text)

# Protobuf Text Format Support for C

Python, C++ and Java protobufs support text format but C protobufs did not.
This is a project that fixed that. It is a supplement to the
`libprotobuf-c` library in the [protobuf-c](https://github.com/protobuf-c)
project.

If you want to just get started using it, grab the code, run
`./configure && make && sudo make install` and then read the
[docs](http://text.protobuf-c.io/).

## Contents

The `protobuf-c-text/` directory has the code for the library.  Tests
are in `t/`.

## Dependencies

The [re2c](http://re2c.org/) parser is required to generate the
lexer (`parser.re`).

Coverage needs the `lcov` tool.

Documentation needs the `doxygen` and `graphviz` tools.

## Testing

The `t/c-*` programs use the `BROKEN_MALLOC` and `BROKEN_MALLOC_SEGV`
environment vars to control when and how malloc will fail.
The `BROKEN_MALLOC` var is set to the number of times for malloc to
succeed until it fails.  When the `BROKEN_MALLOC_SEGV` var is set the
test program will segfault on the first failure.  This is useful for
tracking down errors.

Note that the error message will print out the `gdb` line and the `run`
command you need to issue to reproduce the error.

## Useful make Targets

Beyond the normal autotools make targets, the following useful targets
exist:

* `coverage-html`: If you ran `./configure --enable-gcov` this will
  generate test code coverage reports along with marked up source
  files to show what is missing.
* `analyze`: If `clang` is on your system the static analyzer from the
  llvm project will be run.
* `doxygen-doc`: This will generate local versions of the
  [docs](http://text.protobuf-c.io/) available online.  They'll be found
  in `docs/html`.

## Maintainer Notes

`make gh-pages` notes:

The initial steps was done as follows.  This should not need to be repeated
but is documented here for future projects.

```bash
mkdir foo
git checkout --orphan gh-pages
GIT_INDEX_FILE=$PWD/.git/index.gh-pages git --work-tree foo status
touch foo/.nojekyll
GIT_INDEX_FILE=$PWD/.git/index.gh-pages git --work-tree foo add .nojekyll
GIT_INDEX_FILE=$PWD/.git/index.gh-pages git --work-tree foo commit -m 'Turn off Jekyll'
git checkout master
rm -rf foo
```

Subsequent updates are done like so (starting in `master`):

```bash
./configure --enable-gcov
make clean doxygen-doc coverage-html
GIT_INDEX_FILE=$PWD/.git/index.gh-pages git --work-tree $PWD/docs/html checkout gh-pages
GIT_INDEX_FILE=$PWD/.git/index.gh-pages git --work-tree $PWD/docs/html checkout .nojekyll
GIT_INDEX_FILE=$PWD/.git/index.gh-pages git --work-tree $PWD/docs/html checkout CNAME
GIT_INDEX_FILE=$PWD/.git/index.gh-pages git --work-tree $PWD/docs/html add .
GIT_INDEX_FILE=$PWD/.git/index.gh-pages git --work-tree $PWD/docs/html ls-files --deleted | GIT_INDEX_FILE=$PWD/.git/index.gh-pages xargs git --work-tree $PWD/docs/html rm
GIT_INDEX_FILE=$PWD/.git/index.gh-pages git --work-tree $PWD/docs/html commit -m "Update docs."
git checkout master
git push
```

Note that all references to files are done relative to the dir specified
in `--work-tree`.  Changing dir into that would make things easier, but
the `--work-tree` flag still needs to be set as would `GIT_INDEX_FILE`.

Also for reference,
[github pages docs](https://help.github.com/categories/20/articles)
are quite handy.


text:
namespace net {

DhcpProxyScriptFetcherFactory::DhcpProxyScriptFetcherFactory()
    : feature_enabled_(false) {
  set_enabled(true);
}

scoped_ptr<DhcpProxyScriptFetcher> DhcpProxyScriptFetcherFactory::Create(
    URLRequestContext* context) {
  if (!feature_enabled_) {
    return make_scoped_ptr(new DoNothingDhcpProxyScriptFetcher());
  } else {
    DCHECK(IsSupported());
    scoped_ptr<DhcpProxyScriptFetcher> ret;
#if defined(OS_WIN)
    ret.reset(new DhcpProxyScriptFetcherWin(context));
#endif
    DCHECK(ret);
    return ret.Pass();
  }
}

void DhcpProxyScriptFetcherFactory::set_enabled(bool enabled) {
  if (IsSupported()) {
    feature_enabled_ = enabled;
  }
}

bool DhcpProxyScriptFetcherFactory::enabled() const {
  return feature_enabled_;
}

// static
bool DhcpProxyScriptFetcherFactory::IsSupported() {
#if defined(OS_WIN)
  return true;
#else
  return false;
#endif
}

}  // namespace net


text:
/*
 * XML Type:  nameType
 * Namespace: http://xmlbeans.apache.org/samples/validation/todolist
 * Java type: org.apache.xmlbeans.samples.validation.todolist.NameType
 *
 * Automatically generated - do not modify.
 */
package org.apache.xmlbeans.samples.validation.todolist.impl;
/**
 * An XML nameType(@http://xmlbeans.apache.org/samples/validation/todolist).
 *
 * This is an atomic type that is a restriction of org.apache.xmlbeans.XmlString.
 */
public class NameTypeImpl extends org.apache.xmlbeans.impl.values.JavaStringHolderEx implements org.apache.xmlbeans.samples.validation.todolist.NameType
{

    public NameTypeImpl(org.apache.xmlbeans.SchemaType sType)
    {
        super(sType, false);
    }

    protected NameTypeImpl(org.apache.xmlbeans.SchemaType sType, boolean b)
    {
        super(sType, b);
    }
}


text:
package index

import (
	"bytes"
	"fmt"
	"io"
	"sort"
	"sync"

	segment "github.com/blugelabs/bluge_segment_api"
)

type InMemoryDirectory struct {
	segLock  sync.RWMutex
	segments map[uint64]*bytes.Buffer
}

func NewInMemoryDirectory() *InMemoryDirectory {
	return &InMemoryDirectory{
		segLock:  sync.RWMutex{},
		segments: make(map[uint64]*bytes.Buffer),
	}
}

func (d *InMemoryDirectory) Setup(readOnly bool) error {
	return nil
}

func (d *InMemoryDirectory) List(kind string) ([]uint64, error) {
	d.segLock.RLock()
	defer d.segLock.RUnlock()
	var rv uint64Slice
	if kind == ItemKindSegment {
		for id := range d.segments {
			rv = append(rv, id)
		}
	}

	sort.Sort(sort.Reverse(rv))
	return rv, nil
}

func (d *InMemoryDirectory) Load(kind string, id uint64) (*segment.Data, io.Closer, error) {
	d.segLock.RLock()
	defer d.segLock.RUnlock()
	if kind == ItemKindSegment {
		if buf, ok := d.segments[id]; ok {
			return segment.NewDataBytes(buf.Bytes()), nil, nil
		}
		return nil, nil, fmt.Errorf("segment %d not found", id)
	}

	return nil, nil, nil
}

func (d *InMemoryDirectory) Persist(kind string, id uint64, w WriterTo, closeCh chan struct{}) error {
	d.segLock.Lock()
	defer d.segLock.Unlock()
	if kind == ItemKindSegment {
		var buf bytes.Buffer
		_, err := w.WriteTo(&buf, closeCh)
		if err != nil {
			return err
		}
		d.segments[id] = &buf
	}
	return nil
}

func (d *InMemoryDirectory) Remove(kind string, id uint64) error {
	d.segLock.Lock()
	defer d.segLock.Unlock()
	if kind == ItemKindSegment {
		delete(d.segments, id)
	}
	return nil
}

func (d *InMemoryDirectory) Stats() (numItems, numBytes uint64) {
	return 0, 0
}

func (d *InMemoryDirectory) Sync() error {
	return nil
}

func (d *InMemoryDirectory) Lock() error {
	return nil
}

func (d *InMemoryDirectory) Unlock() error {
	return nil
}


text:
			<button ng-click="headerC.openOrClose()" class="navbar-toggle collapsed pull-left" style="margin-left: 5px;" data-toggle="collapse" data-target="#menu">
				Menu

			</button>

	<form class="navbar-form navbar-left">

			<input type="text" class="form-control" placeholder="Procure por emails">

				<button type="button" class="btn btn-default"></button>

	</form>


text:
<!doctype html>

    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="css/common.css">
    <link rel="stylesheet" href="css/main.css">

<form action="index.php?r=account/add" method="post"  enctype="multipart/form-data"  class="jqtransform">

        <input type="hidden" name="_csrf" value="<?=\Yii::$app->request->csrfToken?>"/>

            *公众号名称:

                <input class="input-text lh30" id="title" name="aname" size="50" value="" type="text" placeholder="请输入公众号名称">
                <?php if(!empty($error_data))echo $error_data['aname'][0]?>

            Appid:

                <input class="input-text lh30" name="appid" size="50" placeholder="请输入Appid" type="text">
                <?php if(!empty($error_data))echo $error_data['appid'][0]?>

            Appsecret:

                <input class="input-text lh30" name="appsecret" size="50" placeholder="请输入appsecret" type="text">
                <?php if(!empty($error_data))echo $error_data['appsecret'][0]?>

            内容:

                <textarea name="account" class="common-textarea" id="content" cols="30" style="width: 98%;" rows="10"></textarea>
                <?php if(!empty($error_data))echo $error_data['account'][0]?>

                <input type="submit"  class="btn btn82 btn_save2" value="提交">
                <input type="button" value="返回" onclick="location.href='javascript:history.go(-1)'"
                       class="ext_btn">

</form>


text:
define(["js/core/Bindable", "flow"], function (Bindable, flow) {

    var routeStripper = /^#?!?\/?/,
        undefined,
        emptyCallback = function () {
        };

    /***
     * @summary The History listens to the browsers history and calls the routers when the fragment has changed
     * It also allows to navigate to a given fragment.
     *
     */
    var History = Bindable.inherit("js.core.History", {

        ctor: function () {
            this.callBase();
            this.$routers = [];
            this.$processUrl = true;

            this.$history = [];

            if (this.$.useState === null) {
                this.set("useState", (this.runsInBrowser() && ("onpopstate" in window)));
            }
        },

        defaults: {
            /**
             * The polling interval for the URL hash if onhashchange is not supported
             * @type Number
             */
            interval: 50,

            /***
             * should the push and pop state api be used
             */
            useState: false,

            baseUrl: "/"
        },

        /***
         * @Bindable
         * @return {String}
         */
        fragment: function() {
            return this.$fragment;
        }.on('change:fragment'),

        /***
         * determinate the current fragment
         * @return {String} the current fragment without the starting #/
         * @private
         */
        _getFragment: function () {
            var fragment;

            if (this.runsInBrowser()) {

                if (this.$.useState) {
                    fragment = (window.history.state || {}).fragment || "";
                } else {
                    fragment = decodeURI(window.location.hash);
                }

            } else {
                fragment = this.$history[this.$history.length - 1] || "";
            }

            return fragment.replace(routeStripper, '');
        },
        /***
         * This method is called to start the history
         * @param {Function} callback - get's called after the navigation is completed
         * @param {String} initialHash
         */
        start: function (callback, initialHash) {

            var self = this,
                fragment;

            this.$checkUrlFn = function () {
                self.checkUrl.apply(self, arguments);
            };

            if (this.runsInBrowser()) {
                // we're in a browser

                if (this.$.useState) {

                    fragment = window.location.pathname;
                    fragment = fragment.replace(new RegExp("^" + (this.$.baseUrl || "")), "");

                    if (window.addEventListener) {
                        window.addEventListener('popstate', this.$checkUrlFn, false);
                    } else {
                        window.attachEvent('onpopstate', this.$checkUrlFn);
                    }

                } else {

                    if ("onhashchange" in window) {
                        if (window.addEventListener) {
                            window.addEventListener('hashchange', this.$checkUrlFn, false);
                        } else {
                            window.attachEvent('onhashchange', this.$checkUrlFn);
                        }
                    } else {
                        // polling
                        this.$checkUrlInterval = setInterval(this.$checkUrlFn, this.$.interval);
                    }
                }

            } else {
                // rendering on node
                this.$history.push(initialHash || "");
            }

            fragment = fragment || this._getFragment();

            this.navigate(fragment, false, true, true, callback);
            this.$processUrl = true;
        },

        /**
         * Navigates back with the browsers history
         *
         */
        back: function(){
            window.history.back();
        },

        /***
         * Removes all onhaschange listeners or clears polling interval for hash check
         */
        stop: function () {
            if (typeof window !== "undefined") {

                if (this.$.useState) {
                    if (window.removeEventListener) {
                        window.removeEventListener('popstate', this.$checkUrlFn, false);
                    } else {
                        window.detachEvent('onpopstate', this.$checkUrlFn);
                    }
                } else {
                    if ("onhashchange" in window) {
                        if (window.removeEventListener) {
                            window.removeEventListener('hashchange', this.$checkUrlFn, false);
                        } else {
                            window.detachEvent('onhashchange', this.$checkUrlFn);
                        }
                    } else {
                        // polling
                        clearInterval(this.$checkUrlInterval);
                    }
                }
            }
        },

        /**
         * Adds a router to the history instance
         *
         * @param router
         */
        addRouter: function (router) {
            this.$routers.push(router);
        },

        /**
         * Checks if the current fragment has changed and calls navigate in case it did
         *
         */
        checkUrl: function () {

            if (this.$processUrl) {
                var currentFragment = this._getFragment();
                if (currentFragment == this.$fragment) {
                    return false;
                }

                this.navigate(currentFragment, !this.$.useState, true, true, emptyCallback);
            }

            this.$processUrl = true;

        },
        /**
         * Triggers a route
         *
         * @param {String} fragment - the fragment which should be triggered
         * @param {Function} callback - gets called after the route execution stack is done
         */
        triggerRoute: function (fragment, callback) {

            var routeExecutionStack = [];

            for (var i = 0; i < this.$routers.length; i++) {
                routeExecutionStack = routeExecutionStack.concat(this.$routers[i].generateRoutingStack(fragment));
            }

            if (routeExecutionStack.length === 0) {
                this.routeNotFound(fragment, callback);
            } else {
                flow()
                    .seqEach(routeExecutionStack, function(routingFunction, cb){
                        routingFunction(cb);
                    })
                    .exec(callback);
            }
        },

        routeNotFound: function(fragment, callback) {
            this.log("no route for '" + fragment + "' found.");
            // no route found but

            if (callback) {
                // execute callback
                callback();
            }
        },

        /***
         * Navigates to a fragment
         * @param {String} fragment
         * @param {Boolean} [createHistoryEntry] - default true
         * @param {Boolean} [triggerRoute] - default true
         * @param force
         * @param {Function} callback - navigate callback
         */
        navigate: function (fragment, createHistoryEntry, triggerRoute, force, callback) {

            var self = this;

            if (!callback && createHistoryEntry instanceof Function) {
                callback = createHistoryEntry;
                createHistoryEntry = null;
            }

            if (!callback && triggerRoute instanceof Function) {
                callback = triggerRoute;
                triggerRoute = null;
            }

            if (!callback && force instanceof Function) {
                callback = force;
                force = null;
            }

            if (createHistoryEntry == undefined || createHistoryEntry === null) {
                createHistoryEntry = true;
            }

            if (triggerRoute == undefined || triggerRoute === null) {
                triggerRoute = true;
            }

            var eventData = {
                fragment: fragment,
                createHistoryEntry: createHistoryEntry,
                triggerRoute: triggerRoute
            };

            var urlChange = this._getFragment() !== fragment;

            if (!urlChange && !force) {
                callback && callback();
                return;
            }

            this.trigger(History.EVENTS.NAVIGATION_START, eventData);
            this.$processUrl = urlChange;

            if (createHistoryEntry) {
                if (this.runsInBrowser()) {
                    if (this.$.useState) {

                        console.log("Pushing " + fragment + " to history");

                        window.history.pushState({
                            fragment: "/" + fragment
                        }, null, this.$.baseUrl + fragment);
                    } else {
                        window.location.hash = "/" + encodeURI(fragment);
                    }
                } else {
                    this.checkUrl(null);
                }
                this.$history.push(fragment);
            } else {
                if (this.runsInBrowser()) {

                    if (this.$.useState) {

                        console.log("Replacing " + fragment + " to history");

                        window.history.replaceState({
                            fragment: "/" + fragment
                        }, null, this.$.baseUrl + fragment);
                    } else {
                        // replace hash
                        window.location.replace("#/" + fragment);
                    }
                }
                this.$history[this.$history.length - 1] = fragment;
            }

            this.$processUrl = true;

            if(this.$fragment !== fragment){
                this.$fragment = fragment;
                this.trigger('change:fragment', this.$fragment);
            }

            if (triggerRoute) {
                this.triggerRoute(fragment, function() {
                    self.trigger(History.EVENTS.NAVIGATION_COMPLETE, eventData);
                    if (callback) {
                        callback.apply(self, arguments);
                    }
                });
            } else {
                this.trigger(History.EVENTS.NAVIGATION_COMPLETE, eventData);
            }
        }
    });

    History.EVENTS = {
        NAVIGATION_START: "navigationStart",
        NAVIGATION_COMPLETE: "navigationComplete"
    };

    return History;
});


text:
published: true
category: vlive
tags: [Roa,Yehana]
---

170308 PRISTIN If Roa And Yehana Meets?


text:
module MenuRenderer

  def exclude(*type_names)
    @excluded_class_names ||= []
    @excluded_class_names.concat(type_names).uniq!
  end
  module_function :exclude

  def excluded_class_names
    MenuRenderer.instance_variable_get(:@excluded_class_names)
  end

  module_function :excluded_class_names
  public :excluded_class_names

  def view=(val)
    @view = val
  end

  def view
    @view
  end

  def additional_menu_features?
    @additional_menu_features ||= (menu_renderer_module_name != 'MenuRenderer' && Object.const_defined?(menu_renderer_module_name))
  end

  def menu_renderer_module_name
    simple_name = self.class_name.to_s.sub('Page','')
    "#{simple_name}MenuRenderer"
  end

  def menu_renderer_modules
    [Object.const_get(menu_renderer_module_name)]
  end

  def allowed_child_classes
    (allowed_children_cache.to_s.split(',') - Array(excluded_class_names)).map do |name|
      begin
        name.constantize
      rescue LoadError, NameError => e
        nil
      end
    end.compact
  end

  def default_child_item
    menu_item(default_child)
  end

  def separator_item
    view.content_tag :li, '', class: 'separator'
  end

  def child_items
    (allowed_child_classes - [self.class.default_child]).map do |child|
      menu_item(child)
    end
  end

  def menu_items
    [default_child_item, separator_item] + child_items
  end

  def menu_list
    view.content_tag :ul, menu_items.join.html_safe, class: 'menu', id: "allowed_children_#{id}"
  end

  def remove_link
    view.link_to view.image('minus') + ' ' + I18n.t('remove'), view.remove_admin_page_url(self), class: "action"
  end

  def remove_option
    remove_link
  end

  def add_child_disabled?
    allowed_child_classes.size == 0
  end

  def disabled_add_child_link
    view.content_tag :span, view.image('plus_disabled') + ' ' + I18n.t('add_child'), class: 'action disabled'
  end

  def add_child_link
    view.link_to((view.image('plus') + ' ' + I18n.t('add_child')), view.new_admin_page_child_path(self, page_class: default_child.name), class: "action")
  end

  def add_child_link_with_menu_hook
    view.link_to((view.image('plus') + ' ' + I18n.t('add_child')), "#allowed_children_#{id}", class: "action dropdown")
  end

  def add_child_menu
    menu_list
  end

  def add_child_link_with_menu
    add_child_link_with_menu_hook + add_child_menu
  end

  def add_child_option
    if add_child_disabled?
      disabled_add_child_link
    else
      if allowed_child_classes.size == 1
        add_child_link
      else
        add_child_link_with_menu
      end
    end
  end

  private

  def clean_page_description(page_class)
    page_class.description.to_s.strip.gsub(/\t/,'').gsub(/\s+/,' ')
  end

  def menu_item(child_class)
    view.content_tag(:li, menu_link(child_class))
  end

  def menu_link(child_class)
    title = clean_page_description(child_class)
    path = view.new_admin_page_child_path(self, page_class: child_class.name)
    text = link_text_for_child_class(child_class.name)
    view.link_to(text, path, title: title)
  end

  def link_text_for_child_class(given_class_name)
    translation_key = if given_class_name == 'Page' || given_class_name.blank?
      'normal_page'
    else
      given_class_name.sub('Page','').underscore
    end
    fallback = given_class_name == 'Page' ? 'Page' : given_class_name.sub('Page','').titleize
    I18n.t(translation_key, default: fallback)
  end
end


text:
#include <aws/ssm/model/DescribeEffectivePatchesForPatchBaselineResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::SSM::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

DescribeEffectivePatchesForPatchBaselineResult::DescribeEffectivePatchesForPatchBaselineResult()
{
}

DescribeEffectivePatchesForPatchBaselineResult::DescribeEffectivePatchesForPatchBaselineResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

DescribeEffectivePatchesForPatchBaselineResult& DescribeEffectivePatchesForPatchBaselineResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  JsonView jsonValue = result.GetPayload().View();
  if(jsonValue.ValueExists("EffectivePatches"))
  {
    Aws::Utils::Array<JsonView> effectivePatchesJsonList = jsonValue.GetArray("EffectivePatches");
    for(unsigned effectivePatchesIndex = 0; effectivePatchesIndex < effectivePatchesJsonList.GetLength(); ++effectivePatchesIndex)
    {
      m_effectivePatches.push_back(effectivePatchesJsonList[effectivePatchesIndex].AsObject());
    }
  }

  if(jsonValue.ValueExists("NextToken"))
  {
    m_nextToken = jsonValue.GetString("NextToken");

  }

  return *this;
}


text:
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import autobind from 'class-autobind';

import { loadAdminRoles } from 'actions';
import { TypeAheadInputRemote } from './typeahead_input_remote';

class RoleInput extends Component {
  constructor(props) {
    super(props);
    autobind(this);
  }

  loadData() {
    return new Promise((resolve, reject) => {
      this.props.loadAdminRoles().then((response) => {
        const data = response.data.map(d => ({
          id: d._id,
          label: d.name,
        }));

        resolve(data);
      }).catch(reject);
    });
  }

  render() {
    const { field, reduxField } = this.props;

    return (
      <TypeAheadInputRemote
        field={field}
        reduxField={reduxField}
        loadData={this.loadData}
      />
    );
  }
}

RoleInput.propTypes = {
  field: PropTypes.object.isRequired,
  reduxField: PropTypes.string,

  adminRoles: PropTypes.array.isRequired,
  loadAdminRoles: PropTypes.func.isRequired,
};

export const AdminRoleInput = connect(({ adminRoles }) => (
  { adminRoles }),
  { loadAdminRoles }
)(RoleInput);


text:
import { expect }        from 'chai'
import sinon             from 'sinon'
import { EntityManager } from '../../../src/core/entity-manager'
import { SystemType }    from '../../../src/core/system-manager'

describe('EntityManager', function() {
    describe('registerInitSystem(name, components, callback)', () => {
        beforeEach(() => {
            this.entityManager = new EntityManager(50)

            this.position = 'position'

            this.velocity = 'velocity'

            this.entityId = 0
            this.entity = {
                id: this.entityId,
                components: [ this.position, this.velocity, ],
                [this.position]: { x: 0, y: 0, },
                [this.velocity]: 2,
            }

            this.entityManager.entities[this.entityId] = this.entity
        })

        afterEach(() => {
            delete this.entityManager
        })

        test('is a function', () => {
            expect(this.entityManager.registerInitSystem).to.be.a('function')
        })

        test('invokes [systemManager.registerSystem] with [type] = SystemType.Init', () => {
            const spy = sinon.spy(this.entityManager.systemManager, 'registerSystem')

            const name       = 'initTestSystem'
            const components = [ this.position, this.velocity ]
            const callback   = (entities) => {
                for (const { entity } of entities) {
                    entity.position = { x : 5, y : 5 }
                    entity.velocity = -2
                }
            }

            const entityIds = [ this.entityId, ]

            this.entityManager.registerInitSystem(name, components, callback)

            expect(spy.calledOnce).to.be.true

            expect(spy.calledWith(SystemType.Init, name, components, entityIds, callback)).to.be.true
        })
    })
})


text:
/**
 * SnowflakeNode
 *
 * @author Kyle Scholz
 *
 * Represents a node in a Snowflake Graph.
 */
var SnowflakeNode = function( id, radius, fanAngle, rootAngle ) {
	this['relSize']=1;

	// Represents the angle of entry of this node's parent edge ...
	this['rootAngle'] = parseInt(rootAngle);

	// Each node knows it's parent.
	this['parent'];

	// Branch weight represents the weight of all of this node's children.
	this['branchWeight']=0;

	// A unique identifier
	this['id'] = id;

	// Indicates the radius (or length of edges rooted in this node)
	this['radius'] = radius;

	// Indicates the angle that can be filled with this nodes children.
    this['fanAngle'] = fanAngle;

	// Target Angle and Radius
	this.targetX = 0;
	this.targetY = 0;
	this.targetT = 0;
	this.targetR = 0;

	// Current Position
	this.positionX = 0;
	this.positionY = 0;
	this.positionT = 0;
	this.positionR = 0;

	// This node's children
	this['children'] = new Array();
}

/*
 * Increments this branch's weight.
 */
SnowflakeNode.prototype.incrementBranchWeight = function() {
	this.branchWeight++;
	if ( this.parent ) { this.parent.incrementBranchWeight(); }
}

/*
 * Adds a child to this node.
 */
SnowflakeNode.prototype.addChild = function( node ) {
	this['children'].push(node);
	node['parent'] = this;
	node.positionT = this['rootAngle'];
	this.incrementBranchWeight();
	this.updateChildren();
	return node;
}

/*
 * ...Doesn't actually destroy the node. The is a recursive method that
 * identifies all of the members of a branch and breaks parent-child
 * relationships.
 */
SnowflakeNode.prototype.destroy = function() {
	var destroyed = [];
	for ( var i=0; i<this['children'].length; i++ ) {
		destroyed.push( this['children'][i].id );
		this['children'][i].parent = null;
		destroyed = destroyed.concat( this['children'][i].destroy() );
	}
	this.children = [];
	return destroyed;
}

/*
 * Seperate node from it's parent
 */
SnowflakeNode.prototype.emancipate = function() {
	if ( this.parent ) {
		for( var i=0, l=this.parent.children.length; i<l; i++ ) {
			if ( this.parent.children[i]==this ) {
				this.parent.children.splice(i,1);
			}
		}
	}
	this.parent = null;
}

/*
 * Updates target positions for a set of child nodes any time the set of
 * child nodes changes.
 */
SnowflakeNode.prototype.updateChildren = function() {
	var partitions = 0;
	for ( var i=0; i<this['children'].length; i++ ) {
		partitions += this['children'][i].relSize;
	}

	// for each child node, calculate a new target
	for ( var i=0, l=this['children'].length; i<l; i++ ) {
		var angle;

		// Make an "only child" follow it's parent's path.
		if ( this['children'].length == 1 ) {
			angle=this['rootAngle'];
			// Otherwise, theta is a function of the number of child nodes and
			// the fanAngle that has been specified that they must fit in.
			// ...place the child in the middle of it's partition
		} else {
			angle=(this['fanAngle']/(partitions)*i) + this['rootAngle'] -
			(this['fanAngle']/(partitions)*(partitions-1))/2;
		}
		var node = this['children'][i];
		node.rootAngle = parseInt(angle);
		node.targetT = angle;
		node.targetR = this['radius'];
		node.updateChildren();
	}
}

/**
 * SnowflakeGraphModel:
 *
 * Performs positioning on nodes.
 *
 * @extends GraphModel
 */
var SnowflakeGraphModel = function( view ) {
	this.view=view;

	this.nodes={};
	this.selected = null;

	this.timer = new Timer( 1 );
	this.timer.subscribe( this );

	// A collection  of root nodes
	this.updateQueue = new Array();

	this.updateCollection = {};

	//
	this.nextUID = 0;

	// A constant that dictates the smoothness of animation. We'll always make a
	// tradeoff between smoothness and speed (or resource utilization). For
	// different graph applications, different fluidity values will be
	// appropriate.
	//
	// In this animation, fluidity is used to controls the distance traversed in
	// each tick, in the functions: newTheta=(theta-targetTheta)/
	this.fluidity = 2.5;

	// A boolean that indicates whether this graph should stagger node positions
	// for readability.
	this.doStagger = false;

	this.staggerPixels = 30;
}

/*
 * Start animation timer.
 */
SnowflakeGraphModel.prototype.start = function() {
	this.timer.start();
}

/*
 * Stop animation timer.
 */
SnowflakeGraphModel.prototype.stop = function() {
	this.timer.stop();
}

/*
 * Perform an animation tick.
 */
SnowflakeGraphModel.prototype.update = function() {
	var m = 0;
	for( var i=0; i<this.updateQueue.length; i++ ) {
		m = this.setNodePosition( this.updateQueue[i] );
	}
	if ( m == 0 ) {	return 100; }
	return 1;
}

/*
 * Move node closer to target.
 */
SnowflakeGraphModel.prototype.setNodePosition = function( node, force, i ) {
	var m = 0;
	if (!i) { i=0; }
	if ( node.parent ) {
		var dt = (node.positionT - node.targetT);
		var dr = (node.positionR - node.targetR);

		if ( force || ((Math.abs(dt)>1 || Math.abs(dr)>1) && !(this.selected==node.id)) ) {
			node.positionT -= (dt / this['fluidity']);
			node.positionR -= (dr / this['fluidity']);

			// Determine if we should stagger
			var stagger = 0;
			if ( this.doStagger && i % 2 ) { stagger = this.staggerPixels; }

			// Set coordinates based on angle and radius
			node.positionY = node.parent.positionY -
				(Math.cos(node.positionT*(Math.PI/180)) *
				(node.positionR+stagger));

		    node.positionX = node.parent.positionX -
				(Math.sin(node.positionT*(Math.PI/180)) *
				(node.positionR+stagger));

			this.view.drawNode( node );
			m = 1;
		} else if ( this.selected == node.id ) {
			this.view.drawNode( node );
		}
	} else {
		// are we migrating a root node?
		// Get new coordinate values for this node
		var dx = (node.positionX - node.targetX);
		var dy = (node.positionY - node.targetY);

		if ( force || (Math.abs(dx)>1 || Math.abs(dy)>1) ) {
			node.positionX -= (dx / this['fluidity']);
			node.positionY -= (dy / this['fluidity']);
			node.updateChildren();
			this.view.drawNode( node );
		}
	}

	for ( var i=0, l=node.children.length; i<l; i++ ) {
		m += this.setNodePosition( node['children'][i], force, i );
	}
	return m;
}

/*
 * Add a new SnowflakeNode.
 */
SnowflakeGraphModel.prototype.addNode = function( radius, fanAngle, rootAngle ) {
	var id = this['nextUID']++;
	var node = new SnowflakeNode( id, radius, fanAngle, rootAngle );
	this.nodes[id]=node;
	return node;
}

/*
 * Remove a node (and all of it's children, of course)
 */
SnowflakeGraphModel.prototype.removeNode = function( modelNode ) {
	var destroyed = modelNode.destroy();
	for( var i=0, l=this.updateQueue.length; i<l; i++ ) {
		if ( this.updateQueue[i]==modelNode ) {
			this.updateQueue.splice(i,1);
		}
	}
	for( var i=0, l=destroyed.length; i<l; i++ ) {
		this.view.removeNode( this.nodes[destroyed[i]] );
		delete this.nodes[destroyed[i]];
	}
	delete this.nodes[modelNode.id];
	this.view.removeNode( modelNode );
}

/*
 * Find the root of this node. This model may have multiple roots, so this
 * requires a recursive traversal.
 */
SnowflakeGraphModel.prototype.findRoot = function(node) {
	if ( !node && this.updateQueue.length>0 ) {
		return this.findRoot( this.updateQueue[0] );
	} else if ( !node ) {
		return null;
	} else if ( node.parent) {
		return this.findRoot(node.parent);
	} else {
		return node;
	}
}


text:
package gov.hhs.fha.nhinc.patientdiscovery.entity;

/**
 * PatientDiscovery OrchestrationContext for g0 endpoint
 *
 * @author paul.eftis
 */
public class OutboundPatientDiscoveryOrchestrationContextBuilder_g0 extends
        OutboundPatientDiscoveryOrchestrationContextBuilder {

    /**
     * @return strategy for g0
     */
    @Override
    protected OutboundPatientDiscoveryStrategy getStrategy() {
        return new OutboundPatientDiscoveryStrategyImpl_g0();
    }

    /**
     * @return OutboundPatientDiscoveryOrchestratable for g0
     */
    @Override
    protected OutboundPatientDiscoveryOrchestratable getOrchestratable() {
        OutboundPatientDiscoveryOrchestratable orch = new OutboundPatientDiscoveryOrchestratable(
                getNhinDelegate(), getProcessor(), getAuditTransformer(), getPolicyTransformer(), getAssertionType(),
                getServiceName(), getTargetSystemType(), getRequest());
        return orch;
    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>类 com.weibo.sdk.android.api.WeiboAPI.FEATURE的使用</title>
<meta name="date" content="2013-05-25">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

您的浏览器已禁用 JavaScript。

概览

程序包

类

使用

树

已过时

索引

帮助

上一个

下一个

框架

无框架

所有类

类 com.weibo.sdk.android.api.WeiboAPI.FEATURE
的使用

使用WeiboAPI.FEATURE的程序包

程序包
说明

com.weibo.sdk.android.api

com.weibo.sdk.android.api中WeiboAPI.FEATURE的使用

返回WeiboAPI.FEATURE的com.weibo.sdk.android.api中的方法

限定符和类型
方法和说明

static WeiboAPI.FEATURE
WeiboAPI.FEATURE.valueOf(java.lang.String name)

返回带有指定名称的该类型的枚举常量。

static WeiboAPI.FEATURE[]
WeiboAPI.FEATURE.values()

按照声明该枚举类型的常量的顺序, 返回
包含这些常量的数组。

参数类型为WeiboAPI.FEATURE的com.weibo.sdk.android.api中的方法

限定符和类型
方法和说明

void
StatusesAPI.bilateralTimeline(long since_id,
                 long max_id,
                 int count,
                 int page,
                 boolean base_app,
                 WeiboAPI.FEATURE feature,
                 boolean trim_user,
                 com.weibo.sdk.android.net.RequestListener listener)

获取双向关注用户的最新微博

void
StatusesAPI.friendsTimeline(long since_id,
               long max_id,
               int count,
               int page,
               boolean base_app,
               WeiboAPI.FEATURE feature,
               boolean trim_user,
               com.weibo.sdk.android.net.RequestListener listener)

获取当前登录用户及其所关注用户的最新微博

void
StatusesAPI.friendsTimelineIds(long since_id,
                  long max_id,
                  int count,
                  int page,
                  boolean base_app,
                  WeiboAPI.FEATURE feature,
                  com.weibo.sdk.android.net.RequestListener listener)

获取当前登录用户及其所关注用户的最新微博的ID

void
StatusesAPI.homeTimeline(long since_id,
            long max_id,
            int count,
            int page,
            boolean base_app,
            WeiboAPI.FEATURE feature,
            boolean trim_user,
            com.weibo.sdk.android.net.RequestListener listener)

获取当前登录用户及其所关注用户的最新微博

void
StatusesAPI.userTimeline(long since_id,
            long max_id,
            int count,
            int page,
            boolean base_app,
            WeiboAPI.FEATURE feature,
            boolean trim_user,
            com.weibo.sdk.android.net.RequestListener listener)

获取当前用户最新发表的微博列表

void
StatusesAPI.userTimeline(long uid,
            long since_id,
            long max_id,
            int count,
            int page,
            boolean base_app,
            WeiboAPI.FEATURE feature,
            boolean trim_user,
            com.weibo.sdk.android.net.RequestListener listener)

获取某个用户最新发表的微博列表

void
StatusesAPI.userTimeline(java.lang.String screen_name,
            long since_id,
            long max_id,
            int count,
            int page,
            boolean base_app,
            WeiboAPI.FEATURE feature,
            boolean trim_user,
            com.weibo.sdk.android.net.RequestListener listener)

获取某个用户最新发表的微博列表

void
StatusesAPI.userTimelineIds(long uid,
               long since_id,
               long max_id,
               int count,
               int page,
               boolean base_app,
               WeiboAPI.FEATURE feature,
               com.weibo.sdk.android.net.RequestListener listener)

获取用户发布的微博的ID

void
StatusesAPI.userTimelineIds(java.lang.String screen_name,
               long since_id,
               long max_id,
               int count,
               int page,
               boolean base_app,
               WeiboAPI.FEATURE feature,
               com.weibo.sdk.android.net.RequestListener listener)

获取用户发布的微博的ID

概览

程序包

类

使用

树

已过时

索引

帮助

上一个

下一个

框架

无框架

所有类


text:
<?php

/*
 * This file is part of the Active Collab Utils project.
 *
 * (c) A51 doo <info@activecollab.com>. All rights reserved.
 */

declare(strict_types=1);

namespace ActiveCollab\Utils\Test\HttpClient;

use ActiveCollab\HttpClient\Client\Factory\ClientFactory;
use ActiveCollab\HttpClient\Client\Factory\ClientFactoryInterface;
use ActiveCollab\HttpClient\Client\ClientInterface;
use ActiveCollab\HttpClient\Configure\ClientMiddleware\ClientMiddlewareInterface;
use ActiveCollab\Utils\Test\Base\TestCase;
use Laminas\Diactoros\ResponseFactory;

class ClientFactoryTest extends TestCase
{
    public function testWillUseDefaultClientMiddlewares(): void
    {
        $clientMock = $this->createMock(ClientInterface::class);
        $middleware1 = $this->createMock(ClientMiddlewareInterface::class);
        $middleware1
            ->expects($this->once())
            ->method('alter');

        $middleware2 = $this->createMock(ClientMiddlewareInterface::class);
        $middleware2
            ->expects($this->once())
            ->method('alter');

        $clientFactory = $this->createTestFactory($clientMock, $middleware1, $middleware2);

        $clientFactory->createClient();
    }

    private function createTestFactory(
        ClientInterface $client,
        ClientMiddlewareInterface ...$defaultMiddlewares
    ): ClientFactoryInterface
    {
        return new class ($client, ...$defaultMiddlewares) extends ClientFactory
        {
            private ClientInterface $client;

            public function __construct(
                ClientInterface $client,
                ClientMiddlewareInterface ...$defaultMiddlewares
            )
            {
                parent::__construct(new ResponseFactory(), ...$defaultMiddlewares);

                $this->client = $client;
            }

            protected function doCreateClient(): ClientInterface
            {
                return $this->client;
            }
        };
    }
}


text:
tjungblut-online-ml
===================

This is my online machine learning library. Over the next few months I will put some algorithms from my main common library into a streaming fashion and move them into this repository.

Everything will be built upon the Java 8 streams and the algorithms are specifically designed to make use of the streams feature, also I aim scale this library vertically by using parallel streams wherever possible.

This is not a distributed system, but its parts can be reused with any MapReduce or BSP implementation (e.g. Hadoop MR/Hama BSP), making it horizontally scalable for terabyte/petabyte datasets as well.

For the future, I also want to support infinite streams where the training can be done asynchronously with using the model.

Supported Algorithms
===================

- [x] Multinomial Naive Bayes
- [x] Stochastic Gradient Descent
 - [x] Logistic regression
 - [x] Linear regression (least squares)
 - [x] Multinomial regression (one vs. all)
 - [x] Maximum Margin (hinge loss)
 - [x] Lasso (l1 norm)
 - [x] Ridge Regression (l2 norm)
 - [x] FTRL-Proximal
 - [x] Adam
 - [ ] CG
 - [ ] Sample-based Adaptive Learning Rates
 - [ ] Shuffled input streams
 - [ ] Multilayer Perceptron
- [ ] Graphite Bindings

Sample Usage
===================

Stochastic Gradient Descent (logistic regression)
-------------------------------------------------

A very simplistic example is the SGD (stochastic gradient descent) classifier, the following example will train a logistic regression model:

```java
// use a gradient descent with a learning rate of 0.1
StochasticGradientDescent min = StochasticGradientDescentBuilder.create(0.1).build();

// generate the data, note that the features must include a bias (constant 1) if you want to have one
List<FeatureOutcomePair> data = generateData();

RegressionLearner learner = new RegressionLearner(min, new SigmoidActivationFunction(), new LogLoss());
// do 5 passes over all data in a stream, the default is 1
learner.setNumPasses(5);

// train the model by supplying the stream
RegressionModel model = learner.train(() -> data.stream());

// print the weights
System.out.println(model.getWeights());
```

The StochasticGradientDescent class makes use of parallel streams, so if you want to change the size of the internal fork-join pool that it uses, you can set:

> -Djava.util.concurrent.ForkJoinPool.common.parallelism=30

to whatever maximizes your throughput in updates per second.

Do Predictions
--------------

You can also do predictions with the model using a Classifier:

```java
RegressionClassifier classifier = new RegressionClassifier(model);
// add the bias to the feature and predict it
DoubleVector prediction = classifier.predict(new DenseDoubleVector(new double[] { 1, 25d, 25d }))
// print the prediction
System.out.println(prediction);
```

Serialize your model
--------------------

If you want to save the model to a file, you can use the serialization API offered by the model:

```java
try (DataOutputStream dos = new DataOutputStream(new FileOutputStream("/tmp/model.bin"))){
	model.serialize(dos);
}
```

Deserialization works in the same way:
```java
RegressionModel model = new RegressionModel();
try (DataInputStream dis = new DataInputStream(new FileInputStream("/tmp/model.bin"))){
	model.deserialize(dis);
}
// take dis
```

Avazu Click-Through Rate Prediction
-------------------------------------

A prime example to use this streaming library for is to do CTR predictions. Below code takes the data from the [Avazu CTR prediction challenge on kaggle](https://www.kaggle.com/c/avazu-ctr-prediction/).
It is using simple feature hashing and FTRL logistic regression.

```java

public class AvazuCtrPrediction {

  private static final int NUM_COLUMNS = 24;
  private static final int SPARSE_HASH_DIMENSION = 2 << 24;
  private static final Pattern SPLITTER = Pattern.compile(",");
  private static final int BUFFER_SIZE = 1024 * 1024 * 5;
  private static final String TRAINING_SET_PATH = "/home/user/datasets/ctr/train.gz";

  private static final SingleEntryDoubleVector POSITIVE_CLASS //
  = new SingleEntryDoubleVector(1d);
  private static final SingleEntryDoubleVector NEGATIVE_CLASS //
  = new SingleEntryDoubleVector(0d);

  private static FeatureOutcomePair parseFeature(String line, String[] header) {

    final int shift = 2;
    String[] split = SPLITTER.split(line);
    Preconditions.checkArgument(split.length == NUM_COLUMNS,
        "line doesn't match expected size");

    // turn the date into the hour
    split[2] = split[2].substring(6);

    // prepare the tokens for feature hashing
    String[] tokens = new String[split.length - shift];
    for (int i = 0; i < tokens.length; i++) {
      tokens[i] = header[i + shift] + "_" + split[i + shift];
    }

    // hash them with 128 bit murmur3
    DoubleVector feature = VectorizerUtils.sparseHashVectorize(tokens, Hashing
        .murmur3_128(), () -> new SequentialSparseDoubleVector(
        SPARSE_HASH_DIMENSION));

    // fix the first element to be the bias
    feature.set(0, 1d);

    return new FeatureOutcomePair(feature,
        split[1].equals("0") ? NEGATIVE_CLASS : POSITIVE_CLASS);
  }

  private static Stream<FeatureOutcomePair> setupStream() {
    try {
      @SuppressWarnings("resource")
      BufferedReader reader = new BufferedReader(new InputStreamReader(
          new GZIPInputStream(new FileInputStream(TRAINING_SET_PATH),
              BUFFER_SIZE), Charset.defaultCharset()));

      // consume the header first
      final String[] header = SPLITTER.split(reader.readLine());
      // yield the stream for everything that comes after
      return reader.lines().map((s) -> parseFeature(s, header));
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  public static void main(String[] args) throws IOException {

    StochasticGradientDescent sgd = StochasticGradientDescentBuilder
        .create(0.01) // learning rate
        .holdoutValidationPercentage(0.05d) // 5% as validation set
        .historySize(10_000) // keep 10k samples to compute relative improvement
        .weightUpdater(new AdaptiveFTRLRegularizer(1, 1, 1)) // FTRL updater
        .progressReportInterval(1_000_000) // report every n iterations
        .build();

    // simple regression with Sigmoid and LogLoss
    RegressionLearner learner = new RegressionLearner(sgd,
        new SigmoidActivationFunction(), new LogLoss());

    // you are able to trade speed with memory usage!
    // using sparse weights should use roughly 400mb, vs. 3gb of dense weights.
    // however, dense weights are 10x faster in this case.
    // learner.useSparseWeights();

    // do two full passes over the data
    learner.setNumPasses(2);
    learner.verbose();

    Stopwatch sw = Stopwatch.createStarted();

    // train the model
    RegressionModel model = learner.train(() -> setupStream());

    // output the weights
    model.getWeights().iterateNonZero().forEachRemaining(System.out::println);

    System.out.println("Time taken: " + sw.toString());

  }

}

```

You should see similar output to the one below (verbosity omitted):

```
Pass 0 | Iteration 1000000 | Validation Cost: 0.392678 | Training Cost: 0.414122 | Avg Improvement: -5.06327e-07 | Iterations/s: 83333.3
---
Pass 0 | Iteration 38000000 | Validation Cost: 0.400473 | Training Cost: 0.422624 | Avg Improvement: 1.80911e-08 | Iterations/s: 93596.1
Pass Summary 0 | Iteration 38406639 | Validation Cost: 0.400674 | Training Cost: 0.422823 | Iterations/s: 93446.8  | Total Time Taken: 6.854 min
Pass 1 | Iteration 1000000 | Validation Cost: 0.377576 | Training Cost: 0.403000 | Avg Improvement: -4.86178e-07 | Iterations/s: 93602.5
---
Pass 1 | Iteration 38000000 | Validation Cost: 0.396356 | Training Cost: 0.418665 | Avg Improvement: 2.13002e-08 | Iterations/s: 93981.1
Pass Summary 1 | Iteration 38406798 | Validation Cost: 0.396473 | Training Cost: 0.418885 | Iterations/s: 94018.9  | Total Time Taken: 13.63 min

0 -> -0.2179566321842441
19 -> -0.008019816916453593
40 -> 0.011372162311553732
72 -> 0.009959662995812498
75 -> 0.01552960872382698
91 -> 0.01122045025790969
114 -> -0.058862175500113786
---
33554352 -> -0.013848560325345247
33554353 -> -7.612543688230045E-4
33554422 -> -0.003704587068022832
Time taken: 13.94 min
```

MNIST Multinomial Logistic Regression
-------------------------------------

A very simply code example for training the multinomial logistic regression is on the MNIST dataset.
Here we use the data from the [digit recognizer kaggle competetion](http://www.kaggle.com/c/digit-recognizer).

```java

    Dataset trainingSet = MNISTReader.readMNISTTrainImages("/home/user/datasets/mnist/kaggle/train.csv");

    IntFunction<RegressionLearner> factory = (i) -> {
    	  // take care of not sharing any state from the outside, since classes are trained in parallel
        StochasticGradientDescent minimizer = StochasticGradientDescentBuilder
        .create(0.01)
        .holdoutValidationPercentage(0.1d)
        .weightUpdater(new L2Regularizer(0.1))
        .progressReportInterval(1_000_000)
        .build();
      RegressionLearner learner = new RegressionLearner(minimizer,
          new SigmoidActivationFunction(), new LogLoss());
      learner.setNumPasses(50);
      learner.verbose();
      return learner;
    };

    MultinomialRegressionLearner learner = new MultinomialRegressionLearner(factory);
    learner.verbose();

    MultinomialRegressionModel model = learner.train(() -> trainingSet.asStream());
    MultinomialRegressionClassifier clf = new MultinomialRegressionClassifier(model);
    // do some classifications

```

The accuracy and confusion matrix on a test set looks like this:

```
 31280 /  42000 acc: 0.7447619047619047
 3680    5  111  110   19  187  152   23   95   42 <-   744   17%	 0
    6 4553  212  254  127  157   52  187  544  137 <-  1676   27%	 1
   53   37 2916  344   53   46  182   33   54   17 <-   819   22%	 2
   31   11  328 3052   77  447   24  208  378   82 <-  1586   34%	 3
   65   15  121   66 3249  402   46  168   84  675 <-  1642   34%	 4
  130   28   67  195  104 1957  107    1  323   17 <-   972   33%	 5
   71   14  181   48   60   91 3511    3   29    2 <-   499   12%	 6
   27    7   74  119   22   86    0 3481   38  698 <-  1071   24%	 7
   59   11  143   88   57  271   45    4 2438   75 <-   753   24%	 8
   10    3   24   75  304  151   18  293   80 2443 <-   958   28%	 9
```

License
-------

Since I am Apache committer, I consider everything inside of this repository
licensed by Apache 2.0 license, although I haven't put the usual header into the source files.

If something is not licensed via Apache 2.0, there is a reference or an additional licence header included in the specific source file.

Maven
-----

If you use maven, you can get the latest release using the following dependency:

```
 <dependency>
     <groupId>de.jungblut.ml</groupId>
     <artifactId>tjungblut-online-ml</artifactId>
     <version>0.5</version>
 </dependency>
```

Build
-----

You will need Java 8 to build this library.

You can simply build with:

> mvn clean package install

The created jars contains debuggable code + sources + javadocs.

If you want to skip testcases you can use:

> mvn clean package install -DskipTests

If you want to skip the signing process you can do:

> mvn clean package install -Dgpg.skip=true


text:
  console.log( "onreadycb" )
  onreadycb=function () {
    var url = "http://202.120.40.52:8400/";
    var iframe = window.open( url , '_blank', 'location=no');
    // Announce that we have a camera.
    iframe.addEventListener("loadstop", function(event) {
      iframe.contentWindow.postMessage({
        cameraEnabled: navigator.camera != null && navigator.camera.getPicture != null
      }, url);
    }, false);
    // Listen for requests to use it.
    window.addEventListener("message", function(event) {
      if (event.origin == url) {
            eval( event.data )
      }
    }, false);
  }
  console.log( "onready" )
  document.addEventListener("deviceready", onreadycb, false);
  $(document).ready( onreadycb )


text:
var specialApps = {
    "allApps"  : "allApps",
    "connect"  : "connect",
    "develop"  : "develop",
    "settings" : "settings"
};
var defaultSubSections = {};
var loggedIn = true;

$(document).ready(function() {
    $.history.init(function(hash){
        loadDiv(window.location.hash.substring(1) || $('.installed-apps a').data('id') || '#Explore-contactsviewer');
    }, { unescape: ",/" });

    $('body').delegate('.install', 'click', function(e) {
        var $e = $(e.currentTarget);
        var id = $e.attr('id');
        $.get('/registry/add/' + id, function() {
            if(typeof _kml !== 'undefined') _kml.push('addapp');
            window.location = 'explore#Explore-' + id;
        });
        return false;
    });

    $('body').delegate('.oauthLink','click', Locker.connectService);

    $('.your-apps').click(function() {
        $('.blue').removeClass('blue');
        $(this).addClass('blue');
        if (document.getElementById('appFrame').contentWindow.filterItems) {
            document.getElementById('appFrame').contentWindow.filterItems($(this).attr('id'));
        }
    });

    function promptForConnections() {
      registry.getMyConnectors(function(connectors) {
        var count = Object.keys(connectors).length;
        if (count === 0 || (count === 1 && typeof(connectors.github) !== 'undefined')) {
          window.location.hash = '#Explore-connect';
        } else {
          $('.nav-section, .sidenav').show();
          showConnectMore();
        }
      });
    }

    function showConnectMore() {
        if ($.cookie("firstvisit") !== 'true') return;
        $.cookie("firstvisit", null, {path: '/' });
        var modal = $('#connect-more').modal();
        $('#simplemodal-overlay,#no-thanks,#close-button,#close-this,.gotit-button').click(function(e) {
            modal.close();
        });
    }

    if (window.location.hash !== '#Explore-connect') promptForConnections();
});

var loadApp = function(info) {
    var app = info.subSection || info.topSection;
    $('.app-container').hide();
    $('.app-container#iframeContainer').show();
    $('.app-details').hide();
    $('#iframeContainer .app-header').hide();
    if (specialApps[app]) {
        setFrame(specialApps[app] + '?params=' + info.params);
    } else if (info.topSection === "Settings") {
        if (info.subSection === "Connections") setFrame('/dashboard/settings-connectors');
        else if (info.subSection === "AccountInformation") setFrame('/dashboard/settings-account');
        else if (info.subSection === "APIKey") setFrame('/dashboard/settings-api');
        else alert("CAN YOOOOO SMELL WHAT THE ROCK IS COOOKING?");
    } else if (app === "Publish") {
        setFrame('publish?app=' + info.params.app);
    } else if (info.topSection === "Develop") {
        if (info.subSection === "BuildAnApp") setFrame('/dashboard/develop-buildapp');
        else if (info.subSection === "ApiExplorer") setFrame('/dashboard/develop-apiexplorer');
        else if (info.subSection === "Publishing") setFrame('/dashboard/develop-publishing');
        else if (info.subSection === "ExampleApps") setFrame('/dashboard/develop-exampleapps');
        else if (info.subSection === "Chat") setFrame('/dashboard/develop-chat');
        else if (info.subSection === "TemplatesIcons") setFrame('/dashboard/develop-templatesicons');
    } else if (app === "connect") {
        setFrame('/dashboard/connect');
    } else {
        handleApp(app);
    }

    $('.iframeLink[data-id="' + info.app + '"]').parent('p').siblings().show();
};

var syncletInstalled = function(provider) {
  if (provider === 'github') $('.your-apps').show();
  // update connected and unconnected services lists
  link = $('.unconnected-services .oauthLink[data-provider="' + provider + '"]');
  if(link.length) {
    link.each(function(index, element) {
      element = $(element);
      var img = element.find('img');
      var connected = element.parent().parent().find('.connected-services');
      connected.append('\n\n\n').append(img.addClass('installed'));
      element.remove();
    });
  }
};

handlers.Explore = loadApp;
handlers.Develop = loadApp;
handlers.connect = loadApp;
handlers.Settings = loadApp;
handlers.allApps = loadApp;
handlers.publish = loadApp;

function setFrame(path) {
    $("#appFrame")[0].contentWindow.location.replace(path);
}

var connectedCount = 0;
function handleApp(appName) {
    $.get('clickapp/' + appName, function(e) {});
    doAppHeader(appName, '#iframeContainer .app-header');
    getAppAndConnectedServices(appName, function(err, app, connected) {
        if(app.uses && app.uses.services && (connected.hasOwnProperty('length') && connected.length === 0)) {
            $("#appFrame").hide();
        } else {
            $("#appFrame").show();
            setFrame('/Me/' + appName);
        }
    });
}

function getAppAndConnectedServices(appName, callback) {
    registry.getMap(function(err, map) {
        if(err || !map[appName]) return callback(err, map);
        var app = map[appName];
        registry.getConnectedServices(app.uses, function(connected) {
            callback(undefined, app, connected);
        });
    });
}


text:
<?php

namespace Omnipay\Wirecard;

use Doctrine\Common\Annotations\AnnotationRegistry;
use JMS\Serializer\SerializerBuilder;
use JMS\Serializer\SerializerInterface;
use Omnipay\Common\AbstractGateway;
use Omnipay\Common\Message\RequestInterface;
use Omnipay\Wirecard\Message\AbstractRequest;
use Omnipay\Wirecard\Message\Builder\ApplePayPurchaseBuilder;
use Omnipay\Wirecard\Message\Builder\CheckPayerResponseBuilder;
use Omnipay\Wirecard\Message\Builder\DebitBuilder;
use Omnipay\Wirecard\Message\Builder\EnrollmentBuilder;
use Omnipay\Wirecard\Message\Builder\PurchaseBuilder;
use Wirecard\Element\Payment;

/**
 * @method AbstractRequest createRequest(string $class, array $parameters)
 */
class Gateway extends AbstractGateway
{
    /**
     * Get gateway display name
     *
     * This can be used by carts to get the display name for each gateway.
     */
    public function getName()
    {
        return 'Wirecard';
    }

    public function initialize(array $parameters = array())
    {
        if (!isset($parameters['serializer'])) {
            AnnotationRegistry::registerLoader('class_exists');
            $parameters['serializer'] = SerializerBuilder::create()->build();
        }

        return parent::initialize($parameters);
    }

    public function getDefaultParameters()
    {
        return array(
            'username' => '',
            'password' => '',
            'endpoint' => '',
            'testMode' => false,
        );
    }

    public function getEndpoint()
    {
        return $this->getParameter('endpoint');
    }

    public function setEndpoint($value)
    {
        return $this->setParameter('endpoint', $value);
    }

    public function getUsername()
    {
        return $this->getParameter('username');
    }

    public function setUsername($value)
    {
        return $this->setParameter('username', $value);
    }

    public function getPassword()
    {
        return $this->getParameter('password');
    }

    public function setPassword($value)
    {
        return $this->setParameter('password', $value);
    }

    /**
     * @param SerializerInterface $serializer
     *
     * @return $this
     */
    public function setSerializer(SerializerInterface $serializer)
    {
        return $this->setParameter('serializer', $serializer);
    }

    /**
     * @return SerializerInterface
     */
    public function getSerializer()
    {
        return $this->getParameter('serializer');
    }

    /**
     * @param array $parameters
     *
     * @return RequestInterface
     */
    public function enrollmentCheck(array $parameters = array())
    {
        $request = $this->createRequest('\Omnipay\Wirecard\Message\EnrollmentCheckRequest', $parameters);
        $request->setBuilder(new EnrollmentBuilder($request));
        $request->getCard()->validate();

        return $request;
    }

    /**
     * @param array $parameters
     *
     * @return RequestInterface
     */
    public function checkPayerResponse(array $parameters = array())
    {
        $request = $this->createRequest('\Omnipay\Wirecard\Message\CheckPayerResponseRequest', $parameters);
        $request->setBuilder(new CheckPayerResponseBuilder($request));

        return $request;
    }

    /**
     * @param array $parameters
     *
     * @return RequestInterface
     */
    public function purchase(array $parameters = array())
    {
        $request = $this->createRequest('\Omnipay\Wirecard\Message\PurchaseRequest', $parameters);
        $request->setBuilder(new PurchaseBuilder($request));

        return $request;
    }

    /**
     * @param array $parameters
     *
     * @return RequestInterface
     */
    public function debit(array $parameters = array())
    {
        $request = $this->createRequest('\Omnipay\Wirecard\Message\DebitRequest', $parameters);
        $request->setBuilder(new DebitBuilder($request));

        return $request;
    }

    /**
     * @param array $parameters
     *
     * @return RequestInterface
     */
    public function applePayPurchase(array $parameters = array())
    {
        $request = $this->createRequest('\Omnipay\Wirecard\Messa{
            "class": "Symfony\\Component\\Debug\\Exception\\FatalThrowableError",
            "message": "basename() expects parameter 1 to be string, object given",
            "code": 0,
            "file": "/var/www/lms/src/Doctrine/ModuleManager.php:314",
            "trace": [
                "/var/www/lms/src/Doctrine/ModuleManager.php:314",
                "/var/www/lms/src/Controller/Editor/PackageController.php:321",
                "/var/www/lms/vendor/symfony/http-kernel/HttpKernel.php:151",
                "/var/www/lms/vendor/symfony/http-kernel/HttpKernel.php:68",
                "/var/www/lms/vendor/symfony/http-kernel/Kernel.php:198",
                "/var/www/lms/public/index.php:25"
            ]
        }ge\ApplePayPurchaseRequest', $parameters);
        $request->setBuilder(new ApplePayPurchaseBuilder($request));

        return $request;
    }

    /**
     * @param string $path
     *
     * @return Payment
     */
    public function checkDebitResponse($path = 'php://input')
    {
        return $this->getSerializer()->deserialize(file_get_contents($path), Payment::class, 'xml');
    }
}