text:
typedef struct actor_struct Actor;

typedef struct actor_struct {
    SDL_Point pos;
    SDL_Point vel;
    SDL_Point acc;
    SDL_Rect textureBox;
    SDL_Texture *texture;
    double angle;
    void (*update)(Actor *, Uint32);
    void (*draw)(Actor *);
} Actor;

Actor* createActor();

#endif


text:
/*
	Used by the Leasing Server to interact with swarming.
*/
package main

import (
	"context"
	"fmt"
	"strings"

	swarming_api "go.chromium.org/luci/common/api/swarming/swarming/v1"
	"golang.org/x/oauth2/google"
	"google.golang.org/api/compute/v1"

	"go.skia.org/infra/go/cas"
	"go.skia.org/infra/go/cas/rbe"
	"go.skia.org/infra/go/httputils"
	"go.skia.org/infra/go/skerr"
	"go.skia.org/infra/go/swarming"
	"go.skia.org/infra/leasing/go/types"
)

// SwarmingInstanceClients contains all of the API clients needed to interact
// with a given Swarming instance.
type SwarmingInstanceClients struct {
	SwarmingServer string
	SwarmingClient *swarming.ApiClient

	CasClient   *cas.CAS
	CasInstance string
}

var (
	casClientPublic  cas.CAS
	casClientPrivate cas.CAS

	swarmingClientPublic  swarming.ApiClient
	swarmingClientPrivate swarming.ApiClient

	// PublicSwarming contains the API clients needed for the public Swarming
	// instance.
	PublicSwarming *SwarmingInstanceClients = &SwarmingInstanceClients{
		SwarmingServer: swarming.SWARMING_SERVER,
		SwarmingClient: &swarmingClientPublic,
		CasClient:      &casClientPublic,
		CasInstance:    rbe.InstanceChromiumSwarm,
	}

	// InternalSwarming contains the API clients needed for the internal
	// Swarming instance.
	InternalSwarming *SwarmingInstanceClients = &SwarmingInstanceClients{
		SwarmingServer: swarming.SWARMING_SERVER_PRIVATE,
		SwarmingClient: &swarmingClientPrivate,
		CasClient:      &casClientPrivate,
		CasInstance:    rbe.InstanceChromeSwarming,
	}

	// PoolsToSwarmingInstance maps Swarming pool names to Swarming instances.
	PoolsToSwarmingInstance = map[string]*SwarmingInstanceClients{
		"Skia":             PublicSwarming,
		"SkiaCT":           PublicSwarming,
		"SkiaInternal":     InternalSwarming,
		"CT":               InternalSwarming,
		"CTAndroidBuilder": InternalSwarming,
		"CTLinuxBuilder":   InternalSwarming,
	}

	cpythonPackage = &swarming_api.SwarmingRpcsCipdPackage{
		PackageName: "infra/3pp/tools/cpython3/${platform}",
		Path:        "python",
		Version:     "version:2@3.8.10.chromium.19",
	}
)

// SwarmingInit initializes Swarming globally.
func SwarmingInit(ctx context.Context, serviceAccountFile string) error {
	ts, err := google.DefaultTokenSource(ctx, swarming.AUTH_SCOPE, compute.CloudPlatformScope)
	if err != nil {
		return skerr.Wrapf(err, "Problem setting up default token source")
	}

	// Public CAS client.
	casClientPublic, err = rbe.NewClient(context.TODO(), rbe.InstanceChromiumSwarm, ts)
	if err != nil {
		return skerr.Wrapf(err, "Failed to create RBE client")
	}

	// Private CAS client.
	casClientPrivate, err = rbe.NewClient(context.TODO(), rbe.InstanceChromeSwarming, ts)
	if err != nil {
		return skerr.Wrapf(err, "Failed to create RBE client")
	}

	// Authenticated HTTP client.
	httpClient := httputils.DefaultClientConfig().WithTokenSource(ts).With2xxOnly().Client()

	// Public Swarming API client.
	swarmingClientPublic, err = swarming.NewApiClient(httpClient, swarming.SWARMING_SERVER)
	if err != nil {
		return skerr.Wrapf(err, "Failed to create public swarming client")
	}
	// Private Swarming API client.
	swarmingClientPrivate, err = swarming.NewApiClient(httpClient, swarming.SWARMING_SERVER_PRIVATE)
	if err != nil {
		return skerr.Wrapf(err, "Failed to create private swarming client")
	}

	return nil
}

// GetSwarmingInstance returns the Swarming instance for the given Swarming
// pool.
func GetSwarmingInstance(pool string) *SwarmingInstanceClients {
	return PoolsToSwarmingInstance[pool]
}

// GetSwarmingClient returns the Swarming client for the given Swarming pool.
func GetSwarmingClient(pool string) *swarming.ApiClient {
	return GetSwarmingInstance(pool).SwarmingClient
}

// GetCASClient returns the CAS client for the given Swarming pool.
func GetCASClient(pool string) *cas.CAS {
	return GetSwarmingInstance(pool).CasClient
}

func getPoolDetails(ctx context.Context, pool string) (*types.PoolDetails, error) {
	swarmingClient := *GetSwarmingClient(pool)
	bots, err := swarmingClient.ListBotsForPool(ctx, pool)
	if err != nil {
		return nil, fmt.Errorf("Could not list bots in pool: %s", err)
	}
	osTypes := map[string]int{}
	osToDeviceTypes := map[string]map[string]int{}
	for _, bot := range bots {
		if bot.IsDead || bot.Quarantined {
			// Do not include dead/quarantined bots in the counts below.
			continue
		}
		osType := ""
		deviceType := ""
		for _, d := range bot.Dimensions {
			if d.Key == "os" {
				val := ""
				// Use the longest string from the os values because that is what the swarming UI
				// does and it works in all cases we have (atleast as of 11/1/17).
				for _, v := range d.Value {
					if len(v) > len(val) {
						val = v
					}
				}
				osType = val
			}
			if d.Key == "device_type" {
				// There should only be one value for device type.
				deviceType = d.Value[0]
			}
		}
		osTypes[osType]++
		if _, ok := osToDeviceTypes[osType]; !ok {
			osToDeviceTypes[osType] = map[string]int{}
		}
		if deviceType != "" {
			osToDeviceTypes[osType][deviceType]++
		}
	}
	return &types.PoolDetails{
		OsTypes:         osTypes,
		OsToDeviceTypes: osToDeviceTypes,
	}, nil
}

// GetDetailsOfAllPools returns details for each of the known Swarming pools.
func GetDetailsOfAllPools(ctx context.Context) (map[string]*types.PoolDetails, error) {
	poolToDetails := map[string]*types.PoolDetails{}
	for pool := range PoolsToSwarmingInstance {
		details, err := getPoolDetails(ctx, pool)
		if err != nil {
			return nil, err
		}
		poolToDetails[pool] = details
	}
	return poolToDetails, nil
}

// AddLeasingArtifactsToCAS uploads the leasing artifacts and merges them into
// the given CAS input if it exists.
func AddLeasingArtifactsToCAS(ctx context.Context, pool string, casInput *swarming_api.SwarmingRpcsCASReference) (string, error) {
	client := *GetCASClient(pool)

	// Upload the leasing artifacts.
	// TODO(rmistry): After this has been done once, we should be able to just
	// use the digest as a constant.
	leasingScriptDigest, err := client.Upload(ctx, *artifactsDir, []string{"leasing.py"}, nil)
	if err != nil {
		return "", skerr.Wrap(err)
	}
	if casInput == nil {
		return leasingScriptDigest, nil
	}
	return client.Merge(ctx, []string{leasingScriptDigest, rbe.DigestToString(casInput.Digest.Hash, casInput.Digest.SizeBytes)})
}

// GetSwarmingTask retrieves the given Swarming task.
func GetSwarmingTask(ctx context.Context, pool, taskID string) (*swarming_api.SwarmingRpcsTaskResult, error) {
	swarmingClient := *GetSwarmingClient(pool)
	return swarmingClient.GetTask(ctx, taskID, false)
}

// GetSwarmingTaskMetadata returns the metadata for the given Swarming task.
func GetSwarmingTaskMetadata(ctx context.Context, pool, taskID string) (*swarming_api.SwarmingRpcsTaskRequestMetadata, error) {
	swarmingClient := *GetSwarmingClient(pool)
	return swarmingClient.GetTaskMetadata(ctx, taskID)
}

// IsBotIDValid returns true iff the given bot exists in the given pool.
func IsBotIDValid(ctx context.Context, pool, botID string) (bool, error) {
	swarmingClient := *GetSwarmingClient(pool)
	dims := map[string]string{
		"pool": pool,
		"id":   botID,
	}
	bots, err := swarmingClient.ListBots(ctx, dims)
	if err != nil {
		return false, fmt.Errorf("Could not query swarming bots with %s: %s", dims, err)
	}
	if len(bots) > 1 {
		return false, fmt.Errorf("Something went wrong, more than 1 bot was returned with %s: %s", dims, err)
	}
	if len(bots) == 0 {
		// There were no matches for the pool + botId combination.
		return false, nil
	}
	if bots[0].BotId == botID {
		return true, nil
	}
	return false, fmt.Errorf("%s returned %s instead of the expected %s", dims, bots[1].BotId, botID)
}

// TriggerSwarmingTask triggers the given Swarming task.
func TriggerSwarmingTask(ctx context.Context, pool, requester, datastoreID, osType, deviceType, botID, serverURL, casDigest, relativeCwd string, cipdInput *swarming_api.SwarmingRpcsCipdInput, cmd []string) (string, error) {
	dimsMap := map[string]string{
		"pool": pool,
	}
	if osType != "" {
		dimsMap["os"] = osType
	}
	if deviceType != "" {
		dimsMap["device_type"] = deviceType
	}
	if botID != "" {
		dimsMap["id"] = botID
	}
	dims := make([]*swarming_api.SwarmingRpcsStringPair, 0, len(dimsMap))
	for k, v := range dimsMap {
		dims = append(dims, &swarming_api.SwarmingRpcsStringPair{
			Key:   k,
			Value: v,
		})
	}

	// Always include cpython for Windows. See skbug.com/9501 for context and
	// for why we do not include it for all architectures.
	pythonBinary := "python/bin/python3"
	if cipdInput == nil {
		cipdInput = &swarming_api.SwarmingRpcsCipdInput{}
	}
	if cipdInput.Packages == nil {
		cipdInput.Packages = []*swarming_api.SwarmingRpcsCipdPackage{cpythonPackage}
	} else {
		cipdInput.Packages = append(cipdInput.Packages, cpythonPackage)
	}

	// Arguments that will be passed to leasing.py
	extraArgs := []string{
		"--task-id", datastoreID,
		"--os-type", osType,
		"--leasing-server", serverURL,
		"--debug-command", strings.Join(cmd, " "),
		"--command-relative-dir", relativeCwd,
	}

	// Construct the command.
	command := []string{pythonBinary, "leasing.py"}
	command = append(command, extraArgs...)

	swarmingInstance := GetSwarmingInstance(pool)
	expirationSecs := int64(swarming.RECOMMENDED_EXPIRATION.Seconds())
	executionTimeoutSecs := int64(swarmingHardTimeout.Seconds())
	ioTimeoutSecs := int64(swarmingHardTimeout.Seconds())
	taskName := fmt.Sprintf("Leased by %s using leasing.skia.org", requester)
	taskRequest := &swarming_api.SwarmingRpcsNewTaskRequest{
		Name:     taskName,
		Priority: leaseTaskPriority,
		TaskSlices: []*swarming_api.SwarmingRpcsTaskSlice{
			{
				ExpirationSecs: expirationSecs,
				Properties: &swarming_api.SwarmingRpcsTaskProperties{
					CipdInput:            cipdInput,
					Dimensions:           dims,
					ExecutionTimeoutSecs: executionTimeoutSecs,
					Command:              command,
					IoTimeoutSecs:        ioTimeoutSecs,
				},
			},
		},
		User: "skiabot@google.com",
	}

	casInput, err := swarming.MakeCASReference(casDigest, swarmingInstance.CasInstance)
	if err != nil {
		return "", skerr.Wrapf(err, "Invalid CAS input")
	}
	taskRequest.TaskSlices[0].Properties.CasInputRoot = casInput

	swarmingClient := *GetSwarmingClient(pool)
	resp, err := swarmingClient.TriggerTask(ctx, taskRequest)
	if err != nil {
		return "", fmt.Errorf("Could not trigger swarming task %s", err)
	}
	return resp.TaskId, nil
}

// GetSwarmingTaskLink returns a link to the given Swarming task.
func GetSwarmingTaskLink(server, taskID string) string {
	return fmt.Sprintf("https://%s/task?id=%s", server, taskID)
}

// GetSwarmingBotLink returns a link to the given Swarming bot.
func GetSwarmingBotLink(server, botID string) string {
	return fmt.Sprintf("https://%s/bot?id=%s", server, botID)
}

redpajama_set_name: RedPajamaGithub


text:
import React, { PropTypes } from 'react';
import { Link, IndexLink} from 'react-router';

const Header = () => {
    return (

                <IndexLink to="/" activeClassName="active">Super Heroes</IndexLink>

                <Link to="/about" activeClassName="active">About</Link>

                Github

    );
};

export default Header;


text:
/******************************************************************************
  This source file is part of the Avogadro project.
  This source code is released under the 3-Clause BSD License, (see "LICENSE").
******************************************************************************/

#include "lammpsinput.h"

#include "lammpsinputdialog.h"

#include <avogadro/io/fileformat.h>
#include <avogadro/qtgui/fileformatdialog.h>
#include <avogadro/qtgui/molecule.h>

#include <QtCore/QDebug>

#include <QtWidgets/QAction>
#include <QtWidgets/QMessageBox>

namespace Avogadro {
namespace Core {
class Molecule;
}
namespace QtPlugins {

LammpsInput::LammpsInput(QObject* parent_)
  : ExtensionPlugin(parent_), m_action(new QAction(this)), m_molecule(nullptr),
    m_dialog(nullptr), m_outputFormat(nullptr)
{
  m_action->setEnabled(true);
  m_action->setText(tr("&LAMMPS…"));
  connect(m_action, SIGNAL(triggered()), SLOT(menuActivated()));
}

LammpsInput::~LammpsInput()
{
}

QList<QAction*> LammpsInput::actions() const
{
  QList<QAction*> actions_;
  actions_.append(m_action);
  return actions_;
}

QStringList LammpsInput::menuPath(QAction*) const
{
  QStringList path;
  path << tr("&Input");
  return path;
}

void LammpsInput::setMolecule(QtGui::Molecule* mol)
{
  if (m_dialog)
    m_dialog->setMolecule(mol);
  m_molecule = mol;
}

bool LammpsInput::readMolecule(QtGui::Molecule& mol)
{
  Io::FileFormat* reader = m_outputFormat->newInstance();
  bool success = reader->readFile(m_outputFileName.toStdString(), mol);
  if (!success) {
    QMessageBox::information(qobject_cast<QWidget*>(parent()), tr("Error"),
                             tr("Error reading output file '%1':\n%2")
                               .arg(m_outputFileName)
                               .arg(QString::fromStdString(reader->error())));
  }

  m_outputFormat = nullptr;
  m_outputFileName.clear();

  return success;
}

void LammpsInput::menuActivated()
{
  if (!m_dialog) {
    m_dialog = new LammpsInputDialog(qobject_cast<QWidget*>(parent()));
  }
  m_dialog->setMolecule(m_molecule);
  m_dialog->show();
}
}
}


text:
namespace blink {

// A list of state regarding the error in AudioWorkletProcessor object.
enum class AudioWorkletProcessorErrorState : unsigned {
  // The constructor or the process method in the processor has not thrown any
  // exception.
  kNoError = 0,

  // An exception thrown from the construction failure.
  kConstructionError = 1,

  // An exception thrown from the process method.
  kProcessError = 2,
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_MODULES_WEBAUDIO_AUDIO_WORKLET_PROCESSOR_ERROR_STATE_H_


text:
package io.fabric8.webui.agents.monitor

import io.fabric8.api.Container
import io.fabric8.webui.agents._
import scala.Some
import io.fabric8.webui.agents.{ManagementExtension, ManagementExtensionFactory}
import io.fabric8.service.{ContainerTemplate, ContainerCachingJmxTemplate}
import javax.ws.rs.{POST, Path}
import io.fabric8.monitor.api.{MonitorFacade, FetchMonitoredViewDTO}
import javax.ws.rs.core.Response
import io.fabric8.webui.BaseResource

/**
 *

 *

 *
 * @author Hiram Chirino
 */
object MonitorAgentResource extends ManagementExtensionFactory {
  def create(a: Container, jmx_username: String, jmx_password: String) = {
    if (a.isAlive && a.getJmxDomains.contains("io.fabric8")) {
      Some(new MonitorAgentResource(a, jmx_username, jmx_password))
    } else {
      None
    }
  }
}

/**
 *

 *

 *
 * @author Hiram Chirino
 */
class MonitorAgentResource(val agent: Container, jmx_username: String, jmx_password: String) extends BaseResource with ManagementExtension {

  def id: String = "monitor"

  @POST
  @Path("fetch")
  def fetch(fetch: FetchMonitoredViewDTO) = {

    val template = agent_template(agent, jmx_username, jmx_password)
    val response = MonitorFacade.fetch(template.getJmxTemplate(), fetch)
    if (response == null) {
      respond(Response.Status.NOT_FOUND)
    }
    response
  }

}


text:
package org.moffi.gui.events.mode;

import org.moffi.gui.events.AbstractGuiEvent;

import java.awt.*;

/**
 * Event indicating the shadow mode has been enabled.
 */
public class ShadowModeEnabledEvent extends AbstractGuiEvent {

    public ShadowModeEnabledEvent(Object sender) {
        super(sender);
    }
}


text:
/// <reference lib="es2015" />

import { RawSourceMap } from 'source-map';

export type ECMA = 5 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020;

export interface ParseOptions {
    bare_returns?: boolean;
    ecma?: ECMA;
    html5_comments?: boolean;
    shebang?: boolean;
}

export interface CompressOptions {
    arguments?: boolean;
    arrows?: boolean;
    booleans_as_integers?: boolean;
    booleans?: boolean;
    collapse_vars?: boolean;
    comparisons?: boolean;
    computed_props?: boolean;
    conditionals?: boolean;
    dead_code?: boolean;
    defaults?: boolean;
    directives?: boolean;
    drop_console?: boolean;
    drop_debugger?: boolean;
    ecma?: ECMA;
    evaluate?: boolean;
    expression?: boolean;
    global_defs?: object;
    hoist_funs?: boolean;
    hoist_props?: boolean;
    hoist_vars?: boolean;
    ie8?: boolean;
    if_return?: boolean;
    inline?: boolean | InlineFunctions;
    join_vars?: boolean;
    keep_classnames?: boolean | RegExp;
    keep_fargs?: boolean;
    keep_fnames?: boolean | RegExp;
    keep_infinity?: boolean;
    loops?: boolean;
    module?: boolean;
    negate_iife?: boolean;
    passes?: number;
    properties?: boolean;
    pure_funcs?: string[];
    pure_getters?: boolean | 'strict';
    reduce_funcs?: boolean;
    reduce_vars?: boolean;
    sequences?: boolean | number;
    side_effects?: boolean;
    switches?: boolean;
    toplevel?: boolean;
    top_retain?: null | string | string[] | RegExp;
    typeofs?: boolean;
    unsafe_arrows?: boolean;
    unsafe?: boolean;
    unsafe_comps?: boolean;
    unsafe_Function?: boolean;
    unsafe_math?: boolean;
    unsafe_symbols?: boolean;
    unsafe_methods?: boolean;
    unsafe_proto?: boolean;
    unsafe_regexp?: boolean;
    unsafe_undefined?: boolean;
    unused?: boolean;
}

export enum InlineFunctions {
    Disabled = 0,
    SimpleFunctions = 1,
    WithArguments = 2,
    WithArgumentsAndVariables = 3
}

export interface MangleOptions {
    eval?: boolean;
    keep_classnames?: boolean | RegExp;
    keep_fnames?: boolean | RegExp;
    module?: boolean;
    nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler;
    properties?: boolean | ManglePropertiesOptions;
    reserved?: string[];
    safari10?: boolean;
    toplevel?: boolean;
}

/**
 * An identifier mangler for which the output is invariant with respect to the source code.
 */
export interface SimpleIdentifierMangler {
    /**
     * Obtains the nth most favored (usually shortest) identifier to rename a variable to.
     * The mangler will increment n and retry until the return value is not in use in scope, and is not a reserved word.
     * This function is expected to be stable; Evaluating get(n) === get(n) should always return true.
     * @param n The ordinal of the identifier.
     */
    get(n: number): string;
}

/**
 * An identifier mangler that leverages character frequency analysis to determine identifier precedence.
 */
export interface WeightedIdentifierMangler extends SimpleIdentifierMangler {
    /**
     * Modifies the internal weighting of the input characters by the specified delta.
     * Will be invoked on the entire printed AST, and then deduct mangleable identifiers.
     * @param chars The characters to modify the weighting of.
     * @param delta The numeric weight to add to the characters.
     */
    consider(chars: string, delta: number): number;
    /**
     * Resets character weights.
     */
    reset(): void;
    /**
     * Sorts identifiers by character frequency, in preparation for calls to get(n).
     */
    sort(): void;
}

export interface ManglePropertiesOptions {
    builtins?: boolean;
    debug?: boolean;
    keep_quoted?: boolean | 'strict';
    nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler;
    regex?: RegExp | string;
    reserved?: string[];
}

export interface FormatOptions {
    ascii_only?: boolean;
    /** @deprecated Not implemented anymore */
    beautify?: boolean;
    braces?: boolean;
    comments?: boolean | 'all' | 'some' | RegExp | ( (node: any, comment: {
        value: string,
        type: 'comment1' | 'comment2' | 'comment3' | 'comment4',
        pos: number,
        line: number,
        col: number,
    }) => boolean );
    ecma?: ECMA;
    ie8?: boolean;
    indent_level?: number;
    indent_start?: number;
    inline_script?: boolean;
    keep_quoted_props?: boolean;
    max_line_len?: number | false;
    preamble?: string;
    preserve_annotations?: boolean;
    quote_keys?: boolean;
    quote_style?: OutputQuoteStyle;
    safari10?: boolean;
    semicolons?: boolean;
    shebang?: boolean;
    shorthand?: boolean;
    source_map?: SourceMapOptions;
    webkit?: boolean;
    width?: number;
    wrap_iife?: boolean;
    wrap_func_args?: boolean;
}

export enum OutputQuoteStyle {
    PreferDouble = 0,
    AlwaysSingle = 1,
    AlwaysDouble = 2,
    AlwaysOriginal = 3
}

export interface MinifyOptions {
    compress?: boolean | CompressOptions;
    ecma?: ECMA;
    enclose?: boolean | string;
    ie8?: boolean;
    keep_classnames?: boolean | RegExp;
    keep_fnames?: boolean | RegExp;
    mangle?: boolean | MangleOptions;
    module?: boolean;
    nameCache?: object;
    format?: FormatOptions;
    /** @deprecated */
    output?: FormatOptions;
    parse?: ParseOptions;
    safari10?: boolean;
    sourceMap?: boolean | SourceMapOptions;
    toplevel?: boolean;
}

export interface MinifyOutput {
    code?: string;
    map?: RawSourceMap | string;
}

export interface SourceMapOptions {
    /** Source map object, 'inline' or source map file content */
    content?: RawSourceMap | string;
    includeSources?: boolean;
    filename?: string;
    root?: string;
    url?: string | 'inline';
}

export function minify(files: string | string[] | { [file: string]: string }, options?: MinifyOptions): Promise<MinifyOutput>;


text:
<!DOCTYPE HTML>

		<meta charset="utf-8">
        <title>eHarbinger</title>
        <link rel="stylesheet" type="text/css" href="meg.css">

 Wall of Fame

				<button style = "margin-left:92%;"> Log Out </button>

 Check out the following achievements made by players!

Benson:	Has the most positive feedback!

Priyam:	Matched with the most players!

				 Suggested Games |   Popular Games in Community |   General Forum |   My Profile


text:
<!DOCTYPE html>

<title>form Single form-associated element in unclosed form with POST</title>

You should see text input below. Type "foobar" in it. Press "enter". You should see page saying "You typed: [foobar]".

<form method="post" action="../res/return_single_post.php">
  <input id="i1" name="test" type="text"/>


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

package dfp.axis.v201403.contactservice;

import com.google.api.ads.common.lib.auth.OfflineCredentials;
import com.google.api.ads.common.lib.auth.OfflineCredentials.Api;
import com.google.api.ads.dfp.axis.factory.DfpServices;
import com.google.api.ads.dfp.axis.v201403.Contact;
import com.google.api.ads.dfp.axis.v201403.ContactServiceInterface;
import com.google.api.ads.dfp.lib.client.DfpSession;
import com.google.api.client.auth.oauth2.Credential;

import java.util.Random;

/**
 * This example creates new contacts. To determine which contacts exist, run
 * GetAllContacts.java.
 *
 * Credentials and properties in {@code fromFile()} are pulled from the
 * "ads.properties" file. See README for more info.
 *
 * Tags: ContactService.createContacts
 *
 * @author Adam Rogal
 */
public class CreateContacts {

  // Set the ID of the advertiser to create a contact for.
  private static final String ADVERTISER_ID = "INSERT_ADVERTISER_COMPANY_ID_HERE";

  // Set the ID of the agency to create a contact for.
  private static final String AGENCY_ID = "INSERT_AGENCY_COMPANY_ID_HERE";

  public static void runExample(DfpServices dfpServices, DfpSession session,
      long advertiserCompanyId, long agencyCompanyId) throws Exception {
    // Get the ContactService.
    ContactServiceInterface contactService =
        dfpServices.get(session, ContactServiceInterface.class);

    // Create an advertiser contact.
    Contact advertiserContact = new Contact();
    advertiserContact.setName("Mr. Advertiser #" + new Random().nextInt(Integer.MAX_VALUE));
    advertiserContact.setEmail("advertiser@advertising.com");
    advertiserContact.setCompanyId(advertiserCompanyId);

    // Create an agency contact.
    Contact agencyContact = new Contact();
    agencyContact.setName("Ms. Agency #" + new Random().nextInt(Integer.MAX_VALUE));
    agencyContact.setEmail("agency@agencies.com");
    agencyContact.setCompanyId(agencyCompanyId);

    // Create the contacts on the server.
    Contact[] contacts =
        contactService.createContacts(new Contact[] {advertiserContact, agencyContact});

    for (Contact createdContact : contacts) {
      System.out.printf("A contact with ID \"%d\" and name \"%s\" was created.\n",
          createdContact.getId(), createdContact.getName());
    }
  }

  public static void main(String[] args) throws Exception {
    // Generate a refreshable OAuth2 credential similar to a ClientLogin token
    // and can be used in place of a service account.
    Credential oAuth2Credential = new OfflineCredentials.Builder()
        .forApi(Api.DFP)
        .fromFile()
        .build()
        .generateCredential();

    // Construct a DfpSession.
    DfpSession session = new DfpSession.Builder()
        .fromFile()
        .withOAuth2Credential(oAuth2Credential)
        .build();

    DfpServices dfpServices = new DfpServices();

    runExample(dfpServices, session, Long.parseLong(ADVERTISER_ID),
        Long.parseLong(AGENCY_ID));
  }
}


text:
package org.regenstrief.ucum.functions;

import org.hl7.types.REAL;
import org.hl7.types.ValueFactory;
import org.regenstrief.ucum.FunctionPair;

public final class hpX implements FunctionPair {

  static final REAL TEN  = ValueFactory.getInstance()
    .REALvalueOfLiteral("10");

  static final REAL LN_TEN  = TEN.log();

  public REAL f_to  (REAL x) {
    return x.log().dividedBy(LN_TEN).negated();
  }

  public REAL f_from(REAL x) {
    return TEN.power(x.negated());
  }
}


text:
package com.mailrest.maildal.model;

import com.noorq.casser.mapping.annotation.UDT;

/**
 *   Domain settings are using to store information about enabled features per domain
 *
 *   It is useful for the client in case of having different web-sites for different purposes
 *
 */

@UDT
public interface DomainSettings {

	/**
	 *   In case of 'test' environment it will override 'to' field in the message
	 *
	 *   @return optional override for 'to' field in test environment
	 */

	String testToRecipients();

	/**
	 *   In case of 'test' environment it will override 'bcc' field in the message
	 *
	 *   @return optional override for 'bcc' field in test environment
	 */

	String testBccRecipients();

	/**
	 *   In case of 'prod' environment it will override 'bcc' field in the message
	 *
	 *   @return optional override for 'bcc' field in prod environment
	 */

	String prodBccRecipients();

	/**
	 *   If it is YES, then to all messages in the domain will be added unsubscribe link
	 *
	 *   @return unsubscribe options
	 */

	UnsubscribeOptions unsubscribeLink();

	/**
	 *   Optional field that defines template of the text that will be added in case of UnsubscribeOptions.YES
	 *
	 *   @return unsubscribe template for plain text
	 */

	String unsubscribeText();

	/**
	 *   Optional field that defines template of the html that will be added in case of UnsubscribeOptions.YES
	 *
	 *   @return unsubscribe template for html text
	 */

	String unsubscribeHtml();

	/**
	 *  In case of YES all links in the message will be overridden by redirect action
	 *  In case of HTML_ONLY links will be overridden only for HTML mails
	 *
	 *  @return options for tracking clicks
	 */

	TrackingOptions trackClicks();

	/**
	 *  In case of YES email will be tracked by special algorithm for opening
	 *
	 *  @return options for tracking opens
	 */

	TrackingOptions trackOpens();

}


text:
'''
Created by auto_sdk on 2014-12-17 17:22:51
'''
from top.api.base import RestApi
class WlbOrderdetailDateGetRequest(RestApi):
	def __init__(self,domain='gw.api.taobao.com',port=80):
		RestApi.__init__(self,domain, port)
		self.end_time = None
		self.page_no = None
		self.page_size = None
		self.start_time = None

	def getapiname(self):
		return 'taobao.wlb.orderdetail.date.get'


text:
var config = require('config.json');
var express = require('express');
var router = express.Router();
var userService = require('services/user.service');
var log = require('../logs/accessLog.controller.js');

// routes
router.post('/authenticate', authenticateUser);
router.post('/register', registerUser);
router.get('/current', getCurrentUser);
router.get('/userlist', getUserList);
router.put('/:_id', updateUser);
router.delete('/:_id', deleteUser);

module.exports = router;

function getUserList(req, res) {
    userService.getUserList()
        .then(function (userList) {
            res.send(userList);
        })
        .catch(function (err) {
            res.status(400).send(err);
        });
}

function authenticateUser(req, res) {
    userService.authenticate(req.body.username, req.body.password)
        .then(function (token) {
            if (token) {
                // authentication successful
                log.info(req.body.username + ' connected');
                res.send({token: token});
            } else {
                // authentication failed
                res.sendStatus(401);
            }
        })
        .catch(function (err) {
            res.status(400).send(err);
        });
}

function registerUser(req, res) {
    userService.create(req.body)
        .then(function () {
            log.info(req.body.username + ' has created account ' + req.body.avatar);
            res.sendStatus(200);
        })
        .catch(function (err) {
            res.status(400).send(err);
        });
}

function getCurrentUser(req, res) {
    userService.getById(req.user.sub)
        .then(function (user) {
            if (user) {
                res.send(user);
            } else {
                res.sendStatus(404);
            }
        })
        .catch(function (err) {
            res.status(400).send(err);
        });
}

function updateUser(req, res) {
    var userId = req.user.sub;
    if (req.params._id !== userId) {
        // can only update own account
        return res.status(401).send('You can only update your own account');
    }

    userService.update(userId, req.body)
        .then(function () {
            log.info(req.user.username + '\'s account has been updated');
            res.sendStatus(200);
        })
        .catch(function (err) {
            res.status(400).send(err);
        });
}

function deleteUser(req, res) {
    var userId = req.user.sub;

    userService.getById(req.user.sub)
        .then(function (user) {
            if (user) {

                console.log('role : '+user.role);
                console.log('userid : '+userId);
                console.log('req.params : '+req.params._id);

                if ((user.role.localeCompare('admin'))) {
                    // can only delete own account
                    console.log(user.role.localeCompare('admin'));
                    return res.status(401).send('You can only delete your own account');
                }
                log.info(req.params.username + '\'s account has been deleted');
                console.log(req.params._id);
                userService.delete(req.params._id)
                    .then(function () {
                        res.sendStatus(200);
                    })
                    .catch(function (err) {
                        res.status(400).send(err);
                    });
            }

        })
        .catch(function (err) {
            res.status(400).send(err);
        });

}


text:
require 'test_helper'

class SurveySchemasControllerTest < ActionDispatch::IntegrationTest
  setup do
    @survey_schema = survey_schemas(:one)
  end

  test "should get index" do
    get survey_schemas_url
    assert_response :success
  end

  test "should get new" do
    get new_survey_schema_url
    assert_response :success
  end

  test "should create survey_schema" do
    assert_difference('SurveySchema.count') do
      post survey_schemas_url, params: { survey_schema: { title: @survey_schema.title } }
    end

    assert_redirected_to survey_schema_url(SurveySchema.last)
  end

  test "should show survey_schema" do
    get survey_schema_url(@survey_schema)
    assert_response :success
  end

  test "should get edit" do
    get edit_survey_schema_url(@survey_schema)
    assert_response :success
  end

  test "should update survey_schema" do
    patch survey_schema_url(@survey_schema), params: { survey_schema: { title: @survey_schema.title } }
    assert_redirected_to survey_schema_url(@survey_schema)
  end

  test "should destroy survey_schema" do
    assert_difference('SurveySchema.count', -1) do
      delete survey_schema_url(@survey_schema)
    end

    assert_redirected_to survey_schemas_url
  end
end


text:
:- module(swish_render_tiles,
	  [ term_rendering//3			% +Term, +Vars, +Options
	  ]).
:- use_module(library(http/html_write)).
:- use_module('../render').

:- register_renderer(tiles, "Render chess board representations").

/** <module> SWISH chessboard renderer

Render chessboards. Currently only deals with the N-queens problem. This
file is nevertheless called =chess.pl= because   it should be trivial to
extend this to more general chess positions.

The   styling   is    a    small     modification    of    [CSS3   Chess
Board](http://designindevelopment.com/css/css3-chess-board/)
*/

%%	term_rendering(+Term, +Vars, +Options)//
%
%	Render an N-queens  problem.  This   renderer  assumes  that the
%	solution is represented by a permutation   of a list of integers
%	1..N, where the I-th integer describes   the column of the queen
%	at row I.

term_rendering(Term, _Vars, _Options) -->
	{ is_map(Term,Tiles),
    Term=..[_,_|Rows],
	  length(Rows, N),
	  LineHeight0 is ceiling(500/N),
    (LineHeight0>32->
      LineHeight=LineHeight0
    ;
      LineHeight=32
    )
	},
	html(div([ style('display:inline-block;'
			),
		   'data-render'('Tile map')
		 ],
		 [table(\tiles(Rows,Tiles,LineHeight)),
		   \tile_map_style
		 ])).

is_map(Term,Tiles) :-
  Term=..[map,Tiles,R1|Rows],
  is_list(Tiles),
  R1=..[_|Row1],
  length(Row1,W),
  maplist(row_length(W),Rows).

row_length(W,Row):-
  Row=..[row|R],
  length(R,W).

tiles([],_Tiles,_Width) --> [].
tiles([H|T],Tiles,Width) -->
  {H=..[_|Row]},
	html(tr(\nrow(Row,Tiles,Width))),
	tiles(T,Tiles,Width).

nrow([],_Tiles,_Width) --> !.
nrow([Tile|TTiles],Tiles,Width) -->
	{ member(tile(Tile,URL),Tiles) },
	  html(td(img([src(URL),alt(Tile),width(Width)],[]))),
	nrow(TTiles,Tiles,Width).

tile_map_style -->
	html({|html||
<style>
table { border-collapse: collapse; padding: 0px; }
table tr td { padding: 0px; border-collapse: collapse;}
</style>
	     |}).


text:
package org.apache.cloudstack.api.command.admin.router;

import org.apache.log4j.Logger;

import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiCommandJobType;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.BaseAsyncCmd;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.DomainRouterResponse;
import org.apache.cloudstack.context.CallContext;

import com.cloud.event.EventTypes;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.router.VirtualRouter;
import com.cloud.network.router.VirtualRouter.Role;
import com.cloud.user.Account;
import com.cloud.vm.VirtualMachine;

@APICommand(name = "startRouter", responseObject = DomainRouterResponse.class, description = "Starts a router.", entityType = {VirtualMachine.class},
        requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
public class StartRouterCmd extends BaseAsyncCmd {
    public static final Logger s_logger = Logger.getLogger(StartRouterCmd.class.getName());
    private static final String s_name = "startrouterresponse";

    /////////////////////////////////////////////////////
    //////////////// API parameters /////////////////////
    /////////////////////////////////////////////////////

    @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = DomainRouterResponse.class, required = true, description = "the ID of the router")
    private Long id;

    /////////////////////////////////////////////////////
    /////////////////// Accessors ///////////////////////
    /////////////////////////////////////////////////////

    public Long getId() {
        return id;
    }

    /////////////////////////////////////////////////////
    /////////////// API Implementation///////////////////
    /////////////////////////////////////////////////////

    @Override
    public String getCommandName() {
        return s_name;
    }

    public static String getResultObjectName() {
        return "router";
    }

    @Override
    public long getEntityOwnerId() {
        VirtualRouter router = _entityMgr.findById(VirtualRouter.class, getId());
        if (router != null) {
            return router.getAccountId();
        }

        return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked
    }

    @Override
    public String getEventType() {
        return EventTypes.EVENT_ROUTER_START;
    }

    @Override
    public String getEventDescription() {
        return "starting router: " + this._uuidMgr.getUuid(VirtualMachine.class, getId());
    }

    @Override
    public ApiCommandJobType getInstanceType() {
        return ApiCommandJobType.DomainRouter;
    }

    @Override
    public Long getInstanceId() {
        return getId();
    }

    @Override
    public void execute() throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
        CallContext.current().setEventDetails("Router Id: " + this._uuidMgr.getUuid(VirtualMachine.class, getId()));
        VirtualRouter result = null;
        VirtualRouter router = _routerService.findRouter(getId());
        if (router == null || router.getRole() != Role.VIRTUAL_ROUTER) {
            throw new InvalidParameterValueException("Can't find router by id");
        } else {
            result = _routerService.startRouter(getId());
        }
        if (result != null) {
            DomainRouterResponse routerResponse = _responseGenerator.createDomainRouterResponse(result);
            routerResponse.setResponseName(getCommandName());
            setResponseObject(routerResponse);
        } else {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to start router");
        }
    }
}


text:
/* © 2010 David Given.
 * LBW is licensed under the MIT open source license. See the COPYING
 * file in this distribution for the full text.
 */

#include "globals.h"
#include "syscalls.h"
#include <unistd.h>

#define LINUX_CSIGNAL                 0x000000ff      /* signal mask to be sent at exit */
#define LINUX_CLONE_VM                0x00000100      /* set if VM shared between processes */
#define LINUX_CLONE_FS                0x00000200      /* set if fs info shared between processes */
#define LINUX_CLONE_FILES             0x00000400      /* set if open files shared between processes */
#define LINUX_CLONE_SIGHAND           0x00000800      /* set if signal handlers and blocked signals shared */
#define LINUX_CLONE_PTRACE            0x00002000      /* set if we want to let tracing continue on the child too */
#define LINUX_CLONE_VFORK             0x00004000      /* set if the parent wants the child towake it up on mm_release */
#define LINUX_CLONE_PARENT            0x00008000      /* set if we want to have the same parent as the cloner */
#define LINUX_CLONE_THREAD            0x00010000      /* Same thread group? */
#define LINUX_CLONE_NEWNS             0x00020000      /* New namespace group? */
#define LINUX_CLONE_SYSVSEM           0x00040000      /* share system V SEM_UNDO semantics */
#define LINUX_CLONE_SETTLS            0x00080000      /* create a new TLS for the child */
#define LINUX_CLONE_PARENT_SETTID     0x00100000      /* set the TID in the parent */
#define LINUX_CLONE_CHILD_CLEARTID    0x00200000      /* clear the TID in the child */
#define LINUX_CLONE_DETACHED          0x00400000      /* Unused, ignored */
#define LINUX_CLONE_UNTRACED          0x00800000      /* set if the tracing process can't force CLONE_PTRACE on this clone */
#define LINUX_CLONE_CHILD_SETTID      0x01000000      /* set the TID in the child */
#define LINUX_CLONE_STOPPED           0x02000000      /* Start in stopped state */
#define LINUX_CLONE_NEWUTS            0x04000000      /* New utsname group? */
#define LINUX_CLONE_NEWIPC            0x08000000      /* New ipcs */
#define LINUX_CLONE_NEWUSER           0x10000000      /* New user namespace */
#define LINUX_CLONE_NEWPID            0x20000000      /* New pid namespace */
#define LINUX_CLONE_NEWNET            0x40000000      /* New network namespace */
#define LINUX_CLONE_IO                0x80000000      /* Clone io context */

/* We can't implement clone() on Interix --- it's just not possible.
 * However, Linux uses clone() to do a whole bunch of stuff, and we can
 * implement some of the common use cases.
 */

SYSCALL(stub32_fork)
{
	int result = fork();

	switch (result)
	{
		case 0: /* child */
			InitProcess();
			InstallExceptionHandler();
			//error("fork() needs work");
			//StartMonitor();
			break;

		case -1: /* error */
			throw errno;
	}

	return result;
}

SYSCALL(stub32_vfork)
{
	int result = fork(); /* vfork doesn't work */

	switch (result)
	{
		case 0: /* child */
			InitProcess();
			InstallExceptionHandler();
			//error("fork() needs work");
			//StartMonitor();
			break;

		case -1: /* error */
			throw errno;
	}

	return result;
}

SYSCALL(sys32_clone)
{
	u32 clone_flags = arg.a0.u;
	u32 newsp = arg.a1.u;
	void* parent_tid = arg.a2.p;
	void* child_tid = arg.a4.p;

	switch (clone_flags)
	{
		case 0x01200011: /* fork, I think */
		case 0x00100011:
		{
			pid_t newpid = stub32_fork(arg);
			switch (newpid)
			{
				case 0: /* child */
					if (clone_flags & LINUX_CLONE_CHILD_SETTID)
					{
						if (child_tid)
							*(pid_t*)child_tid = getpid();
					}
					if (clone_flags & LINUX_CLONE_PARENT_SETTID)
					{
						if (parent_tid)
							*(pid_t*)parent_tid = getpid();
					}
					break;

				default: /* parent */
					if (clone_flags & LINUX_CLONE_PARENT_SETTID)
					{
						if (parent_tid)
							*(pid_t*)parent_tid = newpid;
					}
					break;
			}
			return newpid;
		}

		default:
			log("clone flags=%08x newsp=%08x ptid=%p ctid=%p", clone_flags, newsp,
					parent_tid, child_tid);
			error("unimplemented clone scenario");
	}
}


text:
package com.lfk.justweengine.Engine;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.IOException;
import java.io.InputStream;

/**
 * 封装图片的获取
 * Created by liufengkai on 15/11/27.
 */
public class GameTexture {
    private Context e_context;
    private Bitmap e_bitmap;

    public GameTexture(Context e_context) {
        this.e_context = e_context;
        e_bitmap = null;
    }

    public Bitmap getBitmap() {
        return e_bitmap;
    }

    /**
     * get bitmap form assets
     *
     * @param filename
     * @return
     */
    public boolean loadFromAsset(String filename) {
        InputStream inputStream;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        try {
            inputStream = e_context.getAssets().open(filename);
            e_bitmap = BitmapFactory.decodeStream(inputStream, null, options);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * get bitmap from a big bitmap
     *
     * @param filename
     * @param x
     * @param y
     * @param width
     * @param height
     * @return
     */
    public boolean loadFromAssetStripFrame(String filename,
                                           int x, int y,
                                           int width, int height) {
        InputStream inputStream;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        try {
            inputStream = e_context.getAssets().open(filename);
            Bitmap temp = BitmapFactory.decodeStream(inputStream, null, options).copy(Bitmap.Config.ARGB_8888, true);
            inputStream.close();
            e_bitmap = Bitmap.createBitmap(temp, x, y, width, height);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static Bitmap loadFromBigBitmap(GameTexture texture, int x, int y
            , int w, int h) {
        return Bitmap.createBitmap(texture.getBitmap(), x, y, w, h);
    }

    public void setBitmap(Bitmap e_bitmap) {
        this.e_bitmap = e_bitmap;
    }
}


text:
Public Class TipoDocumento
    Public Property Codigo As String
    Public Property Estado As String
    Public Property IdTipoDocumento As Int32
    Public Property Nombre As String
    Public Property SujetoRetencion As String
    Public ReadOnly Property Documento As String
        Get
            Return Codigo + " " + Nombre
        End Get
    End Property
End Class


text:
package org.xeneo.db.security;

import org.xeneo.core.security.UserService;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 *
 * @author Stefan Huber
 */
public class JdbcUserService implements UserService {

    protected JdbcUser getCurrentJdbcUser() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        JdbcUser user = null;
        if (principal instanceof JdbcUser) {
            user = (JdbcUser) principal;
        }
        return user;
    }

    public JdbcUser getCurrentUser() {
        return getCurrentJdbcUser();
    }

    public String getCurrentUserURI() {
        return getCurrentJdbcUser().getUserURI();
    }

}


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

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

001package pkg_Command;
002
003/**
004 *
005 *
006 * @author  Valentin Messias
007 * @version 2016.01.15
008 */
009import pkg_Engine.Player;
010import pkg_Item.Beamer;
011
012public class ChargeCommand extends Command
013{
014
015
016
017
018    public ChargeCommand()
019    {
020    } // ChargeCommand()
021
022    @Override
023    public boolean execute( final Player pPlayer )
024    {
025        if ( pPlayer.hasItem( "Beamer" ) ) {
026            Beamer vBeamer = (Beamer) pPlayer.getItemList().getItemList().get( "Beamer" );
027            vBeamer.setRoom( pPlayer.getCurrentRoom() );
028            pPlayer.getGE().getGUI().println( "You charged the current room into the beamer !" );
029            return false;
030        }
031        else {
032            pPlayer.getGE().getGUI().println( "You don't have the beamer." );
033            return false;
034        }
035    } // execute(.)
036} // ChargeCommand


text:
using System;

namespace org.apache.lucene.analysis.snowball
{

	using LowerCaseFilter = org.apache.lucene.analysis.core.LowerCaseFilter;
	using KeywordAttribute = org.apache.lucene.analysis.tokenattributes.KeywordAttribute;
	using CharTermAttribute = org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
	using TurkishLowerCaseFilter = org.apache.lucene.analysis.tr.TurkishLowerCaseFilter; // javadoc @link
	using SnowballProgram = org.tartarus.snowball.SnowballProgram;

	///
	/// A filter that stems words using a Snowball-generated stemmer.
	///
	/// Available stemmers are listed in <seealso cref="org.tartarus.snowball.ext"/>.
	/// <para>NOTE: SnowballFilter expects lowercased text.
	///

	///
For the Turkish language, see <seealso cref="TurkishLowerCaseFilter"/>.
	///
For other languages, see <seealso cref="LowerCaseFilter"/>.
	///

	/// </para>
	///
	/// <para>
	/// Note: This filter is aware of the <seealso cref="KeywordAttribute"/>. To prevent
	/// certain terms from being passed to the stemmer
	/// <seealso cref="KeywordAttribute#isKeyword()"/> should be set to true
	/// in a previous <seealso cref="TokenStream"/>.
	///
	/// Note: For including the original term as well as the stemmed version, see
	/// <seealso cref="org.apache.lucene.analysis.miscellaneous.KeywordRepeatFilterFactory"/>
	/// </para>
	///
	///
	///
	public sealed class SnowballFilter : TokenFilter
	{

	  private readonly SnowballProgram stemmer;

	  private readonly CharTermAttribute termAtt = addAttribute(typeof(CharTermAttribute));
	  private readonly KeywordAttribute keywordAttr = addAttribute(typeof(KeywordAttribute));

	  public SnowballFilter(TokenStream input, SnowballProgram stemmer) : base(input)
	  {
		this.stemmer = stemmer;
	  }

	  ///
	  /// Construct the named stemming filter.
	  ///
	  /// Available stemmers are listed in <seealso cref="org.tartarus.snowball.ext"/>.
	  /// The name of a stemmer is the part of the class name before "Stemmer",
	  /// e.g., the stemmer in <seealso cref="org.tartarus.snowball.ext.EnglishStemmer"/> is named "English".
	  ///
	  /// <param name="in"> the input tokens to stem </param>
	  /// <param name="name"> the name of a stemmer </param>
	  public SnowballFilter(TokenStream @in, string name) : base(@in)
	  {
		//Class.forName is frowned upon in place of the ResourceLoader but in this case,
		// the factory will use the other constructor so that the program is already loaded.
		try
		{
		  Type stemClass = Type.GetType("org.tartarus.snowball.ext." + name + "Stemmer").asSubclass(typeof(SnowballProgram));
		  stemmer = stemClass.newInstance();
		}
		catch (Exception e)
		{
		  throw new System.ArgumentException("Invalid stemmer class specified: " + name, e);
		}
	  }

	  ///
	  /// Returns the next input Token, after being stemmed
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: @Override public final boolean incrementToken() throws java.io.IOException
	  public override bool incrementToken()
	  {
		if (input.incrementToken())
		{
		  if (!keywordAttr.Keyword)
		  {
			char[] termBuffer = termAtt.buffer();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int length = termAtt.length();
			int length = termAtt.length();
			stemmer.setCurrent(termBuffer, length);
			stemmer.stem();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final char finalTerm[] = stemmer.getCurrentBuffer();
			char[] finalTerm = stemmer.CurrentBuffer;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int newLength = stemmer.getCurrentBufferLength();
			int newLength = stemmer.CurrentBufferLength;
			if (finalTerm != termBuffer)
			{
			  termAtt.copyBuffer(finalTerm, 0, newLength);
			}
			else
			{
			  termAtt.Length = newLength;
			}
		  }
		  return true;
		}
		else
		{
		  return false;
		}
	  }
	}

}


text:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:bind="http://schemas.android.com/apk/res-auto">

    <data>

        <import type="com.liangfeizc.databindingsamples.basic.User" />
        <variable
            name="user"
            type="User" />

        <variable
            name="contact"
            type="com.liangfeizc.databindingsamples.custombindings.Contact" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <include
            layout="@layout/user"
            bind:user="@{user}" />

        <include
            layout="@layout/contact"
            bind:contact="@{contact}" />
    </LinearLayout>
</layout>


text:
package org.softlang.tests;

import org.junit.Test;
import org.softlang.features.Persistence;

// See README for detailed usage instructions

public class Load {

	@Test
	public void test() {
		new Persistence().loadCompany("meganalysis");
	}
}


text:
<?php

declare(strict_types=1);

namespace DisqusHelper\Widget;

use DisqusHelper\Code;

/**
 * Comments thread widget.
 *
 * @author Nikola Posa <posa.nikola@gmail.com>
 */
final class ThreadWidget implements WidgetInterface
{
    const SCRIPT_NAME = 'embed.js';

    public function render(array $options = []) : string
    {
        return '

';
    }

    public function visit(Code $code) : Code
    {
        $code->addScriptFile(self::SCRIPT_NAME, [
            'lazy_load' => true,
        ]);

        return $code;
    }
}


text:
package pages.vrm_retention

import uk.gov.dvla.vehicles.presentation.common.helpers.webbrowser.{Page, WebDriverFactory}

object HealthCheckPage extends Page {
  final val address = buildAppUrl("healthcheck")
  override lazy val url: String = WebDriverFactory.testUrl + address.substring(1)

  val title = "Health Check"
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const type_overrides_1 = require("./type-overrides");
const pluralize = require('pluralize'); // No typings associated
function getTypeName(namespace, type) {
    let namespaceName = namespace.fullName;
    let finalName;
    for (let title of type.titles) {
        let name = titleToTypeName(namespaceName, title);
        if (finalName) {
            if (name[1]) {
                // An explicit type name, so make sure it isn't masking anything
                if (finalName[1] && name[0] !== finalName[0]) {
                    // Previous explicit name from another title is different
                    throw new Error(title + '\'s override to ' + name[0]
                        + ' would shadow explicit name of ' + finalName[0]);
                }
                // Otherwise take this name since it either is the same, or overrides
                // a non-explicit name
                finalName = name;
            }
            else if (!finalName[1] && name[0].length < finalName[0].length) {
                // Take the shorter of the generated names
                finalName = name;
            }
        }
        else {
            // First valid name
            finalName = name;
        }
    }
    if (finalName) {
        return finalName;
    }
    else {
        throw new Error('Unable to generate typename for ' + type.titles[0]);
    }
}
exports.getTypeName = getTypeName;
function makeStem(text) {
    return pluralize.singular(text).toLowerCase();
}
function capitalize(text) {
    if (text !== '') {
        return text[0].toUpperCase() + text.substring(1);
    }
    else {
        return '';
    }
}
function titleToTypeName(namespace, title) {
    // First check explicit mapping for title
    if (type_overrides_1.TYPENAME_OVERRIDES[title]) {
        return [type_overrides_1.TYPENAME_OVERRIDES[title], true];
    }
    if (title[0].toUpperCase() === title[0]) {
        // Assume this is actually an explicit type name already
        return [title, true];
    }
    let namespaceStems = [];
    for (let n of namespace.split('.')) {
        namespaceStems.push(makeStem(n));
    }
    let tokens = title.split('_');
    let lastIDToken = tokens.length - 1;
    while (lastIDToken >= 0) {
        if (tokens[lastIDToken] === 'id' || tokens[lastIDToken] === 'element') {
            break;
        }
        lastIDToken--;
    }
    let startToken, endToken;
    if (lastIDToken > 0) {
        // Found an ID; if the id was at the end of the token list, then include
        // only the tokens from it to the second ID (or 1st token). Otherwise
        // include tokens from the right of the id to the end.
        if (lastIDToken < tokens.length - 1) {
            startToken = lastIDToken + 1;
            endToken = tokens.length - 1;
        }
        else {
            lastIDToken--;
            endToken = lastIDToken;
            // Search for second _id
            while (lastIDToken >= 0) {
                if (tokens[lastIDToken] === 'id' || tokens[lastIDToken] === 'element') {
                    break;
                }
                lastIDToken--;
            }
            startToken = Math.max(1, lastIDToken + 1);
        }
    }
    else {
        // Take everything except the first token, which is the HTTP method
        startToken = 1;
        endToken = tokens.length - 1;
    }
    // Now filter the tokens to remove redundancy, and fix pluralization
    // based on the presence of element tags.
    let goodTokens = [];
    let backupToken = startToken > 2 ? capitalize(tokens[startToken - 2])
        : 'Info';
    for (let i = startToken; i <= endToken; i++) {
        if (tokens[i] === 'element' || tokens[i] === '200' || tokens[i] === '201'
            || tokens[i] === 'ok') {
            continue;
        }
        let token;
        if (i < tokens.length - 1 && tokens[i + 1] === 'element') {
            // Make it singular
            token = pluralize.singular(tokens[i]);
        }
        else {
            token = tokens[i];
        }
        // Now make it capitalized
        token = capitalize(token);
        let newStem = makeStem(token);
        let oldStem;
        if (goodTokens.length > 0) {
            // Check previous token
            oldStem = [makeStem(goodTokens[goodTokens.length - 1])];
        }
        else {
            // First token of the type name, check against the namespace instead
            oldStem = namespaceStems;
        }
        if (oldStem.indexOf(newStem) >= 0) {
            if (goodTokens.length > 0) {
                // Replace prior token with this as it has higher precedence
                // (and while stems are the same, the actual tokens may differ)
                goodTokens[goodTokens.length - 1] = token;
            }
            else {
                // Don't include it in the main tokens, but remember in case no
                // good token ever shows up
                backupToken = token;
            }
        }
        else {
            // Append the new token since it is not redundant
            goodTokens.push(token);
        }
    }
    let generatedName = goodTokens.length > 0 ? goodTokens.join('') : backupToken;
    return [generatedName, false];
}
//# sourceMappingURL=get-type-name.js.map


text:
package valandur.webapi.serialize.view.data;

import com.fasterxml.jackson.annotation.JsonValue;
import org.spongepowered.api.data.manipulator.mutable.entity.BreedableData;
import valandur.webapi.serialize.BaseView;

public class BreedableDataView extends BaseView<BreedableData> {

    @JsonValue
    public boolean breedable;

    public BreedableDataView(BreedableData value) {
        super(value);

        this.breedable = value.breedable().get();
    }
}


text:
namespace page_load_metrics {

class PageLoadTracker;

// This class can be used to drive tests of PageLoadMetricsObservers in Chrome.
// To hook up an observer, override RegisterObservers and call
// tracker->AddObserver. This will attach the observer to all main frame
// navigations.
class PageLoadMetricsObserverTestHarness
    : public ChromeRenderViewHostTestHarness {
 public:
  // Sample URL for resource loads.
  static const char kResourceUrl[];

  PageLoadMetricsObserverTestHarness();
  ~PageLoadMetricsObserverTestHarness() override;

  void SetUp() override;

  virtual void RegisterObservers(PageLoadTracker* tracker) {}

  PageLoadMetricsObserverTester* tester() { return tester_.get(); }
  const PageLoadMetricsObserverTester* tester() const { return tester_.get(); }

 private:
  std::unique_ptr<PageLoadMetricsObserverTester> tester_;

  DISALLOW_COPY_AND_ASSIGN(PageLoadMetricsObserverTestHarness);
};

}  // namespace page_load_metrics

#endif  // CHROME_BROWSER_PAGE_LOAD_METRICS_OBSERVERS_PAGE_LOAD_METRICS_OBSERVER_TEST_HARNESS_H_


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using GalaSoft.MvvmLight.Messaging;

namespace GalaSoft.MvvmLight.Test.Messaging
{
    [TestClass]
    public class MessengerSendWithTokenTest
    {
        [TestMethod]
        public void TestSendWithToken()
        {
            string receivedContent1 = null;
            string receivedContent2 = null;
            string receivedContent3 = null;

            Messenger.Reset();

            var token1 = new object();
            var token2 = new object();

            Messenger.Default.Register<string>(this, m => receivedContent1 = m);
            Messenger.Default.Register<string>(this, token1, m => receivedContent2 = m);
            Messenger.Default.Register<string>(this, token2, m => receivedContent3 = m);

            var message1 = "Hello world";
            var message2 = "And again";
            var message3 = "Third one";

            Messenger.Default.Send(message1, token1);

            Assert.IsNull(receivedContent1);
            Assert.AreEqual(message1, receivedContent2);
            Assert.IsNull(receivedContent3);

            Messenger.Default.Send(message2, token2);

            Assert.IsNull(receivedContent1);
            Assert.AreEqual(message1, receivedContent2);
            Assert.AreEqual(message2, receivedContent3);

            Messenger.Default.Send(message3);

            Assert.AreEqual(message3, receivedContent1);
            Assert.AreEqual(message1, receivedContent2);
            Assert.AreEqual(message2, receivedContent3);
        }

        [TestMethod]
        public void TestSendMessageBaseWithToken()
        {
            Exception receivedContent1 = null;
            Exception receivedContent2 = null;
            Exception receivedContent3 = null;

            Messenger.Reset();

            var token1 = new object();
            var token2 = new object();

            Messenger.Default.Register<Exception>(this, true, m => receivedContent1 = m);
            Messenger.Default.Register<Exception>(this, token1, true, m => receivedContent2 = m);
            Messenger.Default.Register<Exception>(this, token2, true, m => receivedContent3 = m);

            var message = new InvalidOperationException();

            Messenger.Default.Send(message, token1);

            Assert.IsNull(receivedContent1);
            Assert.AreEqual(message, receivedContent2);
            Assert.IsNull(receivedContent3);
        }

        [TestMethod]
        public void TestSendWithIntToken()
        {
            InvalidOperationException receivedContent1 = null;
            InvalidOperationException receivedContent2 = null;
            InvalidOperationException receivedContent3 = null;

            Messenger.Reset();

            var token1 = 123;
            var token2 = 456;

            Messenger.Default.Register<InvalidOperationException>(this, m => receivedContent1 = m);
            Messenger.Default.Register<InvalidOperationException>(this, token1, m => receivedContent2 = m);
            Messenger.Default.Register<InvalidOperationException>(this, token2, m => receivedContent3 = m);

            var message = new InvalidOperationException();

            Messenger.Default.Send(message, token1);

            Assert.IsNull(receivedContent1);
            Assert.AreEqual(message, receivedContent2);
            Assert.IsNull(receivedContent3);
        }
    }
}


text:
/**
 * Created by Julian/Wolke on 13.11.2016.
 */
let mongoose = require('mongoose');
let permissionSchema = mongoose.Schema({
    id: String,
    permissions: []
});
let permModel = mongoose.model('Permissions', permissionSchema);
module.exports = permModel;


text:
package io.spine.server.projection.given;

import io.spine.core.Subscribe;
import io.spine.server.projection.Projection;
import io.spine.server.projection.ProjectionRepository;
import io.spine.server.route.StateUpdateRouting;
import io.spine.test.projection.Project;
import io.spine.test.projection.ProjectId;
import io.spine.test.projection.ProjectTaskNames;
import io.spine.test.projection.Task;

import static io.spine.server.route.EventRoute.withId;
import static java.util.stream.Collectors.toList;

public final class EntitySubscriberProjection
        extends Projection<ProjectId, ProjectTaskNames, ProjectTaskNames.Builder> {

    public EntitySubscriberProjection(ProjectId id) {
        super(id);
    }

    @Subscribe
    void onUpdate(Project aggregateState) {
        var taskNames = aggregateState.getTaskList().stream()
                .map(Task::getTitle)
                .collect(toList());
        builder().setProjectId(aggregateState.getId())
                 .setProjectName(aggregateState.getName())
                 .clearTaskName()
                 .addAllTaskName(taskNames);
    }

    public static final class Repository
            extends ProjectionRepository<ProjectId, EntitySubscriberProjection, ProjectTaskNames> {

        @Override
        protected void setupStateRouting(StateUpdateRouting<ProjectId> routing) {
            routing.route(Project.class, (state, context) -> withId(state.getId()));
        }
    }
}


text:
package com.intellij.openapi.actionSystem;

import com.intellij.openapi.keymap.KeymapUtil;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;

public class KeyboardModifierGestureShortcut extends Shortcut {

  private final KeyStroke myStroke;
  private final KeyboardGestureAction.ModifierType myType;

  @NotNull
  public static Shortcut newInstance(KeyboardGestureAction.ModifierType type, KeyStroke stroke) {
    return switch (type) {
      case dblClick -> new DblClick(stroke);
      case hold -> new Hold(stroke);
    };
  }

  protected KeyboardModifierGestureShortcut(final KeyStroke stroke, KeyboardGestureAction.ModifierType type) {
    myStroke = stroke;
    myType = type;
  }

  public KeyStroke getStroke() {
    return myStroke;
  }

  public KeyboardGestureAction.ModifierType getType() {
    return myType;
  }

  @Override
  public boolean isKeyboard() {
    return true;
  }

  @Override
  public boolean startsWith(@NotNull final Shortcut sc) {
    if (!(sc instanceof KeyboardModifierGestureShortcut)) return false;

    final KeyboardModifierGestureShortcut other = (KeyboardModifierGestureShortcut)sc;
    if (myType.equals(other.myType)) {
      if (myStroke.getModifiers() != other.myStroke.getModifiers()) return false;
      return other.myStroke.getKeyCode() != -1 || other.myStroke.getKeyCode() == myStroke.getKeyCode();
    }

    return false;
  }

  @Override
  public boolean equals(final Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    final KeyboardModifierGestureShortcut that = (KeyboardModifierGestureShortcut)o;

    if (myStroke != null ? !myStroke.equals(that.myStroke) : that.myStroke != null) return false;
    if (myType != that.myType) return false;

    return true;
  }

  @Override
  public int hashCode() {
    int result;
    result = (myStroke != null ? myStroke.hashCode() : 0);
    result = 31 * result + (myType != null ? myType.hashCode() : 0);
    return result;
  }

  public static class DblClick extends KeyboardModifierGestureShortcut {
    public DblClick(final KeyStroke stroke) {
      super(stroke, KeyboardGestureAction.ModifierType.dblClick);
    }
  }

  public static class Hold extends KeyboardModifierGestureShortcut {
    public Hold(final KeyStroke stroke) {
      super(stroke, KeyboardGestureAction.ModifierType.hold);
    }
  }

  @Override
  public String toString() {
    String s = getType() == KeyboardGestureAction.ModifierType.dblClick ? "Press, release and hold " : "Hold ";
    s += KeymapUtil.getKeystrokeText(this.getStroke());
    return s;
  }
}


text:
#pragma once
#include <aws/pinpoint/Pinpoint_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace Pinpoint
{
namespace Model
{

  /**
   * Phone Number Information response.

See Also:
   AWS
   * API Reference

   */
  class AWS_PINPOINT_API NumberValidateResponse
  {
  public:
    NumberValidateResponse();
    NumberValidateResponse(Aws::Utils::Json::JsonView jsonValue);
    NumberValidateResponse& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     * The carrier or servive provider that the phone number is currently registered
     * with.
     */
    inline const Aws::String& GetCarrier() const{ return m_carrier; }

    /**
     * The carrier or servive provider that the phone number is currently registered
     * with.
     */
    inline void SetCarrier(const Aws::String& value) { m_carrierHasBeenSet = true; m_carrier = value; }

    /**
     * The carrier or servive provider that the phone number is currently registered
     * with.
     */
    inline void SetCarrier(Aws::String&& value) { m_carrierHasBeenSet = true; m_carrier = std::move(value); }

    /**
     * The carrier or servive provider that the phone number is currently registered
     * with.
     */
    inline void SetCarrier(const char* value) { m_carrierHasBeenSet = true; m_carrier.assign(value); }

    /**
     * The carrier or servive provider that the phone number is currently registered
     * with.
     */
    inline NumberValidateResponse& WithCarrier(const Aws::String& value) { SetCarrier(value); return *this;}

    /**
     * The carrier or servive provider that the phone number is currently registered
     * with.
     */
    inline NumberValidateResponse& WithCarrier(Aws::String&& value) { SetCarrier(std::move(value)); return *this;}

    /**
     * The carrier or servive provider that the phone number is currently registered
     * with.
     */
    inline NumberValidateResponse& WithCarrier(const char* value) { SetCarrier(value); return *this;}

    /**
     * The city where the phone number was originally registered.
     */
    inline const Aws::String& GetCity() const{ return m_city; }

    /**
     * The city where the phone number was originally registered.
     */
    inline void SetCity(const Aws::String& value) { m_cityHasBeenSet = true; m_city = value; }

    /**
     * The city where the phone number was originally registered.
     */
    inline void SetCity(Aws::String&& value) { m_cityHasBeenSet = true; m_city = std::move(value); }

    /**
     * The city where the phone number was originally registered.
     */
    inline void SetCity(const char* value) { m_cityHasBeenSet = true; m_city.assign(value); }

    /**
     * The city where the phone number was originally registered.
     */
    inline NumberValidateResponse& WithCity(const Aws::String& value) { SetCity(value); return *this;}

    /**
     * The city where the phone number was originally registered.
     */
    inline NumberValidateResponse& WithCity(Aws::String&& value) { SetCity(std::move(value)); return *this;}

    /**
     * The city where the phone number was originally registered.
     */
    inline NumberValidateResponse& WithCity(const char* value) { SetCity(value); return *this;}

    /**
     * The cleansed phone number, shown in E.164 format.
     */
    inline const Aws::String& GetCleansedPhoneNumberE164() const{ return m_cleansedPhoneNumberE164; }

    /**
     * The cleansed phone number, shown in E.164 format.
     */
    inline void SetCleansedPhoneNumberE164(const Aws::String& value) { m_cleansedPhoneNumberE164HasBeenSet = true; m_cleansedPhoneNumberE164 = value; }

    /**
     * The cleansed phone number, shown in E.164 format.
     */
    inline void SetCleansedPhoneNumberE164(Aws::String&& value) { m_cleansedPhoneNumberE164HasBeenSet = true; m_cleansedPhoneNumberE164 = std::move(value); }

    /**
     * The cleansed phone number, shown in E.164 format.
     */
    inline void SetCleansedPhoneNumberE164(const char* value) { m_cleansedPhoneNumberE164HasBeenSet = true; m_cleansedPhoneNumberE164.assign(value); }

    /**
     * The cleansed phone number, shown in E.164 format.
     */
    inline NumberValidateResponse& WithCleansedPhoneNumberE164(const Aws::String& value) { SetCleansedPhoneNumberE164(value); return *this;}

    /**
     * The cleansed phone number, shown in E.164 format.
     */
    inline NumberValidateResponse& WithCleansedPhoneNumberE164(Aws::String&& value) { SetCleansedPhoneNumberE164(std::move(value)); return *this;}

    /**
     * The cleansed phone number, shown in E.164 format.
     */
    inline NumberValidateResponse& WithCleansedPhoneNumberE164(const char* value) { SetCleansedPhoneNumberE164(value); return *this;}

    /**
     * The cleansed phone number, shown in the local phone number format.
     */
    inline const Aws::String& GetCleansedPhoneNumberNational() const{ return m_cleansedPhoneNumberNational; }

    /**
     * The cleansed phone number, shown in the local phone number format.
     */
    inline void SetCleansedPhoneNumberNational(const Aws::String& value) { m_cleansedPhoneNumberNationalHasBeenSet = true; m_cleansedPhoneNumberNational = value; }

    /**
     * The cleansed phone number, shown in the local phone number format.
     */
    inline void SetCleansedPhoneNumberNational(Aws::String&& value) { m_cleansedPhoneNumberNationalHasBeenSet = true; m_cleansedPhoneNumberNational = std::move(value); }

    /**
     * The cleansed phone number, shown in the local phone number format.
     */
    inline void SetCleansedPhoneNumberNational(const char* value) { m_cleansedPhoneNumberNationalHasBeenSet = true; m_cleansedPhoneNumberNational.assign(value); }

    /**
     * The cleansed phone number, shown in the local phone number format.
     */
    inline NumberValidateResponse& WithCleansedPhoneNumberNational(const Aws::String& value) { SetCleansedPhoneNumberNational(value); return *this;}

    /**
     * The cleansed phone number, shown in the local phone number format.
     */
    inline NumberValidateResponse& WithCleansedPhoneNumberNational(Aws::String&& value) { SetCleansedPhoneNumberNational(std::move(value)); return *this;}

    /**
     * The cleansed phone number, shown in the local phone number format.
     */
    inline NumberValidateResponse& WithCleansedPhoneNumberNational(const char* value) { SetCleansedPhoneNumberNational(value); return *this;}

    /**
     * The country or region where the phone number was originally registered.
     */
    inline const Aws::String& GetCountry() const{ return m_country; }

    /**
     * The country or region where the phone number was originally registered.
     */
    inline void SetCountry(const Aws::String& value) { m_countryHasBeenSet = true; m_country = value; }

    /**
     * The country or region where the phone number was originally registered.
     */
    inline void SetCountry(Aws::String&& value) { m_countryHasBeenSet = true; m_country = std::move(value); }

    /**
     * The country or region where the phone number was originally registered.
     */
    inline void SetCountry(const char* value) { m_countryHasBeenSet = true; m_country.assign(value); }

    /**
     * The country or region where the phone number was originally registered.
     */
    inline NumberValidateResponse& WithCountry(const Aws::String& value) { SetCountry(value); return *this;}

    /**
     * The country or region where the phone number was originally registered.
     */
    inline NumberValidateResponse& WithCountry(Aws::String&& value) { SetCountry(std::move(value)); return *this;}

    /**
     * The country or region where the phone number was originally registered.
     */
    inline NumberValidateResponse& WithCountry(const char* value) { SetCountry(value); return *this;}

    /**
     * The two-character ISO code for the country or region where the phone number was
     * originally registered.
     */
    inline const Aws::String& GetCountryCodeIso2() const{ return m_countryCodeIso2; }

    /**
     * The two-character ISO code for the country or region where the phone number was
     * originally registered.
     */
    inline void SetCountryCodeIso2(const Aws::String& value) { m_countryCodeIso2HasBeenSet = true; m_countryCodeIso2 = value; }

    /**
     * The two-character ISO code for the country or region where the phone number was
     * originally registered.
     */
    inline void SetCountryCodeIso2(Aws::String&& value) { m_countryCodeIso2HasBeenSet = true; m_countryCodeIso2 = std::move(value); }

    /**
     * The two-character ISO code for the country or region where the phone number was
     * originally registered.
     */
    inline void SetCountryCodeIso2(const char* value) { m_countryCodeIso2HasBeenSet = true; m_countryCodeIso2.assign(value); }

    /**
     * The two-character ISO code for the country or region where the phone number was
     * originally registered.
     */
    inline NumberValidateResponse& WithCountryCodeIso2(const Aws::String& value) { SetCountryCodeIso2(value); return *this;}

    /**
     * The two-character ISO code for the country or region where the phone number was
     * originally registered.
     */
    inline NumberValidateResponse& WithCountryCodeIso2(Aws::String&& value) { SetCountryCodeIso2(std::move(value)); return *this;}

    /**
     * The two-character ISO code for the country or region where the phone number was
     * originally registered.
     */
    inline NumberValidateResponse& WithCountryCodeIso2(const char* value) { SetCountryCodeIso2(value); return *this;}

    /**
     * The numeric code for the country or region where the phone number was originally
     * registered.
     */
    inline const Aws::String& GetCountryCodeNumeric() const{ return m_countryCodeNumeric; }

    /**
     * The numeric code for the country or region where the phone number was originally
     * registered.
     */
    inline void SetCountryCodeNumeric(const Aws::String& value) { m_countryCodeNumericHasBeenSet = true; m_countryCodeNumeric = value; }

    /**
     * The numeric code for the country or region where the phone number was originally
     * registered.
     */
    inline void SetCountryCodeNumeric(Aws::String&& value) { m_countryCodeNumericHasBeenSet = true; m_countryCodeNumeric = std::move(value); }

    /**
     * The numeric code for the country or region where the phone number was originally
     * registered.
     */
    inline void SetCountryCodeNumeric(const char* value) { m_countryCodeNumericHasBeenSet = true; m_countryCodeNumeric.assign(value); }

    /**
     * The numeric code for the country or region where the phone number was originally
     * registered.
     */
    inline NumberValidateResponse& WithCountryCodeNumeric(const Aws::String& value) { SetCountryCodeNumeric(value); return *this;}

    /**
     * The numeric code for the country or region where the phone number was originally
     * registered.
     */
    inline NumberValidateResponse& WithCountryCodeNumeric(Aws::String&& value) { SetCountryCodeNumeric(std::move(value)); return *this;}

    /**
     * The numeric code for the country or region where the phone number was originally
     * registered.
     */
    inline NumberValidateResponse& WithCountryCodeNumeric(const char* value) { SetCountryCodeNumeric(value); return *this;}

    /**
     * The county where the phone number was originally registered.
     */
    inline const Aws::String& GetCounty() const{ return m_county; }

    /**
     * The county where the phone number was originally registered.
     */
    inline void SetCounty(const Aws::String& value) { m_countyHasBeenSet = true; m_county = value; }

    /**
     * The county where the phone number was originally registered.
     */
    inline void SetCounty(Aws::String&& value) { m_countyHasBeenSet = true; m_county = std::move(value); }

    /**
     * The county where the phone number was originally registered.
     */
    inline void SetCounty(const char* value) { m_countyHasBeenSet = true; m_county.assign(value); }

    /**
     * The county where the phone number was originally registered.
     */
    inline NumberValidateResponse& WithCounty(const Aws::String& value) { SetCounty(value); return *this;}

    /**
     * The county where the phone number was originally registered.
     */
    inline NumberValidateResponse& WithCounty(Aws::String&& value) { SetCounty(std::move(value)); return *this;}

    /**
     * The county where the phone number was originally registered.
     */
    inline NumberValidateResponse& WithCounty(const char* value) { SetCounty(value); return *this;}

    /**
     * The two-character ISO code for the country or region that you included in the
     * request body.
     */
    inline const Aws::String& GetOriginalCountryCodeIso2() const{ return m_originalCountryCodeIso2; }

    /**
     * The two-character ISO code for the country or region that you included in the
     * request body.
     */
    inline void SetOriginalCountryCodeIso2(const Aws::String& value) { m_originalCountryCodeIso2HasBeenSet = true; m_originalCountryCodeIso2 = value; }

    /**
     * The two-character ISO code for the country or region that you included in the
     * request body.
     */
    inline void SetOriginalCountryCodeIso2(Aws::String&& value) { m_originalCountryCodeIso2HasBeenSet = true; m_originalCountryCodeIso2 = std::move(value); }

    /**
     * The two-character ISO code for the country or region that you included in the
     * request body.
     */
    inline void SetOriginalCountryCodeIso2(const char* value) { m_originalCountryCodeIso2HasBeenSet = true; m_originalCountryCodeIso2.assign(value); }

    /**
     * The two-character ISO code for the country or region that you included in the
     * request body.
     */
    inline NumberValidateResponse& WithOriginalCountryCodeIso2(const Aws::String& value) { SetOriginalCountryCodeIso2(value); return *this;}

    /**
     * The two-character ISO code for the country or region that you included in the
     * request body.
     */
    inline NumberValidateResponse& WithOriginalCountryCodeIso2(Aws::String&& value) { SetOriginalCountryCodeIso2(std::move(value)); return *this;}

    /**
     * The two-character ISO code for the country or region that you included in the
     * request body.
     */
    inline NumberValidateResponse& WithOriginalCountryCodeIso2(const char* value) { SetOriginalCountryCodeIso2(value); return *this;}

    /**
     * The phone number that you included in the request body.
     */
    inline const Aws::String& GetOriginalPhoneNumber() const{ return m_originalPhoneNumber; }

    /**
     * The phone number that you included in the request body.
     */
    inline void SetOriginalPhoneNumber(const Aws::String& value) { m_originalPhoneNumberHasBeenSet = true; m_originalPhoneNumber = value; }

    /**
     * The phone number that you included in the request body.
     */
    inline void SetOriginalPhoneNumber(Aws::String&& value) { m_originalPhoneNumberHasBeenSet = true; m_originalPhoneNumber = std::move(value); }

    /**
     * The phone number that you included in the request body.
     */
    inline void SetOriginalPhoneNumber(const char* value) { m_originalPhoneNumberHasBeenSet = true; m_originalPhoneNumber.assign(value); }

    /**
     * The phone number that you included in the request body.
     */
    inline NumberValidateResponse& WithOriginalPhoneNumber(const Aws::String& value) { SetOriginalPhoneNumber(value); return *this;}

    /**
     * The phone number that you included in the request body.
     */
    inline NumberValidateResponse& WithOriginalPhoneNumber(Aws::String&& value) { SetOriginalPhoneNumber(std::move(value)); return *this;}

    /**
     * The phone number that you included in the request body.
     */
    inline NumberValidateResponse& WithOriginalPhoneNumber(const char* value) { SetOriginalPhoneNumber(value); return *this;}

    /**
     * A description of the phone type. Possible values are MOBILE, LANDLINE, VOIP,
     * INVALID, PREPAID, and OTHER.
     */
    inline const Aws::String& GetPhoneType() const{ return m_phoneType; }

    /**
     * A description of the phone type. Possible values are MOBILE, LANDLINE, VOIP,
     * INVALID, PREPAID, and OTHER.
     */
    inline void SetPhoneType(const Aws::String& value) { m_phoneTypeHasBeenSet = true; m_phoneType = value; }

    /**
     * A description of the phone type. Possible values are MOBILE, LANDLINE, VOIP,
     * INVALID, PREPAID, and OTHER.
     */
    inline void SetPhoneType(Aws::String&& value) { m_phoneTypeHasBeenSet = true; m_phoneType = std::move(value); }

    /**
     * A description of the phone type. Possible values are MOBILE, LANDLINE, VOIP,
     * INVALID, PREPAID, and OTHER.
     */
    inline void SetPhoneType(const char* value) { m_phoneTypeHasBeenSet = true; m_phoneType.assign(value); }

    /**
     * A description of the phone type. Possible values are MOBILE, LANDLINE, VOIP,
     * INVALID, PREPAID, and OTHER.
     */
    inline NumberValidateResponse& WithPhoneType(const Aws::String& value) { SetPhoneType(value); return *this;}

    /**
     * A description of the phone type. Possible values are MOBILE, LANDLINE, VOIP,
     * INVALID, PREPAID, and OTHER.
     */
    inline NumberValidateResponse& WithPhoneType(Aws::String&& value) { SetPhoneType(std::move(value)); return *this;}

    /**
     * A description of the phone type. Possible values are MOBILE, LANDLINE, VOIP,
     * INVALID, PREPAID, and OTHER.
     */
    inline NumberValidateResponse& WithPhoneType(const char* value) { SetPhoneType(value); return *this;}

    /**
     * The phone type, represented by an integer. Possible values include 0 (MOBILE), 1
     * (LANDLINE), 2 (VOIP), 3 (INVALID), 4 (OTHER), and 5 (PREPAID).
     */
    inline int GetPhoneTypeCode() const{ return m_phoneTypeCode; }

    /**
     * The phone type, represented by an integer. Possible values include 0 (MOBILE), 1
     * (LANDLINE), 2 (VOIP), 3 (INVALID), 4 (OTHER), and 5 (PREPAID).
     */
    inline void SetPhoneTypeCode(int value) { m_phoneTypeCodeHasBeenSet = true; m_phoneTypeCode = value; }

    /**
     * The phone type, represented by an integer. Possible values include 0 (MOBILE), 1
     * (LANDLINE), 2 (VOIP), 3 (INVALID), 4 (OTHER), and 5 (PREPAID).
     */
    inline NumberValidateResponse& WithPhoneTypeCode(int value) { SetPhoneTypeCode(value); return *this;}

    /**
     * The time zone for the location where the phone number was originally registered.
     */
    inline const Aws::String& GetTimezone() const{ return m_timezone; }

    /**
     * The time zone for the location where the phone number was originally registered.
     */
    inline void SetTimezone(const Aws::String& value) { m_timezoneHasBeenSet = true; m_timezone = value; }

    /**
     * The time zone for the location where the phone number was originally registered.
     */
    inline void SetTimezone(Aws::String&& value) { m_timezoneHasBeenSet = true; m_timezone = std::move(value); }

    /**
     * The time zone for the location where the phone number was originally registered.
     */
    inline void SetTimezone(const char* value) { m_timezoneHasBeenSet = true; m_timezone.assign(value); }

    /**
     * The time zone for the location where the phone number was originally registered.
     */
    inline NumberValidateResponse& WithTimezone(const Aws::String& value) { SetTimezone(value); return *this;}

    /**
     * The time zone for the location where the phone number was originally registered.
     */
    inline NumberValidateResponse& WithTimezone(Aws::String&& value) { SetTimezone(std::move(value)); return *this;}

    /**
     * The time zone for the location where the phone number was originally registered.
     */
    inline NumberValidateResponse& WithTimezone(const char* value) { SetTimezone(value); return *this;}

    /**
     * The postal code for the location where the phone number was originally
     * registered.
     */
    inline const Aws::String& GetZipCode() const{ return m_zipCode; }

    /**
     * The postal code for the location where the phone number was originally
     * registered.
     */
    inline void SetZipCode(const Aws::String& value) { m_zipCodeHasBeenSet = true; m_zipCode = value; }

    /**
     * The postal code for the location where the phone number was originally
     * registered.
     */
    inline void SetZipCode(Aws::String&& value) { m_zipCodeHasBeenSet = true; m_zipCode = std::move(value); }

    /**
     * The postal code for the location where the phone number was originally
     * registered.
     */
    inline void SetZipCode(const char* value) { m_zipCodeHasBeenSet = true; m_zipCode.assign(value); }

    /**
     * The postal code for the location where the phone number was originally
     * registered.
     */
    inline NumberValidateResponse& WithZipCode(const Aws::String& value) { SetZipCode(value); return *this;}

    /**
     * The postal code for the location where the phone number was originally
     * registered.
     */
    inline NumberValidateResponse& WithZipCode(Aws::String&& value) { SetZipCode(std::move(value)); return *this;}

    /**
     * The postal code for the location where the phone number was originally
     * registered.
     */
    inline NumberValidateResponse& WithZipCode(const char* value) { SetZipCode(value); return *this;}

  private:

    Aws::String m_carrier;
    bool m_carrierHasBeenSet;

    Aws::String m_city;
    bool m_cityHasBeenSet;

    Aws::String m_cleansedPhoneNumberE164;
    bool m_cleansedPhoneNumberE164HasBeenSet;

    Aws::String m_cleansedPhoneNumberNational;
    bool m_cleansedPhoneNumberNationalHasBeenSet;

    Aws::String m_country;
    bool m_countryHasBeenSet;

    Aws::String m_countryCodeIso2;
    bool m_countryCodeIso2HasBeenSet;

    Aws::String m_countryCodeNumeric;
    bool m_countryCodeNumericHasBeenSet;

    Aws::String m_county;
    bool m_countyHasBeenSet;

    Aws::String m_originalCountryCodeIso2;
    bool m_originalCountryCodeIso2HasBeenSet;

    Aws::String m_originalPhoneNumber;
    bool m_originalPhoneNumberHasBeenSet;

    Aws::String m_phoneType;
    bool m_phoneTypeHasBeenSet;

    int m_phoneTypeCode;
    bool m_phoneTypeCodeHasBeenSet;

    Aws::String m_timezone;
    bool m_timezoneHasBeenSet;

    Aws::String m_zipCode;
    bool m_zipCodeHasBeenSet;
  };

} // namespace Model
} // namespace Pinpoint
} // namespace Aws


text:
require 'spec_helper'

describe 'bin/lester renew' do
  include_context 'acceptance setup'

  let :command do
    Lester::Cli.new(argv, io)
  end

  let :argv do
    [
      'renew',
      '--domain', 'example.org',
      '--endpoint', 'http://127.0.0.1:4000',
      '--site-bucket', 'example-org-site',
      '--storage-bucket', storage_bucket_name,
      '--distribution-id', 'distribution-id',
      '--quiet',
    ]
  end

  let :storage_bucket_name do
    'example-org-backup'
  end

  before do
    storage_bucket.put_object(key: 'account/default.json', body: Pathname.new(private_key_path))
    cloudfront.add_config('distribution-id', {
      viewer_certificate: { iam_certificate_id: 'example.org-old' },
    })
  end

  describe '#run' do
    context 'with a registered private key', vcr: { cassette_name: 'new-certificate' } do
      it 'writes challenges to the expected path' do
        command.run
        key = '.well-known/acme-challenge/EGJjhjKuz9x5yNbH8IXfcZO6OljhIrwPQeTeZUcsKao'
        object = site_bucket.object(key)
        expect(object.read).to eq('EGJjhjKuz9x5yNbH8IXfcZO6OljhIrwPQeTeZUcsKao.XUQVUxLBe1x_yLe3HwXhatO3NImdF032T7C7BjKu6pc')
        key = '.well-known/acme-challenge/wdo3QEPA0D2mUav-Yx34nbNkq61bLOMjj_3obOYvE2E'
        object = site_bucket.object(key)
        expect(object.read).to eq('wdo3QEPA0D2mUav-Yx34nbNkq61bLOMjj_3obOYvE2E.XUQVUxLBe1x_yLe3HwXhatO3NImdF032T7C7BjKu6pc')
      end

      it 'uploads the new certificate' do
        command.run
        expect(iam.certificates).to_not be_empty
      end

      it 'installs the certificate' do
        command.run
        update = cloudfront.updates.first
        expect(update[:distribution_config][:viewer_certificate][:iam_certificate_id]).to eq('2ae9ea04d305762117cf854b39bb5ede')
      end

      it 'stores the certificate' do
        command.run
        object = storage_bucket.object('certificates/example.org/201512120949/cert.pem')
        expect { OpenSSL::X509::Certificate.new(object.read) }.to_not raise_error
      end

      it 'stores the certificate request' do
        command.run
        object = storage_bucket.object('certificates/example.org/201512120949/csr.pem')
        expect { OpenSSL::X509::Request.new(object.read) }.to_not raise_error
      end

      it 'stores the certificate chain' do
        command.run
        object = storage_bucket.object('certificates/example.org/201512120949/chain.pem')
        expect { OpenSSL::X509::Certificate.new(object.read) }.to_not raise_error
      end

      it 'stores the certificate fullchain' do
        command.run
        object = storage_bucket.object('certificates/example.org/201512120949/fullchain.pem')
        expect { OpenSSL::X509::Certificate.new(object.read) }.to_not raise_error
      end

      it 'stores the certificate private key' do
        command.run
        object = storage_bucket.object('certificates/example.org/201512120949/privkey.pem')
        expect { OpenSSL::PKey::RSA.new(object.read) }.to_not raise_error
      end

      it 'uses server side encryption for everything that is stored' do
        command.run
        keys = storage_bucket.keys.select { |k| k.start_with?('certificates/example.org') }
        expect(keys).to_not be_empty
        keys.each do |key|
          object = storage_bucket.object(key)
          expect(object.options).to include(server_side_encryption: 'AES256')
        end
      end

      it 'returns an ok exit code' do
        code = command.run
        expect(code).to eq(0)
      end

      context 'when a KMS ID is specified' do
        let :argv do
          [
            'renew',
            '--domain', 'example.org',
            '--endpoint', 'http://127.0.0.1:4000',
            '--site-bucket', 'example-org-site',
            '--storage-bucket', 'example-org-backup',
            '--distribution-id', 'distribution-id',
            '--kms-id', 'alias/letsencrypt',
            '--quiet',
          ]
        end

        it 'uses server side encryption through AWS KMS' do
          command.run
          keys = storage_bucket.keys.select { |k| k.start_with?('certificates/example.org') }
          expect(keys).to_not be_empty
          keys.each do |key|
            object = storage_bucket.object(key)
            expect(object.options).to include(server_side_encryption: 'aws:kms')
            expect(object.options).to include(ssekms_key_id: 'alias/letsencrypt')
          end
        end
      end

      context 'when --storage-bucket includes a prefix' do
        let :storage_bucket_name do
          'example-org-backup/lester'
        end

        it 'stores everything under given prefix' do
          storage_bucket.put_object(key: 'lester/account/default.json', body: Pathname.new(private_key_path))
          command.run
          keys = storage_bucket.keys.select { |k| k.start_with?('lester/certificates') }
          expect(keys).to_not be_empty
        end
      end
    end

    context 'when verification fails', vcr: { cassette_name: 'verification-fail' } do
      it 'prints an error message' do
        command.run
        expect(io.string).to match(/unauthorized: Invalid response/)
      end

      it 'returns a non-ok exit code' do
        command.run
        code = command.run
        expect(code).to eq(1)
      end
    end

    context 'with a non-registered private key', vcr: { cassette_name: 'new-certificate-fail' } do
      it 'prints an error message' do
        command.run
        expect(io.string.chomp).to match(/No registration exists matching provided key \(Acme::Client::Error::Unauthorized\)/)
      end

      it 'returns a non-ok exit code' do
        code = command.run
        expect(code).to eq(1)
      end
    end
  end
end


text:
<?php
class ModelExtensionTotalReward extends Model {
	public function getTotal($total) {
		if (isset($this->session->data['reward'])) {
			$this->load->language('extension/total/reward');

			$points = $this->customer->getRewardPoints();

			if ($this->session->data['reward'] <= $points) {
				$discount_total = 0;

				$points_total = 0;

				foreach ($this->cart->getProducts() as $product) {
					if ($product['points']) {
						$points_total += $product['points'];
					}
				}

				$points = min($points, $points_total);

				foreach ($this->cart->getProducts() as $product) {
					$discount = 0;

					if ($product['points']) {
						$discount = $product['total'] * ($this->session->data['reward'] / $points_total);

						if ($product['tax_class_id']) {
							$tax_rates = $this->tax->getRates($product['total'] - ($product['total'] - $discount), $product['tax_class_id']);

							foreach ($tax_rates as $tax_rate) {
								if ($tax_rate['type'] == 'P') {
									$total['taxes'][$tax_rate['tax_rate_id']] -= $tax_rate['amount'];
								}
							}
						}
					}

					$discount_total += $discount;
				}

				$total['totals'][] = array(
					'code'       => 'reward',
					'title'      => sprintf($this->language->get('text_reward'), $this->session->data['reward']),
					'value'      => -$discount_total,
					'sort_order' => $this->config->get('reward_sort_order')
				);

				$total['total'] -= $discount_total;
			}
		}
	}

	public function confirm($order_info, $order_total) {
		$this->load->language('extension/total/reward');

		$points = 0;

		$start = strpos($order_total['title'], '(') + 1;
		$end = strrpos($order_total['title'], ')');

		if ($start && $end) {
			$points = substr($order_total['title'], $start, $end - $start);
		}

		$this->load->model('account/customer');

		if ($this->model_account_customer->getRewardTotal($order_info['customer_id']) >= $points) {
			$this->db->query("INSERT INTO " . DB_PREFIX . "customer_reward SET customer_id = '" . (int)$order_info['customer_id'] . "', order_id = '" . (int)$order_info['order_id'] . "', description = '" . $this->db->escape(sprintf($this->language->get('text_order_id'), (int)$order_info['order_id'])) . "', points = '" . (float)-$points . "', date_added = NOW()");
		} else {
			return $this->config->get('config_fraud_status_id');
		}
	}

	public function unconfirm($order_id) {
		$this->db->query("DELETE FROM " . DB_PREFIX . "customer_reward WHERE order_id = '" . (int)$order_id . "' AND points < 0");
	}
}