text:
package models

import (
	"strings"
	"testing"
	"time"

	"gopkg.in/yaml.v2"

	envmanModels "github.com/bitrise-io/envman/models"
	"github.com/bitrise-io/go-utils/pointers"
	stepmanModels "github.com/bitrise-io/stepman/models"
	"github.com/stretchr/testify/require"
)

// ----------------------------
// --- Validate

// Config
func TestValidateConfig(t *testing.T) {
	t.Log("Valid bitriseData ID")
	{
		bitriseData := BitriseDataModel{
			Workflows: map[string]WorkflowModel{
				"A-Za-z0-9-_.": WorkflowModel{},
			},
		}

		warnings, err := bitriseData.Validate()
		require.NoError(t, err)
		require.Equal(t, 0, len(warnings))
	}

	t.Log("Invalid bitriseData ID - empty")
	{
		bitriseData := BitriseDataModel{
			Workflows: map[string]WorkflowModel{
				"": WorkflowModel{},
			},
		}
		warnings, err := bitriseData.Validate()
		require.NoError(t, err)
		require.Equal(t, 1, len(warnings))
		require.Equal(t, "invalid workflow ID (): empty", warnings[0])
	}

	t.Log("Invalid bitriseData ID - contains: `/`")
	{
		bitriseData := BitriseDataModel{
			Workflows: map[string]WorkflowModel{
				"wf/id": WorkflowModel{},
			},
		}

		warnings, err := bitriseData.Validate()
		require.NoError(t, err)
		require.Equal(t, 1, len(warnings))
		require.Equal(t, "invalid workflow ID (wf/id): doesn't conform to: [A-Za-z0-9-_.]", warnings[0])
	}

	t.Log("Invalid bitriseData ID - contains: `:`")
	{
		bitriseData := BitriseDataModel{
			Workflows: map[string]WorkflowModel{
				"wf:id": WorkflowModel{},
			},
		}

		warnings, err := bitriseData.Validate()
		require.NoError(t, err)
		require.Equal(t, 1, len(warnings))
		require.Equal(t, "invalid workflow ID (wf:id): doesn't conform to: [A-Za-z0-9-_.]", warnings[0])
	}

	t.Log("Invalid bitriseData ID - contains: ` `")
	{
		bitriseData := BitriseDataModel{
			Workflows: map[string]WorkflowModel{
				"wf id": WorkflowModel{},
			},
		}

		warnings, err := bitriseData.Validate()
		require.NoError(t, err)
		require.Equal(t, 1, len(warnings))
		require.Equal(t, "invalid workflow ID (wf id): doesn't conform to: [A-Za-z0-9-_.]", warnings[0])
	}

	t.Log("Invalid bitriseData ID - contains: ` `")
	{
		bitriseData := BitriseDataModel{
			Workflows: map[string]WorkflowModel{
				" wfid": WorkflowModel{},
			},
		}

		warnings, err := bitriseData.Validate()
		require.NoError(t, err)
		require.Equal(t, 1, len(warnings))
		require.Equal(t, "invalid workflow ID ( wfid): doesn't conform to: [A-Za-z0-9-_.]", warnings[0])
	}

	t.Log("Invalid bitriseData ID - contains: ` `")
	{
		bitriseData := BitriseDataModel{
			Workflows: map[string]WorkflowModel{
				"wfid ": WorkflowModel{},
			},
		}

		warnings, err := bitriseData.Validate()
		require.NoError(t, err)
		require.Equal(t, 1, len(warnings))
	}
}

// Workflow
func TestValidateWorkflow(t *testing.T) {
	t.Log("before-afetr test")
	{
		workflow := WorkflowModel{
			BeforeRun: []string{"befor1", "befor2", "befor3"},
			AfterRun:  []string{"after1", "after2", "after3"},
		}

		warnings, err := workflow.Validate()
		require.NoError(t, err)
		require.Equal(t, 0, len(warnings))
	}

	t.Log("invalid workflow - Invalid env: more than 2 fields")
	{
		configStr := `
format_version: 1.0.0
default_step_lib_source: "https://github.com/bitrise-io/bitrise-steplib.git"

workflows:
  target:
    envs:
    - ENV_KEY: env_value
      opts:
        title: test_env
    title: Output Test
    steps:
    - script:
        title: Should fail
        inputs:
        - content: echo "Hello"
          BAD_KEY: value
`

		config := BitriseDataModel{}
		require.NoError(t, yaml.Unmarshal([]byte(configStr), &config))
		require.NoError(t, config.Normalize())

		warnings, err := config.Validate()
		require.Error(t, err)
		require.Equal(t, true, strings.Contains(err.Error(), "Invalid env: more than 2 fields:"))
		require.Equal(t, 0, len(warnings))
	}

	t.Log("vali workflow - Warning: duplicated inputs")
	{
		configStr := `
format_version: 1.0.0
default_step_lib_source: "https://github.com/bitrise-io/bitrise-steplib.git"

workflows:
  target:
    steps:
    - script:
        title: Should fail
        inputs:
        - content: echo "Hello"
        - content: echo "Hello"
`

		config := BitriseDataModel{}
		require.NoError(t, yaml.Unmarshal([]byte(configStr), &config))
		require.NoError(t, config.Normalize())

		warnings, err := config.Validate()
		require.NoError(t, err)
		require.Equal(t, 1, len(warnings))
	}
}

// ----------------------------
// --- Merge

func TestMergeEnvironmentWith(t *testing.T) {
	diffEnv := envmanModels.EnvironmentItemModel{
		"test_key": "test_value",
		envmanModels.OptionsKey: envmanModels.EnvironmentItemOptionsModel{
			Title:             pointers.NewStringPtr("test_title"),
			Description:       pointers.NewStringPtr("test_description"),
			Summary:           pointers.NewStringPtr("test_summary"),
			ValueOptions:      []string{"test_valu_options1", "test_valu_options2"},
			IsRequired:        pointers.NewBoolPtr(true),
			IsExpand:          pointers.NewBoolPtr(false),
			IsDontChangeValue: pointers.NewBoolPtr(true),
			IsTemplate:        pointers.NewBoolPtr(true),
		},
	}

	t.Log("Different keys")
	{
		env := envmanModels.EnvironmentItemModel{
			"test_key1": "test_value",
		}
		require.Error(t, MergeEnvironmentWith(&env, diffEnv))
	}

	t.Log("Normal merge")
	{
		env := envmanModels.EnvironmentItemModel{
			"test_key":              "test_value",
			envmanModels.OptionsKey: envmanModels.EnvironmentItemOptionsModel{},
		}
		require.NoError(t, MergeEnvironmentWith(&env, diffEnv))

		options, err := env.GetOptions()
		require.NoError(t, err)

		diffOptions, err := diffEnv.GetOptions()
		require.NoError(t, err)

		require.Equal(t, *diffOptions.Title, *options.Title)
		require.Equal(t, *diffOptions.Description, *options.Description)
		require.Equal(t, *diffOptions.Summary, *options.Summary)
		require.Equal(t, len(diffOptions.ValueOptions), len(options.ValueOptions))
		require.Equal(t, *diffOptions.IsRequired, *options.IsRequired)
		require.Equal(t, *diffOptions.IsExpand, *options.IsExpand)
		require.Equal(t, *diffOptions.IsDontChangeValue, *options.IsDontChangeValue)
		require.Equal(t, *diffOptions.IsTemplate, *options.IsTemplate)
	}
}

func TestMergeStepWith(t *testing.T) {
	desc := "desc 1"
	summ := "sum 1"
	website := "web/1"
	fork := "fork/1"
	published := time.Date(2012, time.January, 1, 0, 0, 0, 0, time.UTC)

	stepData := stepmanModels.StepModel{
		Description:         pointers.NewStringPtr(desc),
		Summary:             pointers.NewStringPtr(summ),
		Website:             pointers.NewStringPtr(website),
		SourceCodeURL:       pointers.NewStringPtr(fork),
		PublishedAt:         pointers.NewTimePtr(published),
		HostOsTags:          []string{"osx"},
		ProjectTypeTags:     []string{"ios"},
		TypeTags:            []string{"test"},
		IsRequiresAdminUser: pointers.NewBoolPtr(true),
		Inputs: []envmanModels.EnvironmentItemModel{
			envmanModels.EnvironmentItemModel{
				"KEY_1": "Value 1",
			},
			envmanModels.EnvironmentItemModel{
				"KEY_2": "Value 2",
			},
		},
		Outputs: []envmanModels.EnvironmentItemModel{},
	}

	diffTitle := "name 2"
	newSuppURL := "supp"
	runIfStr := ""
	stepDiffToMerge := stepmanModels.StepModel{
		Title:      pointers.NewStringPtr(diffTitle),
		HostOsTags: []string{"linux"},
		Source: stepmanModels.StepSourceModel{
			Git: "https://git.url",
		},
		Dependencies: []stepmanModels.DependencyModel{
			stepmanModels.DependencyModel{
				Manager: "brew",
				Name:    "test",
			},
		},
		SupportURL: pointers.NewStringPtr(newSuppURL),
		RunIf:      pointers.NewStringPtr(runIfStr),
		Inputs: []envmanModels.EnvironmentItemModel{
			envmanModels.EnvironmentItemModel{
				"KEY_2": "Value 2 CHANGED",
			},
		},
	}

	mergedStepData, err := MergeStepWith(stepData, stepDiffToMerge)
	require.NoError(t, err)

	require.Equal(t, "name 2", *mergedStepData.Title)
	require.Equal(t, "desc 1", *mergedStepData.Description)
	require.Equal(t, "sum 1", *mergedStepData.Summary)
	require.Equal(t, "web/1", *mergedStepData.Website)
	require.Equal(t, "fork/1", *mergedStepData.SourceCodeURL)
	require.Equal(t, true, (*mergedStepData.PublishedAt).Equal(time.Date(2012, time.January, 1, 0, 0, 0, 0, time.UTC)))
	require.Equal(t, "linux", mergedStepData.HostOsTags[0])
	require.Equal(t, "", *mergedStepData.RunIf)
	require.Equal(t, 1, len(mergedStepData.Dependencies))

	dep := mergedStepData.Dependencies[0]
	require.Equal(t, "brew", dep.Manager)
	require.Equal(t, "test", dep.Name)

	// inputs
	input0 := mergedStepData.Inputs[0]
	key0, value0, err := input0.GetKeyValuePair()

	require.NoError(t, err)
	require.Equal(t, "KEY_1", key0)
	require.Equal(t, "Value 1", value0)

	input1 := mergedStepData.Inputs[1]
	key1, value1, err := input1.GetKeyValuePair()

	require.NoError(t, err)
	require.Equal(t, "KEY_2", key1)
	require.Equal(t, "Value 2 CHANGED", value1)
}

func TestGetInputByKey(t *testing.T) {
	stepData := stepmanModels.StepModel{
		Inputs: []envmanModels.EnvironmentItemModel{
			envmanModels.EnvironmentItemModel{
				"KEY_1": "Value 1",
			},
			envmanModels.EnvironmentItemModel{
				"KEY_2": "Value 2",
			},
		},
	}

	_, found := getInputByKey(stepData, "KEY_1")
	require.Equal(t, true, found)

	_, found = getInputByKey(stepData, "KEY_3")
	require.Equal(t, false, found)
}

// ----------------------------
// --- StepIDData

func TestGetStepIDStepDataPair(t *testing.T) {
	stepData := stepmanModels.StepModel{}

	t.Log("valid steplist item")
	{
		stepListItem := StepListItemModel{
			"step1": stepData,
		}

		id, _, err := GetStepIDStepDataPair(stepListItem)
		require.NoError(t, err)
		require.Equal(t, "step1", id)
	}

	t.Log("invalid steplist item - more than 1 step")
	{
		stepListItem := StepListItemModel{
			"step1": stepData,
			"step2": stepData,
		}

		id, _, err := GetStepIDStepDataPair(stepListItem)
		require.Error(t, err)
		require.Equal(t, "", id)
	}
}

func TestCreateStepIDDataFromString(t *testing.T) {
	t.Log("default / long / verbose ID mode")
	{
		stepCompositeIDString := "steplib-src::step-id@0.0.1"
		stepIDData, err := CreateStepIDDataFromString(stepCompositeIDString, "")

		require.NoError(t, err)
		require.Equal(t, "steplib-src", stepIDData.SteplibSource)
		require.Equal(t, "step-id", stepIDData.IDorURI)
		require.Equal(t, "0.0.1", stepIDData.Version)
	}

	t.Log("no steplib-source")
	{
		stepCompositeIDString := "step-id@0.0.1"
		stepIDData, err := CreateStepIDDataFromString(stepCompositeIDString, "default-steplib-src")

		require.NoError(t, err)
		require.Equal(t, "default-steplib-src", stepIDData.SteplibSource)
		require.Equal(t, "step-id", stepIDData.IDorURI)
		require.Equal(t, "0.0.1", stepIDData.Version)
	}

	t.Log("invalid/empty step lib source, but default provided")
	{
		stepCompositeIDString := "::step-id@0.0.1"
		stepIDData, err := CreateStepIDDataFromString(stepCompositeIDString, "default-steplib-src")

		require.NoError(t, err)
		require.Equal(t, "default-steplib-src", stepIDData.SteplibSource)
		require.Equal(t, "step-id", stepIDData.IDorURI)
		require.Equal(t, "0.0.1", stepIDData.Version)
	}

	t.Log("invalid/empty step lib source + no default")
	{
		stepCompositeIDString := "::step-id@0.0.1"
		stepIDData, err := CreateStepIDDataFromString(stepCompositeIDString, "")

		require.Error(t, err)
		require.Equal(t, "", stepIDData.SteplibSource)
		require.Equal(t, "", stepIDData.IDorURI)
		require.Equal(t, "", stepIDData.Version)
	}

	t.Log("no steplib-source & no default -> fail")
	{
		stepCompositeIDString := "step-id@0.0.1"
		stepIDData, err := CreateStepIDDataFromString(stepCompositeIDString, "")

		require.Error(t, err)
		require.Equal(t, "", stepIDData.SteplibSource)
		require.Equal(t, "", stepIDData.IDorURI)
		require.Equal(t, "", stepIDData.Version)
	}

	t.Log("no steplib & no version, only step-id")
	{
		stepCompositeIDString := "step-id"
		stepIDData, err := CreateStepIDDataFromString(stepCompositeIDString, "def-lib-src")

		require.NoError(t, err)
		require.Equal(t, "def-lib-src", stepIDData.SteplibSource)
		require.Equal(t, "step-id", stepIDData.IDorURI)
		require.Equal(t, "", stepIDData.Version)
	}

	t.Log("empty test")
	{
		stepCompositeIDString := ""
		stepIDData, err := CreateStepIDDataFromString(stepCompositeIDString, "def-step-src")

		require.Error(t, err)
		require.Equal(t, "", stepIDData.SteplibSource)
		require.Equal(t, "", stepIDData.IDorURI)
		require.Equal(t, "", stepIDData.Version)
	}

	t.Log("special empty test")
	{
		stepCompositeIDString := "@1.0.0"
		stepIDData, err := CreateStepIDDataFromString(stepCompositeIDString, "def-step-src")

		require.Error(t, err)
		require.Equal(t, "", stepIDData.SteplibSource)
		require.Equal(t, "", stepIDData.IDorURI)
		require.Equal(t, "", stepIDData.Version)
	}

	//
	// ----- Local Path
	t.Log("local Path")
	{
		stepCompositeIDString := "path::/some/path"
		stepIDData, err := CreateStepIDDataFromString(stepCompositeIDString, "")

		require.NoError(t, err)
		require.Equal(t, "path", stepIDData.SteplibSource)
		require.Equal(t, "/some/path", stepIDData.IDorURI)
		require.Equal(t, "", stepIDData.Version)
	}

	t.Log("local Path")
	{
		stepCompositeIDString := "path::~/some/path/in/home"
		stepIDData, err := CreateStepIDDataFromString(stepCompositeIDString, "")

		require.NoError(t, err)
		require.Equal(t, "path", stepIDData.SteplibSource)
		require.Equal(t, "~/some/path/in/home", stepIDData.IDorURI)
		require.Equal(t, "", stepIDData.Version)
	}

	t.Log("local Path")
	{
		stepCompositeIDString := "path::$HOME/some/path/in/home"
		stepIDData, err := CreateStepIDDataFromString(stepCompositeIDString, "")

		require.NoError(t, err)
		require.Equal(t, "path", stepIDData.SteplibSource)
		require.Equal(t, "$HOME/some/path/in/home", stepIDData.IDorURI)
		require.Equal(t, "", stepIDData.Version)
	}

	//
	// ----- Direct git uri
	t.Log("direct git uri")
	{
		stepCompositeIDString := "git::https://github.com/bitrise-io/steps-timestamp.git@develop"
		stepIDData, err := CreateStepIDDataFromString(stepCompositeIDString, "some-def-coll")

		require.NoError(t, err)
		require.Equal(t, "git", stepIDData.SteplibSource)
		require.Equal(t, "https://github.com/bitrise-io/steps-timestamp.git", stepIDData.IDorURI)
		require.Equal(t, "develop", stepIDData.Version)
	}

	t.Log("direct git uri")
	{
		stepCompositeIDString := "git::git@github.com:bitrise-io/steps-timestamp.git@develop"
		stepIDData, err := CreateStepIDDataFromString(stepCompositeIDString, "")

		require.NoError(t, err)
		require.Equal(t, "git", stepIDData.SteplibSource)
		require.Equal(t, "git@github.com:bitrise-io/steps-timestamp.git", stepIDData.IDorURI)
		require.Equal(t, "develop", stepIDData.Version)
	}

	//
	// ----- Old step
	t.Log("old step")
	{
		stepCompositeIDString := "_::https://github.com/bitrise-io/steps-timestamp.git@1.0.0"
		stepIDData, err := CreateStepIDDataFromString(stepCompositeIDString, "")

		require.NoError(t, err)
		require.Equal(t, "_", stepIDData.SteplibSource)
		require.Equal(t, "https://github.com/bitrise-io/steps-timestamp.git", stepIDData.IDorURI)
		require.Equal(t, "1.0.0", stepIDData.Version)
	}
}

// ----------------------------
// --- RemoveRedundantFields

func TestRemoveEnvironmentRedundantFields(t *testing.T) {
	t.Log("Trivial remove - all fields should be default value")
	{
		env := envmanModels.EnvironmentItemModel{
			"TEST_KEY": "test_value",
			envmanModels.OptionsKey: envmanModels.EnvironmentItemOptionsModel{
				Title:             pointers.NewStringPtr(""),
				Description:       pointers.NewStringPtr(""),
				Summary:           pointers.NewStringPtr(""),
				ValueOptions:      []string{},
				IsRequired:        pointers.NewBoolPtr(envmanModels.DefaultIsRequired),
				IsExpand:          pointers.NewBoolPtr(envmanModels.DefaultIsExpand),
				IsDontChangeValue: pointers.NewBoolPtr(envmanModels.DefaultIsDontChangeValue),
				IsTemplate:        pointers.NewBoolPtr(envmanModels.DefaultIsTemplate),
			},
		}
		require.NoError(t, removeEnvironmentRedundantFields(&env))

		options, err := env.GetOptions()
		require.NoError(t, err)

		require.Equal(t, (*string)(nil), options.Title)
		require.Equal(t, (*string)(nil), options.Description)
		require.Equal(t, (*string)(nil), options.Summary)
		require.Equal(t, 0, len(options.ValueOptions))
		require.Equal(t, (*bool)(nil), options.IsRequired)
		require.Equal(t, (*bool)(nil), options.IsExpand)
		require.Equal(t, (*bool)(nil), options.IsDontChangeValue)
		require.Equal(t, (*bool)(nil), options.IsTemplate)
	}

	t.Log("Trivial don't remove - no fields should be default value")
	{
		env := envmanModels.EnvironmentItemModel{
			"TEST_KEY": "test_value",
			envmanModels.OptionsKey: envmanModels.EnvironmentItemOptionsModel{
				Title:             pointers.NewStringPtr("t"),
				Description:       pointers.NewStringPtr("d"),
				Summary:           pointers.NewStringPtr("s"),
				ValueOptions:      []string{"i"},
				IsRequired:        pointers.NewBoolPtr(true),
				IsExpand:          pointers.NewBoolPtr(false),
				IsDontChangeValue: pointers.NewBoolPtr(true),
				IsTemplate:        pointers.NewBoolPtr(true),
			},
		}
		require.NoError(t, removeEnvironmentRedundantFields(&env))

		options, err := env.GetOptions()
		require.NoError(t, err)

		require.Equal(t, "t", *options.Title)
		require.Equal(t, "d", *options.Description)
		require.Equal(t, "s", *options.Summary)
		require.Equal(t, "i", options.ValueOptions[0])
		require.Equal(t, true, *options.IsRequired)
		require.Equal(t, false, *options.IsExpand)
		require.Equal(t, true, *options.IsDontChangeValue)
		require.Equal(t, true, *options.IsTemplate)
	}

	t.Log("No options - opts field shouldn't exist")
	{
		env := envmanModels.EnvironmentItemModel{
			"TEST_KEY": "test_value",
		}
		require.NoError(t, removeEnvironmentRedundantFields(&env))

		_, ok := env[envmanModels.OptionsKey]
		require.Equal(t, false, ok)
	}
}

func configModelFromYAMLBytes(configBytes []byte) (bitriseData BitriseDataModel, err error) {
	if err = yaml.Unmarshal(configBytes, &bitriseData); err != nil {
		return
	}
	return
}

func TestRemoveWorkflowRedundantFields(t *testing.T) {
	configStr := `
format_version: 1.0.0
default_step_lib_source: "https://github.com/bitrise-io/bitrise-steplib.git"

app:
  summary: "sum"
  envs:
  - ENV_KEY: env_value
    opts:
      is_required: true

workflows:
  target:
    envs:
    - ENV_KEY: env_value
      opts:
        title: test_env
    title: Output Test
    steps:
    - script:
        description: test
`

	config, err := configModelFromYAMLBytes([]byte(configStr))
	require.NoError(t, err)

	err = config.RemoveRedundantFields()
	require.NoError(t, err)

	require.Equal(t, "", config.App.Title)
	require.Equal(t, "", config.App.Description)
	require.Equal(t, "sum", config.App.Summary)

	for _, env := range config.App.Environments {
		options, err := env.GetOptions()
		require.NoError(t, err)

		require.Nil(t, options.Title)
		require.Nil(t, options.Description)
		require.Nil(t, options.Summary)
		require.Equal(t, 0, len(options.ValueOptions))
		require.Equal(t, true, *options.IsRequired)
		require.Nil(t, options.IsExpand)
		require.Nil(t, options.IsDontChangeValue)
	}

	for _, workflow := range config.Workflows {
		require.Equal(t, "Output Test", workflow.Title)
		require.Equal(t, "", workflow.Description)
		require.Equal(t, "", workflow.Summary)

		for _, env := range workflow.Environments {
			options, err := env.GetOptions()
			require.NoError(t, err)

			require.Equal(t, "test_env", *options.Title)
			require.Nil(t, options.Description)
			require.Nil(t, options.Summary)
			require.Equal(t, 0, len(options.ValueOptions))
			require.Nil(t, options.IsRequired)
			require.Nil(t, options.IsExpand)
			require.Nil(t, options.IsDontChangeValue)
		}

		for _, stepListItem := range workflow.Steps {
			_, step, err := GetStepIDStepDataPair(stepListItem)
			require.NoError(t, err)

			require.Nil(t, step.Title)
			require.Equal(t, "test", *step.Description)
			require.Nil(t, step.Summary)
			require.Nil(t, step.Website)
			require.Nil(t, step.SourceCodeURL)
			require.Nil(t, step.SupportURL)
			require.Nil(t, step.PublishedAt)
			require.Equal(t, "", step.Source.Git)
			require.Equal(t, "", step.Source.Commit)
			require.Equal(t, 0, len(step.HostOsTags))
			require.Equal(t, 0, len(step.ProjectTypeTags))
			require.Equal(t, 0, len(step.TypeTags))
			require.Nil(t, step.IsRequiresAdminUser)
			require.Nil(t, step.IsAlwaysRun)
			require.Nil(t, step.IsSkippable)
			require.Nil(t, step.RunIf)
			require.Equal(t, 0, len(step.Inputs))
			require.Equal(t, 0, len(step.Outputs))
		}
	}
}


text:
try:
    from urllib.parse import urlparse
except ImportError:
    from urlparse import urlparse

# HACK: silence flakes unused import issue
urlparse

text_type = type(u'')

def want_bytes(s, encoding='utf-8'):
    if isinstance(s, text_type):
        s = s.encode(encoding)
    return s

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/win/conflicts/token_util.h"

#include "base/win/access_token.h"
#include "base/win/sid.h"
#include "third_party/abseil-cpp/absl/types/optional.h"

bool HasAdminRights() {
  absl::optional<base::win::AccessToken> token =
      base::win::AccessToken::FromCurrentProcess(/*impersonation=*/true);
  if (!token)
    return false;
  if (token->IsMember(base::win::WellKnownSid::kBuiltinAdministrators))
    return true;

  // In the case that UAC is enabled, it's possible that the current token is
  // filtered. So check the linked token in case it is a member of the built-in
  // Administrators group.
  absl::optional<base::win::AccessToken> linked_token = token->LinkedToken();
  if (!linked_token)
    return false;
  return linked_token->IsMember(
      base::win::WellKnownSid::kBuiltinAdministrators);
}


text:
.class Landroid/widget/PopupWindow$PopupViewContainer;
.super Landroid/widget/FrameLayout;
.source "PopupWindow.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/widget/PopupWindow;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x2
    name = "PopupViewContainer"
.end annotation

# static fields
.field private static final TAG:Ljava/lang/String; = "PopupWindow.PopupViewContainer"

# instance fields
.field final synthetic this$0:Landroid/widget/PopupWindow;

# direct methods
.method public constructor <init>(Landroid/widget/PopupWindow;Landroid/content/Context;)V
    .locals 0
    .param p2, "context"    # Landroid/content/Context;

    .prologue
    .line 1683
    iput-object p1, p0, Landroid/widget/PopupWindow$PopupViewContainer;->this$0:Landroid/widget/PopupWindow;

    .line 1684
    invoke-direct {p0, p2}, Landroid/widget/FrameLayout;-><init>(Landroid/content/Context;)V

    .line 1685
    return-void
.end method

# virtual methods
.method public dispatchKeyEvent(Landroid/view/KeyEvent;)Z
    .locals 4
    .param p1, "event"    # Landroid/view/KeyEvent;

    .prologue
    const/4 v1, 0x1

    .line 1701
    invoke-virtual {p1}, Landroid/view/KeyEvent;->getKeyCode()I

    move-result v2

    const/4 v3, 0x4

    if-ne v2, v3, :cond_4

    .line 1702
    invoke-virtual {p0}, Landroid/widget/PopupWindow$PopupViewContainer;->getKeyDispatcherState()Landroid/view/KeyEvent$DispatcherState;

    move-result-object v2

    if-nez v2, :cond_1

    .line 1703
    invoke-super {p0, p1}, Landroid/widget/FrameLayout;->dispatchKeyEvent(Landroid/view/KeyEvent;)Z

    move-result v1

    .line 1722
    :cond_0
    :goto_0
    return v1

    .line 1706
    :cond_1
    invoke-virtual {p1}, Landroid/view/KeyEvent;->getAction()I

    move-result v2

    if-nez v2, :cond_2

    invoke-virtual {p1}, Landroid/view/KeyEvent;->getRepeatCount()I

    move-result v2

    if-nez v2, :cond_2

    .line 1708
    invoke-virtual {p0}, Landroid/widget/PopupWindow$PopupViewContainer;->getKeyDispatcherState()Landroid/view/KeyEvent$DispatcherState;

    move-result-object v0

    .line 1709
    .local v0, "state":Landroid/view/KeyEvent$DispatcherState;
    if-eqz v0, :cond_0

    .line 1710
    invoke-virtual {v0, p1, p0}, Landroid/view/KeyEvent$DispatcherState;->startTracking(Landroid/view/KeyEvent;Ljava/lang/Object;)V

    goto :goto_0

    .line 1713
    .end local v0    # "state":Landroid/view/KeyEvent$DispatcherState;
    :cond_2
    invoke-virtual {p1}, Landroid/view/KeyEvent;->getAction()I

    move-result v2

    if-ne v2, v1, :cond_3

    .line 1714
    invoke-virtual {p0}, Landroid/widget/PopupWindow$PopupViewContainer;->getKeyDispatcherState()Landroid/view/KeyEvent$DispatcherState;

    move-result-object v0

    .line 1715
    .restart local v0    # "state":Landroid/view/KeyEvent$DispatcherState;
    if-eqz v0, :cond_3

    invoke-virtual {v0, p1}, Landroid/view/KeyEvent$DispatcherState;->isTracking(Landroid/view/KeyEvent;)Z

    move-result v2

    if-eqz v2, :cond_3

    invoke-virtual {p1}, Landroid/view/KeyEvent;->isCanceled()Z

    move-result v2

    if-nez v2, :cond_3

    .line 1716
    iget-object v2, p0, Landroid/widget/PopupWindow$PopupViewContainer;->this$0:Landroid/widget/PopupWindow;

    invoke-virtual {v2}, Landroid/widget/PopupWindow;->dismiss()V

    goto :goto_0

    .line 1720
    .end local v0    # "state":Landroid/view/KeyEvent$DispatcherState;
    :cond_3
    invoke-super {p0, p1}, Landroid/widget/FrameLayout;->dispatchKeyEvent(Landroid/view/KeyEvent;)Z

    move-result v1

    goto :goto_0

    .line 1722
    :cond_4
    invoke-super {p0, p1}, Landroid/widget/FrameLayout;->dispatchKeyEvent(Landroid/view/KeyEvent;)Z

    move-result v1

    goto :goto_0
.end method

.method public dispatchTouchEvent(Landroid/view/MotionEvent;)Z
    .locals 1
    .param p1, "ev"    # Landroid/view/MotionEvent;

    .prologue
    .line 1728
    iget-object v0, p0, Landroid/widget/PopupWindow$PopupViewContainer;->this$0:Landroid/widget/PopupWindow;

    # getter for: Landroid/widget/PopupWindow;->mTouchInterceptor:Landroid/view/View$OnTouchListener;
    invoke-static {v0}, Landroid/widget/PopupWindow;->access$900(Landroid/widget/PopupWindow;)Landroid/view/View$OnTouchListener;

    move-result-object v0

    if-eqz v0, :cond_0

    iget-object v0, p0, Landroid/widget/PopupWindow$PopupViewContainer;->this$0:Landroid/widget/PopupWindow;

    # getter for: Landroid/widget/PopupWindow;->mTouchInterceptor:Landroid/view/View$OnTouchListener;
    invoke-static {v0}, Landroid/widget/PopupWindow;->access$900(Landroid/widget/PopupWindow;)Landroid/view/View$OnTouchListener;

    move-result-object v0

    invoke-interface {v0, p0, p1}, Landroid/view/View$OnTouchListener;->onTouch(Landroid/view/View;Landroid/view/MotionEvent;)Z

    move-result v0

    if-eqz v0, :cond_0

    .line 1729
    const/4 v0, 0x1

    .line 1731
    :goto_0
    return v0

    :cond_0
    invoke-super {p0, p1}, Landroid/widget/FrameLayout;->dispatchTouchEvent(Landroid/view/MotionEvent;)Z

    move-result v0

    goto :goto_0
.end method

.method protected onCreateDrawableState(I)[I
    .locals 2
    .param p1, "extraSpace"    # I

    .prologue
    .line 1689
    iget-object v1, p0, Landroid/widget/PopupWindow$PopupViewContainer;->this$0:Landroid/widget/PopupWindow;

    # getter for: Landroid/widget/PopupWindow;->mAboveAnchor:Z
    invoke-static {v1}, Landroid/widget/PopupWindow;->access$700(Landroid/widget/PopupWindow;)Z

    move-result v1

    if-eqz v1, :cond_0

    .line 1691
    add-int/lit8 v1, p1, 0x1

    invoke-super {p0, v1}, Landroid/widget/FrameLayout;->onCreateDrawableState(I)[I

    move-result-object v0

    .line 1692
    .local v0, "drawableState":[I
    # getter for: Landroid/widget/PopupWindow;->ABOVE_ANCHOR_STATE_SET:[I
    invoke-static {}, Landroid/widget/PopupWindow;->access$800()[I

    move-result-object v1

    invoke-static {v0, v1}, Landroid/view/View;->mergeDrawableStates([I[I)[I

    .line 1695
    .end local v0    # "drawableState":[I
    :goto_0
    return-object v0

    :cond_0
    invoke-super {p0, p1}, Landroid/widget/FrameLayout;->onCreateDrawableState(I)[I

    move-result-object v0

    goto :goto_0
.end method

.method public onTouchEvent(Landroid/view/MotionEvent;)Z
    .locals 5
    .param p1, "event"    # Landroid/view/MotionEvent;

    .prologue
    invoke-direct/range {p0 .. p1}, Landroid/widget/PopupWindow$PopupViewContainer;->onFlymeTouchEvent(Landroid/view/MotionEvent;)Z

    move-result v0

    if-eqz v0, :cond_flyme_0

    const/4 v0, 0x1

    return v0

    :cond_flyme_0

    const/4 v2, 0x1

    .line 1736
    invoke-virtual {p1}, Landroid/view/MotionEvent;->getX()F

    move-result v3

    float-to-int v0, v3

    .line 1737
    .local v0, "x":I
    invoke-virtual {p1}, Landroid/view/MotionEvent;->getY()F

    move-result v3

    float-to-int v1, v3

    .line 1739
    .local v1, "y":I
    invoke-virtual {p1}, Landroid/view/MotionEvent;->getAction()I

    move-result v3

    if-nez v3, :cond_1

    if-ltz v0, :cond_0

    invoke-virtual {p0}, Landroid/widget/PopupWindow$PopupViewContainer;->getWidth()I

    move-result v3

    if-ge v0, v3, :cond_0

    if-ltz v1, :cond_0

    invoke-virtual {p0}, Landroid/widget/PopupWindow$PopupViewContainer;->getHeight()I

    move-result v3

    if-lt v1, v3, :cond_1

    .line 1741
    :cond_0
    iget-object v3, p0, Landroid/widget/PopupWindow$PopupViewContainer;->this$0:Landroid/widget/PopupWindow;

    invoke-virtual {v3}, Landroid/widget/PopupWindow;->dismiss()V

    .line 1747
    :goto_0
    return v2

    .line 1743
    :cond_1
    invoke-virtual {p1}, Landroid/view/MotionEvent;->getAction()I

    move-result v3

    const/4 v4, 0x4

    if-ne v3, v4, :cond_2

    .line 1744
    iget-object v3, p0, Landroid/widget/PopupWindow$PopupViewContainer;->this$0:Landroid/widget/PopupWindow;

    invoke-virtual {v3}, Landroid/widget/PopupWindow;->dismiss()V

    goto :goto_0

    .line 1747
    :cond_2
    invoke-super {p0, p1}, Landroid/widget/FrameLayout;->onTouchEvent(Landroid/view/MotionEvent;)Z

    move-result v2

    goto :goto_0
.end method

.method public sendAccessibilityEvent(I)V
    .locals 1
    .param p1, "eventType"    # I

    .prologue
    .line 1754
    iget-object v0, p0, Landroid/widget/PopupWindow$PopupViewContainer;->this$0:Landroid/widget/PopupWindow;

    # getter for: Landroid/widget/PopupWindow;->mContentView:Landroid/view/View;
    invoke-static {v0}, Landroid/widget/PopupWindow;->access$1000(Landroid/widget/PopupWindow;)Landroid/view/View;

    move-result-object v0

    if-eqz v0, :cond_0

    .line 1755
    iget-object v0, p0, Landroid/widget/PopupWindow$PopupViewContainer;->this$0:Landroid/widget/PopupWindow;

    # getter for: Landroid/widget/PopupWindow;->mContentView:Landroid/view/View;
    invoke-static {v0}, Landroid/widget/PopupWindow;->access$1000(Landroid/widget/PopupWindow;)Landroid/view/View;

    move-result-object v0

    invoke-virtual {v0, p1}, Landroid/view/View;->sendAccessibilityEvent(I)V

    .line 1759
    :goto_0
    return-void

    .line 1757
    :cond_0
    invoke-super {p0, p1}, Landroid/widget/FrameLayout;->sendAccessibilityEvent(I)V

    goto :goto_0
.end method

.method private onFlymeTouchEvent(Landroid/view/MotionEvent;)Z
    .locals 3
    .param p1, "event"    # Landroid/view/MotionEvent;

    .prologue
    iget-object v0, p0, Landroid/widget/PopupWindow$PopupViewContainer;->this$0:Landroid/widget/PopupWindow;

    iget-object v0, v0, Landroid/widget/PopupWindow;->mMzHelper:Landroid/widget/MzPopupWindowHelper;

    invoke-virtual {p0}, Landroid/widget/PopupWindow$PopupViewContainer;->getWidth()I

    move-result v1

    invoke-virtual {p0}, Landroid/widget/PopupWindow$PopupViewContainer;->getHeight()I

    move-result v2

    invoke-virtual {v0, p1, v1, v2}, Landroid/widget/MzPopupWindowHelper;->onTouchEvent(Landroid/view/MotionEvent;II)Z

    move-result v0

    return v0
.end method


text:
(function() {
/** code for recognition of script path */
var myScript = $("script:last")[0].src;
var ownComponentName = "org.scn.community.basics.PasswordField";
var _readScriptPath = function () {
	var scriptInfo = org_scn_community_basics.readOwnScriptAccess(myScript, ownComponentName);
	return scriptInfo.myScriptPath;
};
/** end of path recognition */

sap.ui.commons.PasswordField.extend(ownComponentName, {

  	initDesignStudio: function() {
		var that = this;
		this._ownScript = _readScriptPath();

		this.addStyleClass("scn-pack-PasswordField");

		this.attachChange(function() {
			that.fireDesignStudioPropertiesChanged(["value"]);
			that.fireDesignStudioEvent("onChanged");
		});
  	},

	renderer: {},

	afterDesignStudioUpdate : function() {
		// no code
	},
});
})();


text:
/*
 *
 * YamlFoldParser.java - Fold parser for YAML.
 *
 * This library is distributed under a modified BSD license.  See the included
 * LICENSE file for details.
 */
package org.fife.ui.rsyntaxtextarea.folding;

import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.Token;

import javax.swing.text.BadLocationException;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * Fold parser for YAML. Based on org.fife.ui.rsyntaxtextarea.folding.HtmlFoldParser.
 *
 * Fold is started by each line.
 * Each fold contains all following lines with indent higher than the current line.
 */
public class YamlFoldParser implements FoldParser {

    /**
     * Constructor.
     *
     */
    public YamlFoldParser() {
    }

	private static boolean isSpaces(Token t) {
        String lexeme = t.getLexeme();
        return lexeme.trim().isEmpty();
    }

    @Override
    public List<Fold> getFolds(RSyntaxTextArea textArea) {

        List<Fold> folds = new ArrayList<>();
        Stack<Integer> indentStack = new Stack<>();

        Fold currentFold = null;
        int lineCount = textArea.getLineCount();

        // closing needs to be done with offset of the previous line
        int lastOffset = 0;

        try {

            for (int line=0; line<lineCount; line++) {

                Token t = textArea.getTokenListForLine(line);
                if (!t.isPaintable()) {
                	continue; // Skip empty lines
				}
                Token startLine = t;
                int offset = t.getOffset();

                // indent level is count of spaces + possible one for leading minus
                int indent = 0;
                while (t!=null && t.isPaintable() && isSpaces(t)) {
                    indent += t.length();
                    t = t.getNextToken();
                }
                if (t != null && t.isPaintable() && t.isSingleChar('-')) {
                    indent++;
                    t = t.getNextToken();
                }

                while (!indentStack.empty()) {
                    int outer = indentStack.peek();
                    if (outer >= indent && currentFold != null) {
                        currentFold.setEndOffset(lastOffset);
                        Fold parentFold = currentFold.getParent();
                        // Don't add fold markers for single-line blocks
                        if (currentFold.isOnSingleLine()) {
							removeFold(currentFold, folds);
                        }
                        currentFold = parentFold;
                        indentStack.pop();
                    } else {
                        break;
                    }
                }

                // scan until the end of the line
                while (t != null && t.isPaintable()) {
                    offset = t.getOffset();
                    t = t.getNextToken();
                }
                lastOffset = offset;

                if (currentFold==null) {
                    currentFold = new Fold(FoldType.CODE, textArea, startLine.getOffset());
                    folds.add(currentFold);
                } else {
                    currentFold = currentFold.createChild(FoldType.CODE, startLine.getOffset());
                }
                indentStack.push(indent);

            }

        } catch (BadLocationException ble) { // Should never happen
            ble.printStackTrace();
        }

        return folds;

    }

    /**
     * If this fold has a parent fold, this method removes it from its parent.
     * Otherwise, it's assumed to be the most recent (top-level) fold in the
     * folds list, and is removed from that.
     *
     * @param fold The fold to remove.
     * @param folds The list of top-level folds.
     */
    private static void removeFold(Fold fold, List<Fold> folds) {
        if (!fold.removeFromParent()) {
            folds.remove(folds.size()-1);
        }
    }

}


text:
{{player.name}}

	    	{{'TRAINER-MODALE-USERS-REMOVE-PLAYER-BTN' | translate}}


text:
package info.novatec.testit.webtester.conditions.syntax;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;

import info.novatec.testit.webtester.conditions.Condition;

@RunWith(MockitoJUnitRunner.class)
public class IsTest {

    Object object = new Object();

    @Test
    public void trueConditionEvaluatesToTrue() {
        Is<Object> is = new Is<>(object -> true);
        assertThat(is.test(object)).isTrue();
    }

    @Test
    public void falseConditionEvaluatesToFalse() {
        Is<Object> is = new Is<>(object -> false);
        assertThat(is.test(object)).isFalse();
    }

    @Test
    public void toStringIsGeneratedCorrectly() {
        Condition<Object> condition = mock(Condition.class);
        doReturn("condition").when(condition).toString();
        assertThat(new Is<>(condition)).hasToString("is(condition)");
    }

}


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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Globalization;

#if NETFX_CORE
using Windows.UI;
#else
#endif

namespace Neos.IdentityServer.MultiFactor.QrEncoding.Windows.Render
{
	public class EncapsulatedPostScriptRenderer
	{
		private ISizeCalculation m_iSize;

#if NETFX_CORE
        private Color m_DarkColor;
        private Color m_LightColor;
#else
        private GColor m_DarkColor;
        private GColor m_LightColor;
#endif

		private EpsModuleDrawingTechnique m_DrawingTechnique;

		/// <summary>
		/// Initializes a Encapsulated PostScript renderer.
		/// </summary>
		/// <param name="darkColor">DarkColor used to draw Dark modules of the QrCode</param>
		/// <param name="lightColor">LightColor used to draw Light modules and QuietZone of the QrCode.
		/// Setting to a transparent color (A = 0) allows transparent light modules so the QR Code blends in the existing background.
		/// In that case the existing background should remain light and rather uniform, and higher error correction levels are recommended.</param>
        /// <param name="quietZoneModules"></param>
#if NETFX_CORE
        public EncapsulatedPostScriptRenderer(ISizeCalculation iSize, Color darkColor, Color lightColor)
        {
#else
        public EncapsulatedPostScriptRenderer(ISizeCalculation iSize, GColor darkColor, GColor lightColor)
		{
#endif
			m_iSize = iSize;
			m_DarkColor = darkColor;
			m_LightColor = lightColor;
			m_DrawingTechnique = EpsModuleDrawingTechnique.Squares;
		}

		/// <summary>
		/// Renders the matrix in an Encapsuled PostScript format.
		/// </summary>
		/// <param name="matrix">The matrix to be rendered</param>
		/// <param name="moduleSize">Size in points (1 inch contains 72 point in PostScript) of a module</param>
		/// <param name="stream">Output stream that must be writable</param>
		public void WriteToStream(BitMatrix matrix, Stream stream)
		{
			using (var writer = new StreamWriter(stream))
			{
				int width = matrix == null ? 21 : matrix.Width;

				DrawingSize drawingSize = m_iSize.GetSize(width);

				OutputHeader(drawingSize, writer);
				OutputBackground(writer);

				if (matrix != null)
				{
					switch (m_DrawingTechnique)
					{
						case EpsModuleDrawingTechnique.Squares:
							DrawSquares(matrix, writer);
							break;
						case EpsModuleDrawingTechnique.Image:
							DrawImage(matrix, writer);
							break;
						default:
							throw new ArgumentOutOfRangeException("DrawingTechnique");
					}
				}

				OutputFooter(writer);
			}
		}

		/// <summary>
		/// Outputs the EPS header with mandatory declarations, variable declarations and function definitions.
		/// </summary>
		/// <param name="matrix">The matrix to be rendered</param>
		/// <param name="moduleSize">Size in points (1 inch contains 72 point in PostScript) of a module</param>
		/// <param name="stream">Output text stream</param>
		private void OutputHeader(DrawingSize drawingSize, StreamWriter stream)
		{
			string strHeader = @"%!PS-Adobe-3.0 EPSF-3.0
%%Creator: Gma.QrCodeNet
%%Title: QR Code
%%CreationDate: {0:yyyyMMdd}
%%Pages: 1
%%BoundingBox: 0 0 {1} {2}
%%Document-Fonts: Times-Roman
%%LanguageLevel: 1
%%EndComments
%%BeginProlog
/w {{ {3} }} def
/h {{ {4} }} def
/q {{ {5} }} def
/s {{ {6} }} def
/W {{ w q q add add }} def
/H {{ h q q add add }} def";

			string strBoxFunctions = @"% Define the box functions taking X and Y coordinates of the top left corner and filling a 1 point large square
/b { newpath moveto 1 0 rlineto 0 1 rlineto -1 0 rlineto closepath fill } def
/br { newpath moveto 1.01 0 rlineto 0 1 rlineto -1.01 0 rlineto closepath fill } def
/bb { newpath moveto 1 0 rlineto 0 1.01 rlineto -1 0 rlineto closepath fill } def
/brb { newpath moveto 1.01 0 rlineto 0 1 rlineto -0.01 0 rlineto 0 0.01 rlineto -1 0 rlineto closepath fill } def";

			string strHeaderEnd = @"%%EndProlog
%%Page: 1 1

% Save the current state
save

% Invert the Y axis
0 W s mul translate
s s neg scale";

			stream.WriteLine(string.Format(strHeader,
				DateTime.UtcNow,
				// Use invariant culture to ensure that the dot is used as the decimal separator
				(drawingSize.CodeWidth).ToString(CultureInfo.InvariantCulture.NumberFormat), // Size in points of the matrix with the quiet zone
				(drawingSize.CodeWidth).ToString(CultureInfo.InvariantCulture.NumberFormat),
				drawingSize.CodeWidth / drawingSize.ModuleSize - ((int)drawingSize.QuietZoneModules * 2), // Number of modules of the matrix without the quiet zone
				drawingSize.CodeWidth / drawingSize.ModuleSize - ((int)drawingSize.QuietZoneModules * 2),
				(int)drawingSize.QuietZoneModules, // Number of quiet zone modules
				drawingSize.ModuleSize.ToString(CultureInfo.InvariantCulture.NumberFormat))); // Size in points of a single module

			if (m_DrawingTechnique == EpsModuleDrawingTechnique.Squares)
				stream.WriteLine(strBoxFunctions);

			stream.WriteLine(strHeaderEnd);
		}

		/// <summary>
		/// Outputs the background unless it is defined as transparent. The background is used for light modules and quiet zone.
		/// </summary>
		/// <param name="matrix">The matrix to be rendered</param>
		/// <param name="stream">Output text stream</param>
		private void OutputBackground(StreamWriter stream)
		{
			string strBackground = @"
% Create the background
{0} 255 div {1} 255 div {2} 255 div setrgbcolor
newpath 0 0 moveto W 0 rlineto 0 H rlineto W neg 0 rlineto closepath fill";

			if (LightColor.A != 0)
				stream.WriteLine(string.Format(strBackground,
					LightColor.R,
					LightColor.G,
					LightColor.B));
		}

		/// <summary>
		/// Draw a square for each dark module
		/// </summary>
		/// <param name="matrix">The matrix to be rendered</param>
		/// <param name="stream">Output text stream</param>
		private void DrawSquares(BitMatrix matrix, StreamWriter stream)
		{
			string strSquaresHeader = @"
% Draw squares
{0} 255 div {1} 255 div {2} 255 div setrgbcolor
q q translate";

			stream.WriteLine(string.Format(strSquaresHeader,
				DarkColor.R,
				DarkColor.G,
				DarkColor.B));

			for (int y = 0; y < matrix.Height; ++y)
			{
				for (int x = 0; x < matrix.Width; ++x)
				{
					if (matrix[x, y]) // Only draw dark modules
					{
						bool bHasRightNeighbor = x + 1 < matrix.Width && matrix[x + 1, y];
						bool bHasBottomNeighbor = y + 1 < matrix.Height && matrix[x, y + 1];
						// If the dark module has a dark neighbor on the right, make the two boxed overlap 1% by calling "br" instead of simply "b"
						// Same applies for bottom neighbor with "bb" command, or "brb" for right and bottom dark neighbors.
						// Overlapping two modules avoids having tiny gaps appearing on certain zoom scales or output devices.

						// Output the coordinates of the upper left corner and call to the box function
						stream.WriteLine(string.Format("{0} {1} b{2}{3}", x, y, bHasRightNeighbor ? "r" : "", bHasBottomNeighbor ? "b" : ""));
					}
				}
			}
		}

		/// <summary>
		/// Use the 'image' or 'colorimage' PostScript command to render modules
		/// </summary>
		/// <param name="matrix">The matrix to be rendered</param>
		/// <param name="stream">Output text stream</param>
		private void DrawImage(BitMatrix matrix, StreamWriter stream)
		{
			bool bGrayScale =
				LightColor.R == LightColor.G &&
				LightColor.G == LightColor.B &&
				DarkColor.R == DarkColor.G &&
				DarkColor.G == DarkColor.B;
			string strLightColor = string.Empty;
			string strDarkColor = string.Empty;
			if (bGrayScale)
			{
				strLightColor = LightColor.R.ToString("x2");
				strDarkColor = DarkColor.R.ToString("x2");
			}
			else
			{
				strLightColor = string.Format("{0:x2}{1:x2}{2:x2}", LightColor.R, LightColor.G, LightColor.B);
				strDarkColor = string.Format("{0:x2}{1:x2}{2:x2}", DarkColor.R, DarkColor.G, DarkColor.B);
			}

			stream.WriteLine(@"% Draw squares
q q translate
w h scale
w h 8 [w 0 0 h 0 0]
{<");
			for (int y = 0; y < matrix.Height; ++y)
			{
				for (int x = 0; x < matrix.Width; ++x)
					stream.Write(matrix[x, y] ? strDarkColor : strLightColor);
				stream.WriteLine();
			}
			stream.WriteLine(">}");
			stream.WriteLine(bGrayScale ? "image" : "false 3 colorimage");
		}

		/// <summary>
		/// Outputs the mandatory EPS footer.
		/// </summary>
		/// <param name="stream">Output text stream</param>
		private void OutputFooter(StreamWriter stream)
		{
			string strFooter = @"
% Restore the initial state
restore showpage
%
% End of page
%
%%Trailer
%%EOF";

			stream.Write(strFooter);
		}

		/// <summary>
		/// ISizeCalculation for the way to calculate QrCode's pixel size.
		/// Ex for ISizeCalculation:FixedCodeSize, FixedModuleSize
		/// </summary>
		public ISizeCalculation SizeCalculator
		{
			set
			{
				m_iSize = value;
			}
			get
			{
				return m_iSize;
			}
		}

		/// <summary>
		/// DarkColor used to draw Dark modules of the QrCode
        /// </summary>
#if NETFX_CORE
        public Color DarkColor
        {
#else
        public GColor DarkColor
		{
#endif
			set
			{
				m_DarkColor = value;
			}
			get
			{
				return m_DarkColor;
			}
		}

		/// <summary>
		/// LightColor used to draw Light modules and QuietZone of the QrCode.
		/// Setting to a transparent color (A = 0) allows transparent light modules so the QR Code blends in the existing background.
		/// In that case the existing background should remain light and rather uniform, and higher error correction levels are recommended.
        /// </summary>
#if NETFX_CORE
        public Color LightColor
        {
#else
        public GColor LightColor
		{
#endif
			set
			{
				m_LightColor = value;
			}
			get
			{
				return m_LightColor;
			}
		}

		/// <summary>
		/// Selection of the technique used to draw the modules. 'Squares' draws vector squares one by one; 'Image' uses the 'image' or 'colorimage' PostScript command.
		/// 'Squares' supports transparency of light modules and often has smaller file size for color QR Codes.
		/// 'Image' might be faster to render on some devices as it is a single command.
		/// </summary>
		public EpsModuleDrawingTechnique DrawingTechnique
		{
			get
			{
				return m_DrawingTechnique;
			}
			set
			{
				m_DrawingTechnique = value;
			}
		}
	}
	public enum EpsModuleDrawingTechnique
	{
		Squares,
		Image
	};
}


text:
<?php namespace FFMPEGWrapper\Option;

use FFMPEGWrapper\FFMPEG;

abstract class FFMPEGOption {

    /**
     * @param FFMPEG $ffmpeg
     *
     * @return void
     */
    public function check(FFMPEG $ffmpeg)
    {
        // noop
    }

    /**
     * @return string
     */
    public function toFFMPEGArgOption()
    {
        return "";
    }

    /**
     * @return array
     */
    public function toFFMPEGEnvOption()
    {
        return [];
    }
}


text:
ACCEPTED

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

#### Published in
in Crous & Braun, CBS Diversity Ser. (Utrecht) 1: 368 (2003)

#### Original name
Cercospora scandicearum Magnus, 1893

### Remarks
null


text:
<!DOCTYPE  html>

    <meta charset="utf-8">

    <title>doc</title>

Source Map

This is a library to generate and consume the source map format
described here.

This library is written in the Asynchronous Module Definition format, and works
in the following environments:

Modern Browsers supporting ECMAScript 5 (either after the build, or with an
AMD loader such as RequireJS)

Inside Firefox (as a JSM file, after the build)

With NodeJS versions 0.8.X and higher

Node

$ npm install source-map

Building from Source (for everywhere else)

Install Node and then run

$ git clone https://fitzgen@github.com/mozilla/source-map.git
$ cd source-map
$ npm link .

Next, run

$ node Makefile.dryice.js

This should spew a bunch of stuff to stdout, and create the following files:

dist/source-map.js - The unminified browser version.

dist/source-map.min.js - The minified browser version.

dist/SourceMap.jsm - The JavaScript Module for inclusion in Firefox source.

Examples

Consuming a source map

var rawSourceMap = {
  version: 3,
  file: 'min.js',
  names: ['bar', 'baz', 'n'],
  sources: ['one.js', 'two.js'],
  sourceRoot: 'http://example.com/www/js/',
  mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA'
};

var smc = new SourceMapConsumer(rawSourceMap);

console.log(smc.sources);
// [ 'http://example.com/www/js/one.js',
//   'http://example.com/www/js/two.js' ]

console.log(smc.originalPositionFor({
  line: 2,
  column: 28
}));
// { source: 'http://example.com/www/js/two.js',
//   line: 2,
//   column: 10,
//   name: 'n' }

console.log(smc.generatedPositionFor({
  source: 'http://example.com/www/js/two.js',
  line: 2,
  column: 10
}));
// { line: 2, column: 28 }

smc.eachMapping(function (m) {
  // ...
});

Generating a source map

In depth guide:
Compiling to JavaScript, and Debugging with Source Maps

With SourceNode (high level API)

function compile(ast) {
  switch (ast.type) {
  case 'BinaryExpression':
    return new SourceNode(
      ast.location.line,
      ast.location.column,
      ast.location.source,
      [compile(ast.left), " + ", compile(ast.right)]
    );
  case 'Literal':
    return new SourceNode(
      ast.location.line,
      ast.location.column,
      ast.location.source,
      String(ast.value)
    );
  // ...
  default:
    throw new Error("Bad AST");
  }
}

var ast = parse("40 + 2", "add.js");
console.log(compile(ast).toStringWithSourceMap({
  file: 'add.js'
}));
// { code: '40 + 2',
//   map: [object SourceMapGenerator] }

With SourceMapGenerator (low level API)

var map = new SourceMapGenerator({
  file: "source-mapped.js"
});

map.addMapping({
  generated: {
    line: 10,
    column: 35
  },
  source: "foo.js",
  original: {
    line: 33,
    column: 2
  },
  name: "christopher"
});

console.log(map.toString());
// '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}'

API

Get a reference to the module:

// NodeJS
var sourceMap = require('source-map');

// Browser builds
var sourceMap = window.sourceMap;

// Inside Firefox
let sourceMap = {};
Components.utils.import('resource:///modules/devtools/SourceMap.jsm', sourceMap);

SourceMapConsumer

A SourceMapConsumer instance represents a parsed source map which we can query
for information about the original file positions by giving it a file position
in the generated source.

new SourceMapConsumer(rawSourceMap)

The only parameter is the raw source map (either as a string which can be
JSON.parse'd, or an object). According to the spec, source maps have the
following attributes:

version: Which version of the source map spec this map is following.

sources: An array of URLs to the original source files.

names: An array of identifiers which can be referrenced by individual
mappings.

sourceRoot: Optional. The URL root from which all sources are relative.

sourcesContent: Optional. An array of contents of the original source files.

mappings: A string of base64 VLQs which contain the actual mappings.

file: Optional. The generated filename this source map is associated with.

SourceMapConsumer.prototype.originalPositionFor(generatedPosition)

Returns the original source, line, and column information for the generated
source's line and column positions provided. The only argument is an object with
the following properties:

line: The line number in the generated source.

column: The column number in the generated source.

and an object is returned with the following properties:

source: The original source file, or null if this information is not
available.

line: The line number in the original source, or null if this information is
not available.

column: The column number in the original source, or null or null if this
information is not available.

name: The original identifier, or null if this information is not available.

SourceMapConsumer.prototype.generatedPositionFor(originalPosition)

Returns the generated line and column information for the original source,
line, and column positions provided. The only argument is an object with
the following properties:

source: The filename of the original source.

line: The line number in the original source.

column: The column number in the original source.

and an object is returned with the following properties:

line: The line number in the generated source, or null.

column: The column number in the generated source, or null.

SourceMapConsumer.prototype.sourceContentFor(source)

Returns the original source content for the source provided. The only
argument is the URL of the original source file.

SourceMapConsumer.prototype.eachMapping(callback, context, order)

Iterate over each mapping between an original source/line/column and a
generated line/column in this source map.

callback: The function that is called with each mapping. Mappings have the
form { source, generatedLine, generatedColumn, originalLine, originalColumn,
name }

context: Optional. If specified, this object will be the value of this
every time that callback is called.

order: Either SourceMapConsumer.GENERATED_ORDER or
SourceMapConsumer.ORIGINAL_ORDER. Specifies whether you want to iterate over
the mappings sorted by the generated file's line/column order or the
original's source/line/column order, respectively. Defaults to
SourceMapConsumer.GENERATED_ORDER.

SourceMapGenerator

An instance of the SourceMapGenerator represents a source map which is being
built incrementally.

new SourceMapGenerator([startOfSourceMap])

You may pass an object with the following properties:

file: The filename of the generated source that this source map is
associated with.

sourceRoot: A root for all relative URLs in this source map.

SourceMapGenerator.fromSourceMap(sourceMapConsumer)

Creates a new SourceMapGenerator based on a SourceMapConsumer

sourceMapConsumer The SourceMap.

SourceMapGenerator.prototype.addMapping(mapping)

Add a single mapping from original source line and column to the generated
source's line and column for this source map being created. The mapping object
should have the following properties:

generated: An object with the generated line and column positions.

original: An object with the original line and column positions.

source: The original source file (relative to the sourceRoot).

name: An optional original token name for this mapping.

SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)

Set the source content for an original source file.

sourceFile the URL of the original source file.

sourceContent the content of the source file.

SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])

Applies a SourceMap for a source file to the SourceMap.
Each mapping to the supplied source file is rewritten using the
supplied SourceMap. Note: The resolution for the resulting mappings
is the minimium of this map and the supplied map.

sourceMapConsumer: The SourceMap to be applied.

sourceFile: Optional. The filename of the source file.
If omitted, sourceMapConsumer.file will be used, if it exists.
Otherwise an error will be thrown.

sourceMapPath: Optional. The dirname of the path to the SourceMap
to be applied. If relative, it is relative to the SourceMap.

This parameter is needed when the two SourceMaps aren't in the same
directory, and the SourceMap to be applied contains relative source
paths. If so, those relative source paths need to be rewritten
relative to the SourceMap.

If omitted, it is assumed that both SourceMaps are in the same directory,
thus not needing any rewriting. (Supplying '.' has the same effect.)

SourceMapGenerator.prototype.toString()

Renders the source map being generated to a string.

SourceNode

SourceNodes provide a way to abstract over interpolating and/or concatenating
snippets of generated JavaScript source code, while maintaining the line and
column information associated between those snippets and the original source
code. This is useful as the final intermediate representation a compiler might
use before outputting the generated JS and source map.

new SourceNode([line, column, source[, chunk[, name]]])

line: The original line number associated with this source node, or null if
it isn't associated with an original line.

column: The original column number associated with this source node, or null
if it isn't associated with an original column.

source: The original source's filename; null if no filename is provided.

chunk: Optional. Is immediately passed to SourceNode.prototype.add, see
below.

name: Optional. The original identifier.

SourceNode.fromStringWithSourceMap(code, sourceMapConsumer)

Creates a SourceNode from generated code and a SourceMapConsumer.

code: The generated code

sourceMapConsumer The SourceMap for the generated code

SourceNode.prototype.add(chunk)

Add a chunk of generated JS to this source node.

chunk: A string snippet of generated JS code, another instance of
 SourceNode, or an array where each member is one of those things.

SourceNode.prototype.prepend(chunk)

Prepend a chunk of generated JS to this source node.

chunk: A string snippet of generated JS code, another instance of
 SourceNode, or an array where each member is one of those things.

SourceNode.prototype.setSourceContent(sourceFile, sourceContent)

Set the source content for a source file. This will be added to the
SourceMap in the sourcesContent field.

sourceFile: The filename of the source file

sourceContent: The content of the source file

SourceNode.prototype.walk(fn)

Walk over the tree of JS snippets in this node and its children. The walking
function is called once for each snippet of JS and is passed that snippet and
the its original associated source's line/column location.

fn: The traversal function.

SourceNode.prototype.walkSourceContents(fn)

Walk over the tree of SourceNodes. The walking function is called for each
source file content and is passed the filename and source content.

fn: The traversal function.

SourceNode.prototype.join(sep)

Like Array.prototype.join except for SourceNodes. Inserts the separator
between each of this source node's children.

sep: The separator.

SourceNode.prototype.replaceRight(pattern, replacement)

Call String.prototype.replace on the very right-most source snippet. Useful
for trimming whitespace from the end of a source node, etc.

pattern: The pattern to replace.

replacement: The thing to replace the pattern with.

SourceNode.prototype.toString()

Return the string representation of this source node. Walks over the tree and
concatenates all the various snippets together to one string.

SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])

Returns the string representation of this tree of source nodes, plus a
SourceMapGenerator which contains all the mappings between the generated and
original sources.

The arguments are the same as those to new SourceMapGenerator.

Tests

Install NodeJS version 0.8.0 or greater, then run node test/run-tests.js.

To add new tests, create a new file named test/test-<your new test name>.js
and export your test functions with names that start with "test", for example

exports["test doing the foo bar"] = function (assert, util) {
  ...
};

The new test will be located automatically when you run the suite.

The util argument is the test utility module located at test/source-map/util.

The assert argument is a cut down version of node's assert module. You have
access to the following assertion functions:

doesNotThrow

equal

ok

strictEqual

throws

(The reason for the restricted set of test functions is because we need the
tests to run inside Firefox's test suite as well and so the assert module is
shimmed in that environment. See build/assert-shim.js.)


text:
import React, { Component } from 'react'
import './App.css'
import './assets/css/bootstrap.css'
import StepPersonal from './component/StepPersonal'
import StepDoctor from './component/StepDoctor'
import StepGoals from './component/StepGoals'
import StepHistory from './component/StepHistory'
import StepImage from './component/StepImage'
import StepInsurance from './component/StepInsurance'
import StepSubmit from './component/StepSubmit'
import AppStore, { Steps } from './store/AppStore'
import ProgressBar from './component/ProgressBar'
import Footer from './component/Footer'

class App extends Component {
  constructor(props){
    super(props)

    this.state = AppStore.getState()

    this.onStoreUpdate = this.onStoreUpdate.bind(this)
    this.renderStep = this.renderStep.bind(this)
  }

  componentWillMount(){
    window.addEventListener('StoreUpdate', this.onStoreUpdate)
  }

  componentWillUnMount(){
    window.removeEventListener('StoreUpdate', this.onStoreUpdate)
  }

  onStoreUpdate(){
    this.setState(AppStore.getState())
  }

  renderStep(){
    switch(this.state.step){
      case Steps.PERSONAL:
        return <StepPersonal data={this.state.personal} />
      case Steps.IMAGE:
        return <StepImage data={this.state.image} />
      case Steps.HISTORY:
        return <StepHistory data={this.state.history} />
      case Steps.GOALS:
        return <StepGoals data={this.state.goal} />
      case Steps.DOCTOR:
        return <StepDoctor data={this.state.doctor} />
      case Steps.INSURANCE:
        return <StepInsurance data={this.state.insurance} />
      case Steps.SUBMIT:
        return <StepSubmit data={this.state} />
      default:
        return
Bad step

    }
  }

  render() {
    return (

CompanyName Patient Signup

        <ProgressBar step={this.state.step} maxStep={Steps.SUBMIT} />
        {this.renderStep()}

    )
  }
}

export default App


text:
/**
 * Histogram is the base class for Column and Bar series.
 *
 * @class Histogram
 * @constructor
 */
function Histogram(){}

Histogram.prototype = {
    /**
     * @protected
     *
     * Draws the series.
     *
     * @method drawSeries
     */
    drawSeries: function()
    {
        if(this.get("xcoords").length < 1)
        {
            return;
        }
        var style = Y.clone(this.get("styles").marker),
            setSize,
            calculatedSize,
            xcoords = this.get("xcoords"),
            ycoords = this.get("ycoords"),
            i = 0,
            len = xcoords.length,
            top = ycoords[0],
            type = this.get("type"),
            graph = this.get("graph"),
            seriesCollection = graph.seriesTypes[type],
            seriesLen = seriesCollection.length,
            seriesSize = 0,
            totalSize = 0,
            offset = 0,
            ratio,
            renderer,
            order = this.get("order"),
            graphOrder = this.get("graphOrder"),
            left,
            marker,
            setSizeKey,
            calculatedSizeKey,
            config,
            fillColors = null,
            borderColors = null,
            hotspot,
            isChrome = ISCHROME;
        if(Y.Lang.isArray(style.fill.color))
        {
            fillColors = style.fill.color.concat();
        }
        if(Y.Lang.isArray(style.border.color))
        {
            borderColors = style.border.colors.concat();
        }
        if(this.get("direction") == "vertical")
        {
            setSizeKey = "height";
            calculatedSizeKey = "width";
        }
        else
        {
            setSizeKey = "width";
            calculatedSizeKey = "height";
        }
        setSize = style[setSizeKey];
        calculatedSize = style[calculatedSizeKey];
        this._createMarkerCache();
        if(isChrome)
        {
            this._createHotspotCache();
        }
        for(; i < seriesLen; ++i)
        {
            renderer = seriesCollection[i];
            seriesSize += renderer.get("styles").marker[setSizeKey];
            if(order > i)
            {
                offset = seriesSize;
            }
        }
        totalSize = len * seriesSize;
        if(totalSize > graph.get(setSizeKey))
        {
            ratio = graph.get(setSizeKey)/totalSize;
            seriesSize *= ratio;
            offset *= ratio;
            setSize *= ratio;
            setSize = Math.max(setSize, 1);
        }
        offset -= seriesSize/2;
        for(i = 0; i < len; ++i)
        {
            config = this._getMarkerDimensions(xcoords[i], ycoords[i], calculatedSize, offset);
            top = config.top;
            calculatedSize = config.calculatedSize;
            left = config.left;
            style[setSizeKey] = setSize;
            style[calculatedSizeKey] = calculatedSize;
            if(fillColors)
            {
                style.fill.color = fillColors[i % fillColors.length];
            }
            if(borderColors)
            {
                style.border.colors = borderColors[i % borderColors.length];
            }
            marker = this.getMarker(style, graphOrder, i);
            marker.setPosition(left, top);
            if(isChrome)
            {
                hotspot = this.getHotspot(style, graphOrder, i);
                hotspot.setPosition(left, top);
                hotspot.parentNode.style.zIndex = 5;
            }
        }
        this._clearMarkerCache();
        if(isChrome)
        {
            this._clearHotspotCache();
        }
    },

    /**
     * @private
     */
    _defaultFillColors: ["#66007f", "#a86f41", "#295454", "#996ab2", "#e8cdb7", "#90bdbd","#000000","#c3b8ca", "#968373", "#678585"],

    /**
     * @private
     */
    _getPlotDefaults: function()
    {
        var defs = {
            fill:{
                type: "solid",
                alpha: 1,
                colors:null,
                alphas: null,
                ratios: null
            },
            border:{
                weight: 0,
                alpha: 1
            },
            width: 12,
            height: 12,
            shape: "rect",

            padding:{
                top: 0,
                left: 0,
                right: 0,
                bottom: 0
            }
        };
        defs.fill.color = this._getDefaultColor(this.get("graphOrder"), "fill");
        defs.border.color = this._getDefaultColor(this.get("graphOrder"), "border");
        return defs;
    }
};

Y.Histogram = Histogram;


text:
  Bergères-lès-Vertus est
       un village
       localisé dans le département de Marne en Champagne-Ardenne. Elle totalisait 538 habitants en 2008.

La commune propose quelques  aménagements, elle propose entre autres un terrain de tennis et un terrain de sport.

À Bergères-lès-Vertus, la valeur moyenne à l'achat d'un appartement s'évalue à 493 € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 1 113 € du m². À la location la valorisation moyenne se situe à 8,41 € du m² par mois.

Si vous pensez emmenager à Bergères-lès-Vertus, vous pourrez aisément trouver une maison à acheter.

Le nombre d'habitations, à Bergères-lès-Vertus, était réparti en 2011 en 17 appartements et 243 maisons soit
 un marché plutôt équilibré.

À coté de Bergères-lès-Vertus sont situées les communes de
Le Mesnil-sur-Oger située à 7 km, 1 239 habitants,
Gionges à 6 km, 148 habitants,
Givry-lès-Loisy localisée à 6 km, 78 habitants,
Val-des-Marais située à 7 km, 544 habitants,
Trécon à 5 km, 79 habitants,
Voipreux à 4 km, 204 habitants,
 entre autres. De plus, Bergères-lès-Vertus est située à seulement 27 km de Châlons-en-Champagne.


text:
package org.apache.commons.math4.legacy.genetics;

import org.apache.commons.math4.legacy.exception.NumberIsTooSmallException;

/**
 * Stops after a fixed number of generations.
 *

 * Each time {@link #isSatisfied(Population)} is invoked, a generation counter
 * is incremented. Once the counter reaches the configured
 * {@code maxGenerations} value, {@link #isSatisfied(Population)} returns true.
 *
 * @since 2.0
 */
public class FixedGenerationCount implements StoppingCondition {
    /** Number of generations that have passed. */
    private int numGenerations;

    /** Maximum number of generations (stopping criteria). */
    private final int maxGenerations;

    /**
     * Create a new FixedGenerationCount instance.
     *
     * @param maxGenerations number of generations to evolve
     * @throws NumberIsTooSmallException if the number of generations is < 1
     */
    public FixedGenerationCount(final int maxGenerations) throws NumberIsTooSmallException {
        if (maxGenerations <= 0) {
            throw new NumberIsTooSmallException(maxGenerations, 1, true);
        }
        this.maxGenerations = maxGenerations;
    }

    /**
     * Determine whether or not the given number of generations have passed. Increments the number of generations
     * counter if the maximum has not been reached.
     *
     * @param population ignored (no impact on result)
     * @return true IFF the maximum number of generations has been exceeded
     */
    @Override
    public boolean isSatisfied(final Population population) {
        if (this.numGenerations < this.maxGenerations) {
            numGenerations++;
            return false;
        }
        return true;
    }

    /**
     * Returns the number of generations that have already passed.
     * @return the number of generations that have passed
     */
    public int getNumGenerations() {
        return numGenerations;
    }
}


text:
typedef struct nni_taskq nni_taskq;
typedef struct nni_task  nni_task;

extern int  nni_taskq_init(nni_taskq **, int);
extern void nni_taskq_fini(nni_taskq *);

// nni_task_dispatch sends the task to the queue.  It is guaranteed to
// succeed.  (If the queue is shutdown, then the behavior is undefined.)
extern void nni_task_dispatch(nni_task *);

// nni_task_exec runs the task synchronously, if possible.  (Under certain
// circumstances the task must be run asynchronously.)  The caller is
// responsible for ensuring that it does not hold any resources which might
// be acquired by the task itself; otherwise deadlock may occur.  (When in
// doubt, use nni_task_dispatch instead.)
extern void nni_task_exec(nni_task *);

// nni_task_prep is used by and exclusively for the aio framework.
// nni_task_prep marks the task as "scheduled" without actually
// dispatching anything to it yet; nni_task_wait will block waiting for the
// task to complete normally (after a call to nni_task_dispatch or
// nni_task_exec).
extern void nni_task_prep(nni_task *);

// nni_task_abort is called to undo the effect of nni_task_prep,
// basically. The aio framework uses this when nni_aio_schedule()
// returns an error.
extern void nni_task_abort(nni_task *);

extern void nni_task_wait(nni_task *);
extern void  nni_task_init(nni_task *, nni_taskq *, nni_cb, void *);

// nni_task_fini destroys the task.  It will reap resources asynchronously
// if the task is currently executing.  Use nni_task_wait() first if the
// callback must be stopped entirely before destroying the task (such as if
// it reschedules the task.)
extern void nni_task_fini(nni_task *);

extern int  nni_taskq_sys_init(void);
extern void nni_taskq_sys_fini(void);

// nni_task implementation details are not to be used except by the
// nni_task_framework.  Placing here allows for inlining this in
// consuming structures.
struct nni_task {
	nni_list_node task_node;
	void *        task_arg;
	nni_cb        task_cb;
	nni_taskq *   task_tq;
	unsigned      task_busy;
	bool          task_prep;
	nni_mtx       task_mtx;
	nni_cv        task_cv;
};

#endif // CORE_TASKQ_H


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PSQ
{
    class Helpers
    {
        internal static void ExecutePowerShellScript(string scriptPath)
        {
            try
            {
                Process process = new Process();
                process.StartInfo.FileName = @"c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe";
                process.StartInfo.Arguments = @"-noprofile -executionpolicy bypass -nologo -file """ + scriptPath + @"""";
                process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                process.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "An error occured", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}


text:
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

		<LINK rel="stylesheet" type="text/css" href="popup.css">

Welcome to the Heroes Draft Helper!

					This tool is designed to help with the draft process for your Heroes of the Storm game.
					In order to operate, you'll need to Collect some data from HotsLogs.com using the buttons below.
					You can re-visit any of the pages feeds to update to the most current data, but at a minimum you'll need to load the Maps data, the Hero Sub-Role data, and at least one Player's win rates using the buttons below.
					Each Button will take you to the appropriate HotsLogs location, and you'll see a new button embedded on that page to "Store" that data.
					Be sure to load your friends' Player data, too, and update as needed!

				0 Player record(s).

				<button id="collect_player_data" type="button" class="btn btn-primary collect-data"> Collect Player Data</button>

				0 Map records.

				<button id="collect_map_data" type="button" class="btn btn-primary collect-data"> Collect Map Data</button>

				0 Hero/Role records.

				<button id="collect_role_data" type="button" class="btn btn-primary collect-data"> Collect Hero Data</button>

				0 Hero Detail records.

				<button id="collect_hero_detail_data" type="button" class="btn btn-primary collect-data"> Collect Hero Details</button>


text:
import Math_degreesPerTurns from './degreesPerTurns';

export default function(n) {
	return n * Math_degreesPerTurns;
}


text:
package com.example.android.sunshine;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.android.sunshine.ForecastAdapter.ForecastAdapterOnClickHandler;
import com.example.android.sunshine.data.SunshinePreferences;
import com.example.android.sunshine.utilities.NetworkUtils;
import com.example.android.sunshine.utilities.OpenWeatherJsonUtils;

import java.net.URL;

// COMPLETED (8) Implement ForecastAdapterOnClickHandler from the MainActivity
public class MainActivity extends AppCompatActivity implements ForecastAdapterOnClickHandler {

    private RecyclerView mRecyclerView;
    private ForecastAdapter mForecastAdapter;

    private TextView mErrorMessageDisplay;

    private ProgressBar mLoadingIndicator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forecast);

        /*
         * Using findViewById, we get a reference to our RecyclerView from xml. This allows us to
         * do things like set the adapter of the RecyclerView and toggle the visibility.
         */
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview_forecast);

        /* This TextView is used to display errors and will be hidden if there are no errors */
        mErrorMessageDisplay = (TextView) findViewById(R.id.tv_error_message_display);

        /*
         * LinearLayoutManager can support HORIZONTAL or VERTICAL orientations. The reverse layout
         * parameter is useful mostly for HORIZONTAL layouts that should reverse for right to left
         * languages.
         */
        LinearLayoutManager layoutManager
                = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);

        mRecyclerView.setLayoutManager(layoutManager);

        /*
         * Use this setting to improve performance if you know that changes in content do not
         * change the child layout size in the RecyclerView
         */
        mRecyclerView.setHasFixedSize(true);

        // COMPLETED (11) Pass in 'this' as the ForecastAdapterOnClickHandler
        /*
         * The ForecastAdapter is responsible for linking our weather data with the Views that
         * will end up displaying our weather data.
         */
        mForecastAdapter = new ForecastAdapter(this);

        /* Setting the adapter attaches it to the RecyclerView in our layout. */
        mRecyclerView.setAdapter(mForecastAdapter);

        /*
         * The ProgressBar that will indicate to the user that we are loading data. It will be
         * hidden when no data is loading.
         *
         * Please note: This so called "ProgressBar" isn't a bar by default. It is more of a
         * circle. We didn't make the rules (or the names of Views), we just follow them.
         */
        mLoadingIndicator = (ProgressBar) findViewById(R.id.pb_loading_indicator);

        /* Once all of our views are setup, we can load the weather data. */
        loadWeatherData();
    }

    /**
     * This method will get the user's preferred location for weather, and then tell some
     * background method to get the weather data in the background.
     */
    private void loadWeatherData() {
        String location = SunshinePreferences.getPreferredWeatherLocation(this);
        new FetchWeatherTask().execute(location);
    }

    // COMPLETED (9) Override ForecastAdapterOnClickHandler's onClick method
    // COMPLETED (10) Show a Toast when an item is clicked, displaying that item's weather data
    /**
     * This method is overridden by our MainActivity class in order to handle RecyclerView item
     * clicks.
     *
     * @param weatherForDay The weather for the day that was clicked
     */
    @Override
    public void onClick(String weatherForDay) {
        Context context = this;
        Toast.makeText(context, weatherForDay, Toast.LENGTH_SHORT)
                .show();
    }

    /**
     * This method will make the View for the weather data visible and
     * hide the error message.
     *

     * Since it is okay to redundantly set the visibility of a View, we don't
     * need to check whether each view is currently visible or invisible.
     */
    private void showWeatherDataView() {
        /* First, make sure the error is invisible */
        mErrorMessageDisplay.setVisibility(View.INVISIBLE);
        /* Then, make sure the weather data is visible */
        mRecyclerView.setVisibility(View.VISIBLE);
    }

    /**
     * This method will make the error message visible and hide the weather
     * View.
     *

     * Since it is okay to redundantly set the visibility of a View, we don't
     * need to check whether each view is currently visible or invisible.
     */
    private void showErrorMessage() {
        /* First, hide the currently visible data */
        mRecyclerView.setVisibility(View.INVISIBLE);
        /* Then, show the error */
        mErrorMessageDisplay.setVisibility(View.VISIBLE);
    }

    public class FetchWeatherTask extends AsyncTask<String, Void, String[]> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mLoadingIndicator.setVisibility(View.VISIBLE);
        }

        @Override
        protected String[] doInBackground(String... params) {

            /* If there's no zip code, there's nothing to look up. */
            if (params.length == 0) {
                return null;
            }

            String location = params[0];
            URL weatherRequestUrl = NetworkUtils.buildUrl(location);

            try {
                String jsonWeatherResponse = NetworkUtils
                        .getResponseFromHttpUrl(weatherRequestUrl);

                String[] simpleJsonWeatherData = OpenWeatherJsonUtils
                        .getSimpleWeatherStringsFromJson(MainActivity.this, jsonWeatherResponse);

                return simpleJsonWeatherData;

            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(String[] weatherData) {
            mLoadingIndicator.setVisibility(View.INVISIBLE);
            if (weatherData != null) {
                showWeatherDataView();
                mForecastAdapter.setWeatherData(weatherData);
            } else {
                showErrorMessage();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        /* Use AppCompatActivity's method getMenuInflater to get a handle on the menu inflater */
        MenuInflater inflater = getMenuInflater();
        /* Use the inflater's inflate method to inflate our menu layout to this menu */
        inflater.inflate(R.menu.forecast, menu);
        /* Return true so that the menu is displayed in the Toolbar */
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_refresh) {
            mForecastAdapter.setWeatherData(null);
            loadWeatherData();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


text:
import unittest
import ConfigParser

from utils.configurator import Configurator

class TestConfigurator(unittest.TestCase):

    def setUp(self):
        self.conf = Configurator()

    def test_set_output(self):
        self.conf.set_output(filename="test.txt", fileformat="csv", compound="test")
        self.assertEqual(self.conf.scrapy_settings["FEED_URI"], "test.txt")
        self.assertEqual(self.conf.scrapy_settings["FEED_FORMAT"], "csv")

        self.conf.set_output("<compound>.*format*", "jsonlines", "test")
        self.assertEqual(self.conf.scrapy_settings["FEED_URI"], "test.json")
        self.assertEqual(self.conf.scrapy_settings["FEED_FORMAT"], "jsonlines")

        self.conf.set_output("<compound>.*format*", "csv", "test")
        self.assertEqual(self.conf.scrapy_settings["FEED_URI"], "test.csv")
        self.assertEqual(self.conf.scrapy_settings["FEED_FORMAT"], "csv")

    def test_start_log(self):
        for i in range(0, 3):
            self.conf.set_logging("TEST", i)
            self.assertEqual(self.conf.scrapy_settings.get("LOG_FILE"), "TEST")
            if i > 0:
                self.assertEqual(self.conf.scrapy_settings.get("LOG_ENABLED"), True)
                if i > 1:
                    self.assertEqual(self.conf.scrapy_settings.get("LOG_STDOUT"), False)
                else:
                    self.assertEqual(self.conf.scrapy_settings.get("LOG_STDOUT"), True)
            else:
                self.assertEqual(self.conf.scrapy_settings.get("LOG_ENABLED"), False)
                self.assertEqual(self.conf.scrapy_settings.get("LOG_STDOUT"), True)
            if i == 1:
                self.assertEqual(self.conf.scrapy_settings.get("LOG_LEVEL"), "WARNING")
            elif i == 2:
                self.assertEqual(self.conf.scrapy_settings.get("LOG_LEVEL"), "INFO")
            elif i == 3:
                self.assertEqual(self.conf.scrapy_settings.get("LOG_LEVEL"), "DEBUG")

            self.conf.set_logging(verbose=i)
            self.assertEqual(self.conf.scrapy_settings.get("LOG_FILE"), None)

    def test_read_sourceconfiguration(self):
        config = self.conf.read_sourceconfiguration()
        self.assertIsInstance(config, ConfigParser.ConfigParser)

    def test_get_section(self):
        config = ConfigParser.ConfigParser()
        section = self.conf.get_section(config, 'test')
        self.assertIn('reliability', section)
        self.assertEquals(section['reliability'], '')

        config.set('DEFAULT', 'reliability', 'Low')

        section = self.conf.get_section(config, 'test')
        self.assertEquals(section['reliability'], 'Low')

        config.add_section('test')
        config.set('test', 'var', 'Maybe')

        section = self.conf.get_section(config, 'test')
        self.assertEquals(section['reliability'], 'Low')
        self.assertEqual(section['var'], 'Maybe')


text:
package tk.mybatis.springboot.mapper;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.springboot.Application;
import tk.mybatis.springboot.model.City2;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liuzh
 * @since 2016-03-06 17:42
 */
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@Transactional
@SpringApplicationConfiguration(Application.class)
public class MyBatis331Test {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private MyBatis331Mapper mapper;

    @Test
    @Rollback
    public void testInsertList() {
        List<City2> city2List = new ArrayList<City2>();
        city2List.add(new City2("石家庄", "河北"));
        city2List.add(new City2("邯郸", "河北"));
        city2List.add(new City2("秦皇岛", "河北"));
        Assert.assertEquals(3, mapper.insertCities(city2List));
        for (City2 c2 : city2List) {
            logger.info(c2.toString());
            Assert.assertNotNull(c2.getId());
        }
    }

    @Test
    public void testSelectById(){
        City2 city2 = mapper.selectByCityId(1);
        logger.info(city2.toString());
        Assert.assertNotNull(city2);
        Assert.assertNotNull(city2.getCityName());
        Assert.assertNotNull(city2.getCityState());
    }

    @Test
    public void testSelectAll(){
        List<City2> city2List = mapper.selectAll();
        for(City2 c2 : city2List){
            logger.info(c2.toString());
            Assert.assertNotNull(c2);
            Assert.assertNotNull(c2.getCityName());
            Assert.assertNotNull(c2.getCityState());
        }
    }

}


text:
from designate import objects
from designate.objects.adapters.api_v2 import base

class PoolNsRecordAPIv2Adapter(base.APIv2Adapter):
    ADAPTER_OBJECT = objects.PoolNsRecord
    MODIFICATIONS = {
        'fields': {
            'priority': {
                'read_only': False
            },
            'hostname': {
                'read_only': False
            },
        },
        'options': {
            'links': False,
            'resource_name': 'ns_record',
            'collection_name': 'ns_records',
        }
    }

class PoolNsRecordListAPIv2Adapter(base.APIv2Adapter):
    ADAPTER_OBJECT = objects.PoolNsRecordList
    MODIFICATIONS = {
        'options': {
            'links': False,
            'resource_name': 'ns_record',
            'collection_name': 'ns_records',
        }
    }

    @classmethod
    def render_list(cls, list_objects, *args, **kwargs):
        r_list = super(PoolNsRecordListAPIv2Adapter, cls).render_list(
            list_objects, *args, **kwargs)
        return r_list[cls.MODIFICATIONS['options']['collection_name']]