text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="HandheldFriendly" content="true" />
  <link rel="shortcut icon" href="https://www.epa.gov/sites/all/themes/epa/favicon.ico" type="image/vnd.microsoft.icon" />
  <meta name="MobileOptimized" content="width" />
  <meta http-equiv="cleartype" content="on" />
  <meta http-equiv="ImageToolbar" content="false" />
  <meta name="viewport" content="width=device-width" />
  <meta name="version" content="20161218" />

  <meta name="DC.description" content="" />
  <meta name="DC.title" content="" />
  <title>
  Causes and Consequences of Variation in the Invasive Lizard, Anolis sagrei|

  Research Project Database | Grantee Research Project | ORD | US EPA</title>

  <meta name="keywords" content="" />
  <link rel="shortlink" href="" />
  <link rel="canonical" href="" />
  <meta name="DC.creator" content="" />
  <meta name="DC.language" content="en" />
  <meta name="DC.Subject.epachannel" content="" />
  <meta name="DC.type" content="" />
  <meta name="DC.date.created" content="" />
  <meta name="DC.date.modified" content="2004-06-09" />

  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/misc/ui/jquery.ui.autocomplete.css" media="all" />
  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/sites/all/themes/epa/css/lib/jquery.ui.theme.css" media="all" />
  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/sites/all/libraries/template2/s.css" media="all" />

	<link rel="alternate" type="application/atom+xml" title="EPA.gov All Press Releases" href="https://www.epa.gov/newsreleases/search/rss" />
	<link rel="alternate" type="application/atom+xml" title="EPA.gov Headquarters Press Releases" href="https://www.epa.gov/newsreleases/search/rss/field_press_office/headquarters" />
	<link rel="alternate" type="application/atom+xml" title="Greenversations, EPA's Blog" href="https://blog.epa.gov/blog/feed/" />

Jump to main content

  <hgroup class="site-name-and-slogan">

US EPA

United States Environmental Protection Agency

  </hgroup>
  <form class="epa-search" method="get" action="https://search.epa.gov/epasearch/epasearch">
    Search
    <input class="form-text" placeholder="Search EPA.gov" name="querytext" id="search-box" value=""/>
    <button class="epa-search-button" id="search-button" type="submit" title="Search">Search</button>
    <input type="hidden" name="fld" value="" />
    <input type="hidden" name="areaname" value="" />
    <input type="hidden" name="areacontacts" value="" />
    <input type="hidden" name="areasearchurl" value="" />
    <input type="hidden" name="typeofsearch" value="epa" />
    <input type="hidden" name="result_template" value="2col.ftl" />
    <input type="hidden" name="filter" value="sample4filt.hts" />
  </form>

Contact Us

Related Information

Research Grants

P3: Student Design Competition

Research Fellowships

Small Business Innovation Research (SBIR)

Grantee Research Project Results Search

      Causes and Consequences of Variation in the Invasive Lizard, Anolis sagrei

    EPA Grant Number: U916175

    Title: Causes and Consequences of Variation in the Invasive Lizard, Anolis sagrei

    Investigators:
     Kolbe, Jason J.

    Institution:

      Washington University

    	EPA Project Officer:

           Graham, Karen

      Project Period:
      January 1, 2003 through
        January 1, 2006

        Project Amount:

          $81,769

      RFA:
      STAR Graduate Fellowships (2003)

          Recipients Lists

      Research Category:

          Fellowship - Zoology
          ,
          Academic Fellowships
          ,
          Biology/Life Sciences

Objective:

The objective of this research project is to
  test the following
hypotheses concerning this problem:

1. Do populations of A. sagrei from introduced and native areas differ in
  their ecology, morphology, and behavior?

2. Does the population of origin or the new environment predict the pheno-types
  of introduced populations of A. sagrei?

Invasive species are second only to habitat destruction as the greatest threat
  to biodiversity (Wilson, 1992; Wilcove, 1998). Conservation strategies attempting
  to deal with invasive species often are hampered by a lack of knowledge of
  the invasion history and changes in the biology of invading organisms relative
  to their native range (Tsutsui, et al., 2001). A key question concerning the
  establishment of an invasive species in a new area is whether the invading
  species arrives preadapted to coexist with members of the new community or
  if competition upon arrival leads to rapid evolutionary change and subsequent
  coexistence (Losos, et al., 1993). Invasive species that are preadapted for
  coexistence in their new environment may have a greater impact on native fauna
  if sufficient differences in resource use do not exist; competition may result
  in the extinction of either the invader or one or more residents. Understanding
  the relative importance of these factors for invaders, and the patterns of
  genetic and phenotypic variation in both the native and introduced ranges of
  an invasive species, is essential for formulating management strategies in
  the introduced areas and assessing future risk of invasion in new areas.

Approach:

The native range of A. sagrei includes Cuba, the
    Bahamas, Cayman Brac, Little Cayman, Swan Island, Jamaica, and the Caribbean
    coast of Mexico
    and Belize (Schwartz and Henderson, 1991). Introductions over the past 60
  years have resulted in established A. sagrei populations in Hawaii, Texas,
  Louisiana,
    Grand Cayman, Taiwan, and, most notably, Florida (Lee, 1985; McKeown, 1996).
    Continued northerly expansion of populations from Florida into Georgia suggests
    that the A. sagrei invasion has not yet stabilized (Echternacht, et al.,
  1995; Campbell, 1996). Where it is invasive, negative effects of A. sagrei  on native
    fauna are numerous and include competition-induced habitat shifts (Losos,
  et al., 1993), decreases in population density (Campbell, 1999; Echternacht,
  1999),
    and intraguild predation (Gerber and Echternacht, 2000). Only 10 years after
    its introduction to Grand Cayman, A. sagrei occupied most of the island,
  occurred in very high densities in some areas, and displaced the native anole,
    Anolis
    conspersus, in some habitats. This introduction resulted in a shift in structural
    habitat and potentially influenced the life history and survival of this
  native lizard (Losos, et al., 1993). Evidence from experimental introductions
  of A.
    sagrei showed that introduced A. sagrei increased dramatically in density
  at the expense of native Anolis carolinensis (Campbell, 1999) and A. carolinensis  persisted at lower densities and was more likely to go extinct when on islands
    with A. sagrei (Losos and Spiller, 1999). Furthermore, asymmetrical intraguild
    predation exists between introduced A. sagrei and native A. carolinensis  from
    Florida and A. conspersus from Grand Cayman (Gerber and Echternacht, 2000).
    Adult A. sagrei are significantly more likely to eat juveniles from the two
    native species than the native species are to eat introduced juveniles. The
    predatory effects of A. sagrei on congeners are of particular concern because
    of the greater potential for predators to cause extinctions compared to the
    effect of competitors (Mooney & Cleland, 2001).

As introductions of invasive species continue, and A. sagrei continues to
  expand its range, many questions remain concerning the effect of invasive species
  on native fauna. Limited study of A. sagrei indicates highly detrimental effects
  of this invasive on native lizards. However, little is known about the causes
  of variation in ecology, morphology, and behavior of invasive species or the
  consequences of this variation for interactions with native species. Within
  its native range, A. sagrei is extremely variable in morphology, life history,
  and physiology (e.g., Lister, 1976; Lee, 1992) and is divided into locally
  endemic populations that may be unique species (J. Kolbe, unpublished data).
  This extreme phenotypic and genetic variability within its native range makes
  pinpointing the causes and consequences of invasive A. sagrei populations very
  difficult. Thus, any approach to determining why A. sagrei is invasive needs
  to connect patterns of variation between introduced and source populations,
  and is best accomplished by using an approach that incorporates the historical
  relationships among native and introduced populations. A historical approach
  will facilitate identification of the relative importance of ecological vs.
  evolutionary factors that lead to the coexistence of invasive A. sagrei in
  new communities. I propose an integrative approach combining molecular analysis
  of genetic variation within A. sagrei and comparative analyses of ecological,
  morphological, and behavioral trait variation between introduced and source
  populations. This information will serve as the basis for sound management
  decisions to mitigate the impact of invasive A. sagrei on native fauna, both
  in areas where A. sagrei currently is invasive and other areas where A.
  sagrei   introductions are possible. Successful management will benefit from addressing
  the three problems described below.

Problem 1: Uncertainty concerning the relationships among populations and
  the origin of introduced populations of Anolis sagrei. Many anole species are
  highly geographically structured (Glor, et al., 2001) and my preliminary data
  suggest that A. sagrei consists of several genetically differentiated populations.
  However, the extent of genetic differentiation throughout the native range
  of A. sagrei as well as the origin of introduced populations of A.
  sagrei in
  the United States and worldwide are unclear. Evidence exists that introduced
  populations in Florida are from both Cuba and the Bahamas (Lee, 1985), but
  the relative contribution of these or other source populations is unknown.
  Identifying the number of populations contributing to the invasion and their
  geographic origin is critical for understanding the causes and consequences
  of variation in this invasive species. Establishing this historical perspective,
  that is, the relationships among A. sagrei populations, is a prerequisite for
  comparing variation in ecology, morphology, and behavior between introduced
  and native populations. This phylogenetic perspective will provide the context
  for comparative studies underlying the development of invasive species management
  plans. I propose to test the following hypotheses concerning this problem:

1. Are A. sagrei monophyletic (i.e., are all populations of A.
    sagrei more
  closely related to each other than any is to populations of another species)?

2. What is the extent of locally endemic (i.e., genetically differentiated)
  populations throughout the native range of A. sagrei?

3.	Where did the introduced
    populations of A. sagrei originate?

Problem 2: Lack of understanding of the causes of variation in ecology,
    morphology, and behavior of Anolis sagrei. Patterns of ecomorphological variation among
    Anolis lizard species are well studied (Losos, 1990a,b); however, detailed
  studies of variation in ecology, morphology, and behavior at the population
  level are lacking. Anolis sagrei shows geographic variation in morphology,
  life history, and physiology (e.g., Lister, 1976; Lee, 1992), including parts
  of its introduced range (Lee, 1985, 1987). Whether patterns of variation in
  introduced populations represent their ancestral heritage or adaptation to
  the new environments in which introduced populations exist is uncertain. Experimental
  evidence indicates that morphology can evolve rapidly in A. sagrei populations
  experiencing new structural environments (Losos, et al., 1997), but also suggests
  that phenotypic plasticity in hindlimb length may contribute to variability
  among individuals and populations (Losos, et al., 2000). Both causes of variation
  suggest an important influence of new environments on A. sagrei populations
  either through natural selection or phenotypic plasticity. Conversely, phenotypic
  evolution of introduced populations may be constrained because of low genetic
  variation associated with small founder populations or developmental canalization.
  Sorting out the causes and patterns of variation among introduced and native
  populations will provide the ecological and evolutionary context for evaluating
  the consequences of variation for native fauna. Furthermore, invasive species
  management plans that incorporate knowledge of the causes and patterns of variation
  in introduced populations will increase their chances for success.

Problem 3: Uncertainty about the consequences of different source
    populations of Anolis sagrei and their effects on native fauna in introduced
    areas. The
  impact of an invasive species is measured by the extent of its negative interactions,
  such as predation or competition, with native fauna (Mooney and Cleland, 2001).
  Some of the negative effects of A. sagrei on native fauna include competition-induced
  habitat shifts, intraguild predation, and decreases in population density.
  The extent to which these interactions are novel for A. sagrei in introduced
  areas is unknown. Are A. sagrei interacting differently with fauna in introduced
  areas as compared to its interaction with species in its native community?
  Do A. sagrei eat lizards in Cuba and Bahamas or just in introduced parts of
  its range? Do A. sagrei affect abundance of other species in its native range?
  These questions directly relate to whether invading species arrive preadapted
  to coexist with members of the new community or if competition upon arrival
  leads to evolutionary change and subsequent coexistence, which is likely a
  crucial element in determining invasion success rates and the extent of detrimental
  effects on native fauna. Knowledge of both the causes and patterns of variation
  in introduced populations and the consequences of this variation for native
  fauna will enhance the success of management plans. I propose to test the following
  hypotheses concerning this problem:

1. Does variation in ecological, morphological, and behavioral traits influence
  the effects of invasive A. sagrei on native fauna?

2. Do different A. sagrei source populations result in differential effects
  on native fauna?

The goal of this research is to understand the causes and consequences of
  ecological, morphological, and behavioral variation in the invasive lizard,
  Anolis sagrei. I will accomplish this goal using molecular phylogenetics to
  reconstruct the invasion history of A. sagrei and comparative ecological studies
  to determine the causes of phenotypic variation in introduced A. sagrei populations
  and the consequences for native fauna.

Supplemental Keywords:

      fellowship, invasive species, native fauna, Anolis sagrei, Anolis carolinensis, lizard, biodiversity threat, phenotypic plasticity, morphology.

Relevant Websites:

2004 STAR Graduate Fellowship Conference Poster (PDF, 1p., 1.57MB, about PDF)

Top of Page

 The perspectives, information and conclusions conveyed in research project abstracts, progress reports, final reports, journal abstracts and journal publications convey the viewpoints of the principal investigator and may not represent the views and policies of ORD and EPA.  Conclusions drawn by the principal investigators have not been reviewed by the Agency.

Main menu

Environmental Topics

Laws & Regulations

About EPA

Discover.

Accessibility

EPA Administrator

Budget & Performance

Contracting

Grants

No FEAR Act Data

Privacy and Security

Connect.

Data.gov

Inspector General

Jobs

Newsroom

Open Government

Regulations.gov

Subscribe

USA.gov

White House

Ask.

Contact Us

Hotlines

FOIA Requests

Frequent Questions

Follow.

Facebook

Twitter

YouTube

Flickr

Instagram

Last updated on Wednesday, June 9, 2004


text:
package io.druid.indexing.overlord.setup;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
import io.druid.indexing.common.task.Task;
import io.druid.indexing.overlord.ImmutableZkWorker;
import io.druid.indexing.overlord.TestRemoteTaskRunnerConfig;
import io.druid.jackson.DefaultObjectMapper;
import org.easymock.EasyMock;
import org.joda.time.Period;
import org.junit.Assert;
import org.junit.Test;

public class JavaScriptWorkerSelectStrategyTest
{

  final JavaScriptWorkerSelectStrategy strategy = new JavaScriptWorkerSelectStrategy(
      "function (config, zkWorkers, task) {\n"
      + "var batch_workers = new java.util.ArrayList();\n"
      + "batch_workers.add(\"10.0.0.1\");\n"
      + "batch_workers.add(\"10.0.0.2\");\n"
      + "workers = zkWorkers.keySet().toArray();\n"
      + "var sortedWorkers = new Array()\n;"
      + "for(var i = 0; i < workers.length; i++){\n"
      + " sortedWorkers[i] = workers[i];\n"
      + "}\n"
      + "Array.prototype.sort.call(sortedWorkers,function(a, b){return zkWorkers.get(b).getCurrCapacityUsed() - zkWorkers.get(a).getCurrCapacityUsed();});\n"
      + "var minWorkerVer = config.getMinWorkerVersion();\n"
      + "for (var i = 0; i < sortedWorkers.length; i++) {\n"
      + " var worker = sortedWorkers[i];\n"
      + "  var zkWorker = zkWorkers.get(worker);\n"
      + "  if(zkWorker.canRunTask(task) && zkWorker.isValidVersion(minWorkerVer)){\n"
      + "    if(task.getType() == 'index_hadoop' && batch_workers.contains(worker)){\n"
      + "      return worker;\n"
      + "    } else {\n"
      + "      if(task.getType() != 'index_hadoop' && !batch_workers.contains(worker)){\n"
      + "        return worker;\n"
      + "      }\n"
      + "    }\n"
      + "  }\n"
      + "}\n"
      + "return null;\n"
      + "}"
  );

  @Test
  public void testSerde() throws Exception
  {
    ObjectMapper mapper = new DefaultObjectMapper();
    Assert.assertEquals(
        strategy,
        mapper.readValue(
            mapper.writeValueAsString(strategy),
            JavaScriptWorkerSelectStrategy.class
        )
    );
  }

  @Test
  public void testFindWorkerForTask()
  {
    ImmutableZkWorker worker1 = createMockWorker(1, true, true);
    ImmutableZkWorker worker2 = createMockWorker(1, true, true);
    ImmutableMap<String, ImmutableZkWorker> workerMap = ImmutableMap.of(
        "10.0.0.1", worker1,
        "10.0.0.3", worker2
    );

    ImmutableZkWorker workerForBatchTask = strategy.findWorkerForTask(
        new TestRemoteTaskRunnerConfig(new Period("PT1S")),
        workerMap,
        createMockTask("index_hadoop")
    ).get();
    // batch tasks should be sent to worker1
    Assert.assertEquals(worker1, workerForBatchTask);

    ImmutableZkWorker workerForOtherTask = strategy.findWorkerForTask(
        new TestRemoteTaskRunnerConfig(new Period("PT1S")),
        workerMap,
        createMockTask("other_type")
    ).get();
    // all other tasks should be sent to worker2
    Assert.assertEquals(worker2, workerForOtherTask);
  }

  @Test
  public void testIsolationOfBatchWorker()
  {
    ImmutableMap<String, ImmutableZkWorker> workerMap = ImmutableMap.of(
        "10.0.0.1", createMockWorker(1, true, true),
        "10.0.0.2", createMockWorker(1, true, true)
    );
    Optional<ImmutableZkWorker> workerForOtherTask = strategy.findWorkerForTask(
        new TestRemoteTaskRunnerConfig(new Period("PT1S")),
        workerMap,
        createMockTask("other_type")
    );
    Assert.assertFalse(workerForOtherTask.isPresent());
  }

  @Test
  public void testNoValidWorker()
  {
    ImmutableMap<String, ImmutableZkWorker> workerMap = ImmutableMap.of(
        "10.0.0.1", createMockWorker(1, true, false),
        "10.0.0.4", createMockWorker(1, true, false)
    );
    Optional<ImmutableZkWorker> workerForBatchTask = strategy.findWorkerForTask(
        new TestRemoteTaskRunnerConfig(new Period("PT1S")),
        workerMap,
        createMockTask("index_hadoop")
    );
    Assert.assertFalse(workerForBatchTask.isPresent());

    Optional<ImmutableZkWorker> workerForOtherTask = strategy.findWorkerForTask(
        new TestRemoteTaskRunnerConfig(new Period("PT1S")),
        workerMap,
        createMockTask("otherTask")
    );
    // all other tasks should be sent to worker2
    Assert.assertFalse(workerForOtherTask.isPresent());
  }

  @Test
  public void testNoWorkerCanRunTask()
  {
    ImmutableMap<String, ImmutableZkWorker> workerMap = ImmutableMap.of(
        "10.0.0.1", createMockWorker(1, false, true),
        "10.0.0.4", createMockWorker(1, false, true)
    );
    Optional<ImmutableZkWorker> workerForBatchTask = strategy.findWorkerForTask(
        new TestRemoteTaskRunnerConfig(new Period("PT1S")),
        workerMap,
        createMockTask("index_hadoop")
    );
    Assert.assertFalse(workerForBatchTask.isPresent());

    Optional<ImmutableZkWorker> workerForOtherTask = strategy.findWorkerForTask(
        new TestRemoteTaskRunnerConfig(new Period("PT1S")),
        workerMap,
        createMockTask("otherTask")
    );
    // all other tasks should be sent to worker2
    Assert.assertFalse(workerForOtherTask.isPresent());
  }

  @Test
  public void testFillWorkerCapacity()
  {
    // tasks shoudl be assigned to the worker with maximum currCapacity used until its full
    ImmutableMap<String, ImmutableZkWorker> workerMap = ImmutableMap.of(
        "10.0.0.1", createMockWorker(1, true, true),
        "10.0.0.2", createMockWorker(5, true, true)
    );
    Optional<ImmutableZkWorker> workerForBatchTask = strategy.findWorkerForTask(
        new TestRemoteTaskRunnerConfig(new Period("PT1S")),
        workerMap,
        createMockTask("index_hadoop")
    );
    Assert.assertEquals(workerMap.get("10.0.0.2"), workerForBatchTask.get());

  }

  private Task createMockTask(String type)
  {
    Task mock = EasyMock.createMock(Task.class);
    EasyMock.expect(mock.getType()).andReturn(type).anyTimes();
    EasyMock.replay(mock);
    return mock;
  }

  private ImmutableZkWorker createMockWorker(int currCapacityUsed, boolean canRunTask, boolean isValidVersion)
  {
    ImmutableZkWorker worker = EasyMock.createMock(ImmutableZkWorker.class);
    EasyMock.expect(worker.canRunTask(EasyMock.anyObject(Task.class))).andReturn(canRunTask).anyTimes();
    EasyMock.expect(worker.getCurrCapacityUsed()).andReturn(currCapacityUsed).anyTimes();
    EasyMock.expect(worker.isValidVersion(EasyMock.anyString())).andReturn(isValidVersion).anyTimes();
    EasyMock.replay(worker);
    return worker;
  }

}

redpajama_set_name: RedPajamaGithub


text:
package net.craftstars.general.command.inven;

import static java.lang.Math.min;

import java.util.HashMap;
import java.util.Map;

import net.craftstars.general.command.CommandBase;
import net.craftstars.general.General;
import net.craftstars.general.items.ItemID;
import net.craftstars.general.items.Items;
import net.craftstars.general.option.Options;
import net.craftstars.general.text.LanguageText;
import net.craftstars.general.text.Messaging;
import net.craftstars.general.util.EconomyManager;
import net.craftstars.general.util.Toolbox;

import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;

public class takeCommand extends CommandBase {
	public takeCommand(General instance) {
		super(instance);
	}

	@Override
	public Map<String, Object> parse(CommandSender sender, Command command, String label, String[] args, boolean isPlayer) {
		HashMap<String,Object> params = new HashMap<String,Object>();
		params.put("inHand", false);
		Player who = null;
		ItemID item = null;
		int amount = 0;
		switch(args.length) {
		case 0: // /take
			if(!isPlayer) return null;
			who = (Player) sender;
			item = new ItemID(who.getItemInHand());
			amount = who.getItemInHand().getAmount();
			params.put("inHand", true);
		break;
		case 1: // /take <item>[:<data>]
			if(!isPlayer) return null;
			who = (Player) sender;
			item = Items.validate(args[0]);
		break;
		case 2: // /take <item>[:<data>] <amount> OR /take <item>[:<data>] <player>
			item = Items.validate(args[0]);
			who = Toolbox.matchPlayer(args[1]);
			if(isPlayer) try {
				amount = Integer.valueOf(args[1]);
				who = (Player) sender;
			} catch(NumberFormatException x) {
				Messaging.send(sender, LanguageText.GIVE_BAD_AMOUNT);
			}
			if(who == null) {
				Messaging.invalidPlayer(sender, args[1]);
				return null;
			}
		break;
		case 3: // /take <item>[:<data>] <amount> <player>
			who = Toolbox.matchPlayer(args[2]);
			if(who == null) {
				Messaging.invalidPlayer(sender, args[2]);
				return null;
			}
			item = Items.validate(args[0]);
			try {
				amount = Integer.valueOf(args[1]);
			} catch(NumberFormatException x) {
				Messaging.send(sender, LanguageText.GIVE_BAD_AMOUNT);
				return null;
			}
		break; // /take <player> <item> <amount> <data> (amount can be : to imply 1)
		case 4:
			try {
				amount = args[2].equals(":") ? 1 : Integer.valueOf(args[2]);
			} catch(NumberFormatException e) {
				Messaging.send(sender, LanguageText.GIVE_BAD_AMOUNT);
				return null;
			}
			who = Toolbox.matchPlayer(args[0]);
			if(who == null) {
				Messaging.invalidPlayer(sender, args[2]);
				return null;
			}
			item = Items.validate(args[1] + "/" + args[3]);
		default:
			return null;
		}
		// Fill in params and go!
		params.put("player", who);
		params.put("item", item);
		params.put("amount", amount);
		return params;
	}

	@Override
	public boolean execute(CommandSender sender, String command, Map<String, Object> args) {
		if(!sender.hasPermission("general.take"))
			return Messaging.lacksPermission(sender, "general.take");
		Player who = (Player) args.get("player");
		ItemID item = (ItemID) args.get("item");
		int amount = (Integer) args.get("amount");
		boolean sell = who.equals(sender);
		if(!sell && !sender.hasPermission("general.take.other"))
			return Messaging.lacksPermission(sender, "general.take.other");
		sell = sell && Options.NO_ECONOMY.get();
		sell = sell && Options.ECONOMY_TAKE_SELL.get().equalsIgnoreCase("sell");
		amount = doTake(who, item, amount, sell, (Boolean)args.get("inHand"));
		if(!sender.equals(who)) Messaging.send(sender, LanguageText.TAKE_THEFT.value("item", item.getName(null),
			"amount", amount, "player", who.getName()));
		return true;
	}

	private int doTake(Player who, ItemID item, int amount, boolean sell, boolean inHand) {
		int removed = 0;
		PlayerInventory i = who.getInventory();
		if(inHand) {
			removed = who.getItemInHand().getAmount();
			who.setItemInHand(null);
		} else if(item.getId() == ItemID.EXP) {
			int currentXP = who.getTotalExperience();
			removed = amount == 0 ? currentXP : min(amount, currentXP);
			int newXP = currentXP - removed;
			Toolbox.resetExperience(who);
			who.giveExp(newXP);
		} else {
			Map<Integer, ? extends ItemStack> items = i.all(item.getId());
			for(int x : items.keySet()) {
				ItemStack stk = items.get(x);
				int n, d;
				n = stk.getAmount();
				d = stk.getDurability();
				if(!Items.dataEquiv(item, d)) continue;
				if(amount > 0 && n > amount) {
					stk.setAmount(n - amount);
					removed += amount;
					amount = 0;
					break;
				} else if(n <= amount) {
					amount -= n;
					removed += n;
					i.setItem(x, null);
				} else if(amount <= 0) i.setItem(x, null);
			}
		}
		Messaging.send(who, LanguageText.TAKE_TOOK.value("item", item.getName(null),
			"amount", removed <= amount ? removed : 0));
		if(sell) {
			double revenue = EconomyManager.sellItem(item, removed);
			EconomyManager.giveMoney(who, revenue);
			Messaging.earned(who, revenue);
		}
		return removed;
	}
}


text:
source helpers.sh

alg_primary_obj=0x000B
alg_primary_key=0x0001
alg_create_obj=0x000B
alg_create_key=hmac

file_primary_key_ctx=context.p_"$alg_primary_obj"_"$alg_primary_key"
file_readpub_key_pub=opu_"$alg_create_obj"_"$alg_create_key"
file_readpub_key_priv=opr_"$alg_create_obj"_"$alg_create_key"
file_readpub_key_name=name.load_"$alg_primary_obj"_"$alg_primary_key"-"$alg_create_obj"_"$alg_create_key"
file_readpub_key_ctx=ctx_load_out_"$alg_primary_obj"_"$alg_primary_key"-"$alg_create_obj"_"$alg_create_key"
file_readpub_output=readpub_"$file_readpub_key_ctx"

Handle_readpub=0x81010014

cleanup() {
    rm -f $file_primary_key_ctx $file_readpub_key_pub $file_readpub_key_priv \
    $file_readpub_key_name $file_readpub_key_ctx $file_readpub_output

    tpm2_evictcontrol -Q -a o -c $Handle_readpub 2>/dev/null || true

    if [ "$1" != "no-shut-down" ]; then
       shut_down
    fi
}
trap cleanup EXIT

start_up

cleanup "no-shut-down"

tpm2_clear

tpm2_createprimary -Q -a e -g $alg_primary_obj -G $alg_primary_key -o $file_primary_key_ctx

tpm2_create -Q -g $alg_create_obj -G $alg_create_key -u $file_readpub_key_pub -r $file_readpub_key_priv  -C $file_primary_key_ctx

tpm2_load -Q -C $file_primary_key_ctx  -u $file_readpub_key_pub  -r $file_readpub_key_priv -n $file_readpub_key_name -o $file_readpub_key_ctx

tpm2_readpublic -Q -c $file_readpub_key_ctx -o $file_readpub_output

tpm2_evictcontrol -Q -a o -c $file_readpub_key_ctx -p $Handle_readpub

rm -f $file_readpub_output
tpm2_readpublic -Q -c $Handle_readpub -o $file_readpub_output

exit 0


text:
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.2"?>
<plugin>
   <extension
         point="org.eclipse.ui.perspectives">
      <perspective
            class="org.marketcetera.photon.test.WorkbenchRunner$Perspective"
            id="org.marketcetera.photon.test.WorkbenchRunner$Perspective"
            name="Test Perspective">
      </perspective>
   </extension>

</plugin>


text:
param(
    [string]$target = "Test",
    [string]$verbosity = "minimal",
    [int]$maxCpuCount = 0
)

# Kill all MSBUILD.EXE processes because they could very likely have a lock against our
# MSBuild runner from when we last ran unit tests.
get-process -name "msbuild" -ea SilentlyContinue | %{ stop-process $_.ID -force }

$msbuilds = @(get-command msbuild -ea SilentlyContinue)
if ($msbuilds.Count -gt 0) {
    $msbuild = $msbuilds[0].Definition
}
else {
    if (test-path "env:\ProgramFiles(x86)") {
        $path = join-path ${env:ProgramFiles(x86)} "MSBuild\14.0\bin\MSBuild.exe"
        if (test-path $path) {
            $msbuild = $path
        }
    }
    if ($msbuild -eq $null) {
        $path = join-path $env:ProgramFiles "MSBuild\14.0\bin\MSBuild.exe"
        if (test-path $path) {
            $msbuild = $path
        }
    }
    if ($msbuild -eq $null) {
        throw "MSBuild could not be found in the path. Please ensure MSBuild v14 (from Visual Studio 2015) is in the path."
    }
}

if ($maxCpuCount -lt 1) {
    $maxCpuCountText = $Env:MSBuildProcessorCount
} else {
    $maxCpuCountText = ":$maxCpuCount"
}

$allArgs = @("build.proj", "/m$maxCpuCountText", "/nologo", "/verbosity:$verbosity", "/t:$target", "/property:RequestedVerbosity=$verbosity", $args)
& $msbuild $allArgs


text:
module TargetProcess
  VERSION = "0.0.1"
end


text:
'use strict';

function commitLocalUpdate(environment, updater) {
  environment.commitUpdate(updater);
}

module.exports = commitLocalUpdate;


text:
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

    <ImageView
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:id="@+id/expense_list_image"
            android:src="@drawable/ic_bankcards"
            android:layout_marginRight="10dp"
            android:layout_gravity="center_vertical"
            android:layout_centerVertical="true"/>

    <LinearLayout
                  android:layout_width="fill_parent"
                  android:layout_height="wrap_content"
                  android:orientation="vertical"
                  android:id="@+id/expense_list_item"
                  android:layout_toRightOf="@+id/expense_list_image">

        <TextView android:id="@+id/expense_view"
                  android:layout_width="fill_parent"
                  android:layout_height="wrap_content"
                  android:textSize="20sp"
                  android:paddingTop="5dp" />

        <TextView android:id="@+id/expense_view_total"
                  android:layout_width="fill_parent"
                  android:layout_height="wrap_content"
                  android:textSize="14sp"
                  android:paddingBottom="5dp" />

    </LinearLayout>
</RelativeLayout>


text:
namespace ranges
{
    inline namespace v3
    {
        /// \addtogroup group-core
        /// @{
        struct range_access
        {
            /// \cond
        private:
            template<typename T>
            static std::false_type single_pass_2_(long);
            template<typename T>
            static typename T::single_pass single_pass_2_(int);

            template<typename T>
            struct single_pass_
            {
                using type = decltype(range_access::single_pass_2_<T>(42));
            };

            template<typename T>
            static meta::id<basic_mixin<T>> mixin_base_2_(long);
            template<typename T>
            static meta::id<typename T::mixin> mixin_base_2_(int);

            template<typename Cur>
            struct mixin_base_
              : decltype(range_access::mixin_base_2_<Cur>(42))
            {};

        public:
            template<typename Cur>
            using single_pass_t = meta::_t<single_pass_<Cur>>;

            template<typename Cur>
            using mixin_base_t = meta::_t<mixin_base_<Cur>>;

            //
            // Concepts that the range cursor must model
            //
            struct Cursor
            {
                template<typename T>
                auto requires_() -> decltype(
                    concepts::valid_expr(
                        concepts::model_of<concepts::SemiRegular, T>(),
                        concepts::model_of<concepts::SemiRegular, mixin_base_t<T>>(),
                        concepts::model_of<concepts::Constructible, mixin_base_t<T>, T>(),
                        concepts::model_of<concepts::Constructible, mixin_base_t<T>, T const &>()
                    ));
                    // Axiom: mixin_base_t<T> has a member get(), accessible to derived classes,
                    //   which perfectly-returns the contained cursor object and does not throw
                    //   exceptions.
            };
            struct HasCursorNext
            {
                template<typename T>
                auto requires_(T &t) -> decltype(
                    concepts::valid_expr(
                        (t.next(), concepts::void_)
                    ));
            };
            struct CursorSentinel
              : concepts::refines<concepts::SemiRegular(concepts::_1), Cursor(concepts::_2)>
            {
                template<typename S, typename C>
                auto requires_(S &s, C &c) -> decltype(
                    concepts::valid_expr(
                        concepts::convertible_to<bool>(c.equal(s))
                    ));
            };
            struct ReadableCursor
            {
                template<typename T>
                auto requires_(T &t) -> decltype(
                    concepts::valid_expr(
                        t.read()
                    ));
            };
            struct HasCursorArrow
            {
                template<typename C>
                auto requires_(C const &c) -> decltype(
                    concepts::valid_expr(
                        c.arrow()
                    ));
            };
            struct WritableCursor
            {
                template<typename T, typename U>
                auto requires_(T &t, U &&u) -> decltype(
                    concepts::valid_expr(
                        (t.write((U &&) u), 42)
                    ));
            };
            struct SizedCursorSentinel
              : concepts::refines<CursorSentinel>
            {
                template<typename S, typename C>
                auto requires_(S &s, C &c) -> decltype(
                    concepts::valid_expr(
                        concepts::model_of<concepts::SignedIntegral>(c.distance_to(s))
                    ));
            };
            struct OutputCursor
              : concepts::refines<WritableCursor, Cursor(concepts::_1)>
            {};
            struct InputCursor
              : concepts::refines<ReadableCursor, Cursor, HasCursorNext>
            {};
            struct ForwardCursor
              : concepts::refines<InputCursor, CursorSentinel(concepts::_1, concepts::_1)>
            {
                template<typename T>
                auto requires_() -> decltype(
                    concepts::valid_expr(
                        concepts::is_false(single_pass_t<uncvref_t<T>>())
                    ));
            };
            struct BidirectionalCursor
              : concepts::refines<ForwardCursor>
            {
                template<typename T>
                auto requires_(T &t) -> decltype(
                    concepts::valid_expr(
                        (t.prev(), concepts::void_)
                    ));
            };
            struct RandomAccessCursor
              : concepts::refines<BidirectionalCursor, SizedCursorSentinel(concepts::_1, concepts::_1)>
            {
                template<typename T>
                auto requires_(T &t) -> decltype(
                    concepts::valid_expr(
                        (t.advance(t.distance_to(t)), concepts::void_)
                    ));
            };
            struct InfiniteCursor
            {
                template<typename T>
                auto requires_() -> decltype(
                    concepts::valid_expr(
                        concepts::is_true(typename T::is_infinite{})
                    ));
            };

            template<typename Rng>
            static RANGES_CXX14_CONSTEXPR auto begin_cursor(Rng &rng)
            RANGES_DECLTYPE_AUTO_RETURN_NOEXCEPT
            (
                rng.begin_cursor()
            )
            template<typename Rng>
            static RANGES_CXX14_CONSTEXPR auto end_cursor(Rng &rng)
            RANGES_DECLTYPE_AUTO_RETURN_NOEXCEPT
            (
                rng.end_cursor()
            )

            template<typename Rng>
            static RANGES_CXX14_CONSTEXPR auto begin_adaptor(Rng &rng)
            RANGES_DECLTYPE_AUTO_RETURN_NOEXCEPT
            (
                rng.begin_adaptor()
            )
            template<typename Rng>
            static RANGES_CXX14_CONSTEXPR auto end_adaptor(Rng &rng)
            RANGES_DECLTYPE_AUTO_RETURN_NOEXCEPT
            (
                rng.end_adaptor()
            )

            template<typename Cur>
            static RANGES_CXX14_CONSTEXPR auto read(Cur const &pos)
            RANGES_DECLTYPE_AUTO_RETURN_NOEXCEPT
            (
                pos.read()
            )
            template<typename Cur>
            static RANGES_CXX14_CONSTEXPR auto arrow(Cur const &pos)
            RANGES_DECLTYPE_AUTO_RETURN_NOEXCEPT
            (
                pos.arrow()
            )
            template<typename Cur>
            static RANGES_CXX14_CONSTEXPR auto move(Cur const &pos)
            RANGES_DECLTYPE_AUTO_RETURN_NOEXCEPT
            (
                pos.move()
            )
            template<typename Cur, typename T>
            static RANGES_CXX14_CONSTEXPR auto write(Cur &pos, T && t)
            RANGES_DECLTYPE_AUTO_RETURN_NOEXCEPT
            (
                pos.write((T &&) t)
            )
            template<typename Cur>
            static RANGES_CXX14_CONSTEXPR auto next(Cur & pos)
            RANGES_DECLTYPE_AUTO_RETURN
            (
                pos.next()
            )
            template<typename Cur, typename O>
            static RANGES_CXX14_CONSTEXPR auto equal(Cur const &pos, O const &other)
            RANGES_DECLTYPE_AUTO_RETURN
            (
                pos.equal(other)
            )
            template<typename Cur>
            static RANGES_CXX14_CONSTEXPR auto prev(Cur & pos)
            RANGES_DECLTYPE_AUTO_RETURN
            (
                pos.prev()
            )
            template<typename Cur, typename D>
            static RANGES_CXX14_CONSTEXPR auto advance(Cur & pos, D n)
            RANGES_DECLTYPE_AUTO_RETURN
            (
                pos.advance(n)
            )
            template<typename Cur, typename O>
            static RANGES_CXX14_CONSTEXPR auto distance_to(Cur const &pos, O const &other)
            RANGES_DECLTYPE_AUTO_RETURN
            (
                pos.distance_to(other)
            )

        private:
            template<typename Cur>
            using sized_cursor_difference_t =
                decltype(range_access::distance_to(std::declval<Cur>(), std::declval<Cur>()));

            template<typename T>
            static std::ptrdiff_t cursor_difference_2_(detail::any);
            template<typename T>
            static sized_cursor_difference_t<T> cursor_difference_2_(long);
            template<typename T>
            static typename T::difference_type cursor_difference_2_(int);

            template<typename Cur>
            struct cursor_difference
            {
                using type = decltype(range_access::cursor_difference_2_<Cur>(42));
            };

            template<typename T>
            using cursor_reference_t = decltype(std::declval<T const &>().read());

            template<typename T>
            static meta::id<uncvref_t<cursor_reference_t<T>>> cursor_value_2_(long);
            template<typename T>
            static meta::id<typename T::value_type> cursor_value_2_(int);

            template<typename Cur>
            struct cursor_value
              : decltype(range_access::cursor_value_2_<Cur>(42))
            {};

        public:
            template<typename Cur>
            using cursor_difference_t = typename cursor_difference<Cur>::type;

            template<typename Cur>
            using cursor_value_t = typename cursor_value<Cur>::type;

            template<typename Cur>
            static RANGES_CXX14_CONSTEXPR Cur &pos(basic_iterator<Cur> &it) noexcept
            {
                return it.pos();
            }
            template<typename Cur>
            static constexpr Cur const &pos(basic_iterator<Cur> const &it) noexcept
            {
                return it.pos();
            }
            template<typename Cur>
            static RANGES_CXX14_CONSTEXPR Cur &&pos(basic_iterator<Cur> &&it) noexcept
            {
                return detail::move(it.pos());
            }

            template<typename Cur>
            static RANGES_CXX14_CONSTEXPR Cur cursor(basic_iterator<Cur> it)
            {
                return std::move(it.pos());
            }
            /// endcond
        };
        /// @}

        /// \cond
        namespace detail
        {
            template<typename T>
            using Cursor =
                concepts::models<range_access::Cursor, T>;

            template<typename S, typename C>
            using CursorSentinel =
                concepts::models<range_access::CursorSentinel, S, C>;

            template<typename T>
            using ReadableCursor =
                concepts::models<range_access::ReadableCursor, T>;

            template<typename T, typename U>
            using WritableCursor =
                concepts::models<range_access::WritableCursor, T, U>;

            template<typename T>
            using HasCursorNext =
                concepts::models<range_access::HasCursorNext, T>;

            template<typename T>
            using HasCursorArrow =
                concepts::models<range_access::HasCursorArrow, T>;

            template<typename S, typename C>
            using SizedCursorSentinel =
                concepts::models<range_access::SizedCursorSentinel, S, C>;

            template<typename T, typename U>
            using OutputCursor =
                concepts::models<range_access::OutputCursor, T, U>;

            template<typename T>
            using InputCursor =
                concepts::models<range_access::InputCursor, T>;

            template<typename T>
            using ForwardCursor =
                concepts::models<range_access::ForwardCursor, T>;

            template<typename T>
            using BidirectionalCursor =
                concepts::models<range_access::BidirectionalCursor, T>;

            template<typename T>
            using RandomAccessCursor =
                concepts::models<range_access::RandomAccessCursor, T>;

            template<typename T>
            using InfiniteCursor =
                concepts::models<range_access::InfiniteCursor, T>;

            template<typename T>
            using cursor_concept =
                concepts::most_refined<
                    meta::list<
                        range_access::RandomAccessCursor,
                        range_access::BidirectionalCursor,
                        range_access::ForwardCursor,
                        range_access::InputCursor,
                        range_access::Cursor>, T>;

            template<typename T>
            using cursor_concept_t = meta::_t<cursor_concept<T>>;

            template<typename Cur, bool Readable = (bool) ReadableCursor<Cur>()>
            struct is_writable_cursor_
              : std::true_type
            {};

            template<typename Cur>
            struct is_writable_cursor_<Cur, true>
              : WritableCursor<Cur, range_access::cursor_value_t<Cur>>
            {};

            template<typename Cur>
            struct is_writable_cursor
              : detail::is_writable_cursor_<Cur>
            {};
        }
        /// \endcond
    }
}

#endif


text:
package command

import (
	"github.com/codegangsta/cli"
	"github.com/denkhaus/cloudia/engine"
)

//provision will use specified Dockerfiles to build all the containers, or the specified one(s).
//If no Dockerfile is given, it will pull the image(s) from the given registry.
func (c *Commander) NewProvisionCommand() {
	c.Register(cli.Command{
		Name:  "provision",
		Usage: "Build or pull images",
		Flags: []cli.Flag{
			cli.BoolFlag{"force, f", "rebuild all images"},
		},
		Action: func(ctx *cli.Context) {
			c.Execute(func(node engine.Node) error {
				return node.Provision(ctx.Bool("force"))
			}, ctx)
		},
	})
}


text:
<?php

namespace Cosa\UserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;

class SecurityController extends Controller
{

    public function testAction()
    {
        $user = $this->get('security.context')->getToken()->getUser();
        var_dump($user);
        exit();

    }
}


text:
// Copyright 2017 The Bazel Authors. 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 com.google.devtools.build.lib.rules.android;

import com.google.devtools.build.lib.analysis.TransitiveInfoProvider;
import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable;

/** Supplies the device broker type string, passed to the android_test runtime. */
@Immutable
public final class DeviceBrokerTypeProvider implements TransitiveInfoProvider {

  private final String deviceBrokerType;

  public DeviceBrokerTypeProvider(String deviceBrokerType) {
    this.deviceBrokerType = deviceBrokerType;
  }

  /**
   * Returns the type of device broker that is appropriate to use to interact with
   * devices obtained by this artifact.
   */
  public String getDeviceBrokerType() {
    return deviceBrokerType;
  }
}


text:
require 'test_helper'

class InvoiceTest < ActiveSupport::TestCase
  fixtures :all

  it "should not be valid without project" do
    invoice = Invoice.new(customer_id: "foo", project_id: nil)
    assert !invoice.valid?, "#{invoice.inspect} should be invalid"
  end

  test "should not be valid without date" do
    invoice = Invoice.new(date: nil)
    assert !invoice.valid?, "#{invoice.inspect} should be invalid"
  end

  it "should not be valid without customer" do
    invoice = Invoice.new(customer_id: nil)
    assert !invoice.valid?, "#{invoice.inspect} should be invalid"
  end

  it "should create invoice if date and valid project present" do
    Timecop.freeze "2014-01-01" do
      project = projects :narendra3
      invoice = Invoice.new(project_id: project.id, date: Time.zone.now)
      assert invoice.valid?, "#{invoice.inspect} should be valid"
    end
  end

  it "should have a unique ref scoped by account"

  it "before_create set_ref"

  it "before_save set_rate"

  it "before_save set_value"

  it "should only set set_payment_due_date if payment_due_date empty"

  it "should respond to defined associations" do
    invoice = Invoice.new
    assert_respond_to invoice, :account
    assert_respond_to invoice, :customer
    assert_respond_to invoice, :project
    assert_respond_to invoice, :positions
  end
end


text:
using EPiServer.Commerce.Order;
using EPiServer.Reference.Commerce.Site.Features.AddressBook.Pages;
using EPiServer.Reference.Commerce.Site.Features.AddressBook.ViewModels;
using EPiServer.Reference.Commerce.Site.Features.Cart.ViewModels;
using EPiServer.Reference.Commerce.Site.Features.Shared.Models;
using EPiServer.Reference.Commerce.Site.Features.Shared.ViewModels;
using EPiServer.Reference.Commerce.Site.Infrastructure.Facades;
using EPiServer.ServiceLocation;
using Mediachase.BusinessFoundation.Data;
using Mediachase.Commerce.Customers;
using Mediachase.Commerce.Orders.Dto;
using System;
using System.Collections.Generic;
using System.Linq;

namespace EPiServer.Reference.Commerce.Site.Features.AddressBook.Services
{
    [ServiceConfiguration(typeof(IAddressBookService), Lifecycle = ServiceInstanceScope.Singleton)]
    public class AddressBookService : IAddressBookService
    {
        private readonly CustomerContextFacade _customerContext;
        private readonly CountryManagerFacade _countryManager;
        private readonly IOrderGroupFactory _orderGroupFactory;

        public AddressBookService(
            CustomerContextFacade customerContext,
            CountryManagerFacade countryManager,
            IOrderGroupFactory orderGroupFactory)
        {
            _customerContext = customerContext;
            _countryManager = countryManager;
            _orderGroupFactory = orderGroupFactory;
        }

        public void MapToModel(CustomerAddress customerAddress, AddressModel addressModel)
        {
            addressModel.Line1 = customerAddress.Line1;
            addressModel.Line2 = customerAddress.Line2;
            addressModel.City = customerAddress.City;
            addressModel.CountryName = customerAddress.CountryName;
            addressModel.CountryCode = customerAddress.CountryCode;
            addressModel.Email = customerAddress.Email;
            addressModel.FirstName = customerAddress.FirstName;
            addressModel.LastName = customerAddress.LastName;
            addressModel.PostalCode = customerAddress.PostalCode;
            addressModel.CountryRegion = new CountryRegionViewModel
            {
                Region = customerAddress.RegionName ?? customerAddress.RegionCode ?? customerAddress.State
            };
            addressModel.ShippingDefault = _customerContext.CurrentContact.PreferredShippingAddress != null
                                                && customerAddress.Name == _customerContext.CurrentContact.PreferredShippingAddress.Name;
            addressModel.BillingDefault = _customerContext.CurrentContact.PreferredBillingAddress != null
                                                && customerAddress.Name == _customerContext.CurrentContact.PreferredBillingAddress.Name;
            addressModel.AddressId = customerAddress.Name;
            addressModel.Name = customerAddress.Name;
            addressModel.DaytimePhoneNumber = customerAddress.DaytimePhoneNumber;
        }

        public void MapToModel(IOrderAddress orderAddress, AddressModel addressModel)
        {
            addressModel.AddressId = orderAddress.Id;
            addressModel.Name = orderAddress.Id;
            addressModel.Line1 = orderAddress.Line1;
            addressModel.Line2 = orderAddress.Line2;
            addressModel.City = orderAddress.City;
            addressModel.CountryName = orderAddress.CountryName;
            addressModel.CountryCode = orderAddress.CountryCode;
            addressModel.Email = orderAddress.Email;
            addressModel.FirstName = orderAddress.FirstName;
            addressModel.LastName = orderAddress.LastName;
            addressModel.PostalCode = orderAddress.PostalCode;
            addressModel.CountryRegion = new CountryRegionViewModel
            {
                Region = orderAddress.RegionName ?? orderAddress.RegionCode
            };
            addressModel.DaytimePhoneNumber = orderAddress.DaytimePhoneNumber;
        }

        public void MapToAddress(AddressModel addressModel, IOrderAddress orderAddress)
        {
            orderAddress.Id = addressModel.Name;
            orderAddress.City = addressModel.City;
            orderAddress.CountryCode = addressModel.CountryCode;
            orderAddress.CountryName = _countryManager.GetCountries().Country.Where(x => x.Code == addressModel.CountryCode).Select(x => x.Name).FirstOrDefault();
            orderAddress.FirstName = addressModel.FirstName;
            orderAddress.LastName = addressModel.LastName;
            orderAddress.Line1 = addressModel.Line1;
            orderAddress.Line2 = addressModel.Line2;
            orderAddress.DaytimePhoneNumber = addressModel.DaytimePhoneNumber;
            orderAddress.PostalCode = addressModel.PostalCode;
            orderAddress.RegionName = addressModel.CountryRegion.Region;
            orderAddress.RegionCode = addressModel.CountryRegion.Region;
            orderAddress.Email = addressModel.Email;
            orderAddress.Organization = addressModel.Organization;
        }

        public void MapToAddress(AddressModel addressModel, CustomerAddress customerAddress)
        {
            customerAddress.Name = addressModel.Name;
            customerAddress.City = addressModel.City;
            customerAddress.CountryCode = addressModel.CountryCode;
            customerAddress.CountryName = _countryManager.GetCountries().Country.Where(x => x.Code == addressModel.CountryCode).Select(x => x.Name).FirstOrDefault();
            customerAddress.FirstName = addressModel.FirstName;
            customerAddress.LastName = addressModel.LastName;
            customerAddress.Line1 = addressModel.Line1;
            customerAddress.Line2 = addressModel.Line2;
            customerAddress.DaytimePhoneNumber = addressModel.DaytimePhoneNumber;
            customerAddress.PostalCode = addressModel.PostalCode;
            customerAddress.RegionName = addressModel.CountryRegion.Region;
            customerAddress.RegionCode = addressModel.CountryRegion.Region;
            // Commerce Manager expects State to be set for addresses in order management. Set it to be same as
            // RegionName to avoid issues.
            customerAddress.State = addressModel.CountryRegion.Region;
            customerAddress.Email = addressModel.Email;
            customerAddress.AddressType =
                CustomerAddressTypeEnum.Public |
                (addressModel.ShippingDefault ? CustomerAddressTypeEnum.Shipping : 0) |
                (addressModel.BillingDefault ? CustomerAddressTypeEnum.Billing : 0);
        }

        public IOrderAddress ConvertToAddress(AddressModel model, IOrderGroup orderGroup)
        {
            var address = orderGroup.CreateOrderAddress(_orderGroupFactory);
            address.Id = model.Name;
            MapToAddress(model, address);

            return address;
        }

        public AddressModel ConvertToModel(IOrderAddress orderAddress)
        {
            var address = new AddressModel();

            if (orderAddress != null)
            {
                MapToModel(orderAddress, address);
            }

            return address;
        }

        public IList<AddressModel> MergeAnonymousShippingAddresses(IList<AddressModel> addresses, IEnumerable<CartItemViewModel> cartItems)
        {
            var mergedAddresses = new List<AddressModel>(addresses);

            for (int index = addresses.Count - 1; index >= 0; index--)
            {
                var currentAddress = addresses[index];

                foreach (var address in mergedAddresses.Where(x => x != currentAddress))
                {
                    if (address.FirstName == currentAddress.FirstName &&
                        address.LastName == currentAddress.LastName &&
                        address.Line1 == currentAddress.Line1 &&
                        address.Line2 == currentAddress.Line2 &&
                        address.Organization == currentAddress.Organization &&
                        address.PostalCode == currentAddress.PostalCode &&
                        address.City == currentAddress.City &&
                        address.CountryCode == currentAddress.CountryCode &&
                        address.CountryRegion.Region == currentAddress.CountryRegion.Region)
                    {
                        foreach (var item in cartItems.Where(x => x.AddressId == currentAddress.AddressId))
                        {
                            item.AddressId = address.AddressId;
                        }

                        mergedAddresses.Remove(currentAddress);
                        break;
                    }
                }
            }

            return mergedAddresses;
        }

        public AddressCollectionViewModel GetAddressBookViewModel(AddressBookPage addressBookPage)
        {
            var model = new AddressCollectionViewModel
            {
                CurrentPage = addressBookPage,
                Addresses = _customerContext.CurrentContact.ContactAddresses.Select(ConvertAddress)
            };
            return model;
        }

        public bool CanSave(AddressModel addressModel)
        {
            return !_customerContext.CurrentContact.ContactAddresses.Any(x =>
                x.Name.Equals(addressModel.Name, StringComparison.InvariantCultureIgnoreCase) &&
                x.Name != addressModel.AddressId);
        }

        public void Save(AddressModel addressModel)
        {
            var currentContact = _customerContext.CurrentContact;
            var customerAddress = CreateOrUpdateCustomerAddress(currentContact, addressModel);

            if (addressModel.BillingDefault)
            {
                currentContact.PreferredBillingAddress = customerAddress;
            }
            else if (currentContact.PreferredBillingAddress != null && currentContact.PreferredBillingAddress.Name.Equals(addressModel.AddressId))
            {
                currentContact.PreferredBillingAddressId = null;
            }

            if (addressModel.ShippingDefault)
            {
                currentContact.PreferredShippingAddress = customerAddress;
            }
            else if (currentContact.PreferredShippingAddress != null && currentContact.PreferredShippingAddress.Name.Equals(addressModel.AddressId))
            {
                currentContact.PreferredShippingAddressId = null;
            }

            currentContact.SaveChanges();
        }

        public void Delete(string addressId)
        {
            var currentContact = _customerContext.CurrentContact;
            var customerAddress = GetAddress(currentContact, addressId);
            if (customerAddress == null)
            {
                return;
            }
            if (currentContact.PreferredBillingAddressId == customerAddress.PrimaryKeyId || currentContact.PreferredShippingAddressId == customerAddress.PrimaryKeyId)
            {
                currentContact.PreferredBillingAddressId = currentContact.PreferredBillingAddressId == customerAddress.PrimaryKeyId ? null : currentContact.PreferredBillingAddressId;
                currentContact.PreferredShippingAddressId = currentContact.PreferredShippingAddressId == customerAddress.PrimaryKeyId ? null : currentContact.PreferredShippingAddressId;
                currentContact.SaveChanges();
            }
            currentContact.DeleteContactAddress(customerAddress);
            currentContact.SaveChanges();
        }

        public void SetPreferredBillingAddress(string addressId)
        {
            var currentContact = _customerContext.CurrentContact;
            var customerAddress = GetAddress(currentContact, addressId);
            if (customerAddress == null)
            {
                return;
            }
            currentContact.PreferredBillingAddress = customerAddress;
            currentContact.SaveChanges();
        }

        public void SetPreferredShippingAddress(string addressId)
        {
            var currentContact = _customerContext.CurrentContact;
            var customerAddress = GetAddress(currentContact, addressId);
            if (customerAddress == null)
            {
                return;
            }
            currentContact.PreferredShippingAddress = customerAddress;
            currentContact.SaveChanges();
        }

        public CustomerAddress GetPreferredBillingAddress()
        {
            return _customerContext.CurrentContact.CurrentContact != null ?
                _customerContext.CurrentContact.CurrentContact.PreferredBillingAddress
                : null;
        }

        public void LoadAddress(AddressModel addressModel)
        {
            var currentContact = _customerContext.CurrentContact;

            addressModel.CountryOptions = GetAllCountries();

            if (addressModel.CountryCode == null && addressModel.CountryOptions.Any())
            {
                addressModel.CountryCode = addressModel.CountryOptions.First().Code;
            }

            if (!string.IsNullOrEmpty(addressModel.AddressId))
            {
                var existingCustomerAddress = GetAddress(currentContact, addressModel.AddressId);

                if (existingCustomerAddress != null)
                {
                    MapToModel(existingCustomerAddress, addressModel);
                }
            }

            if (!string.IsNullOrEmpty(addressModel.CountryCode))
            {
                if (addressModel.CountryRegion == null)
                {
                    addressModel.CountryRegion = new CountryRegionViewModel();
                }
                addressModel.CountryRegion.RegionOptions = GetRegionsByCountryCode(addressModel.CountryCode);
            }
        }

        public IList<AddressModel> List()
        {
            var currentContact = _customerContext.CurrentContact;
            var addresses = new List<AddressModel>();

            if (currentContact != null)
            {
                addresses.AddRange(currentContact.ContactAddresses.Select(customerAddress => new AddressModel
                {
                    AddressId = customerAddress.Name,
                    Name = customerAddress.Name,
                    FirstName = customerAddress.FirstName,
                    LastName = customerAddress.LastName,
                    Line1 = customerAddress.Line1,
                    Line2 = customerAddress.Line2,
                    PostalCode = customerAddress.PostalCode,
                    City = customerAddress.City,
                    CountryCode = customerAddress.CountryCode,
                    CountryName = customerAddress.CountryName,
                    CountryRegion = new CountryRegionViewModel()
                    {
                        Region = customerAddress.RegionName ?? customerAddress.RegionCode ?? customerAddress.State
                    },
                    Email = customerAddress.Email,
                    ShippingDefault = _customerContext.CurrentContact.PreferredShippingAddress != null
                                            && customerAddress.AddressId == _customerContext.CurrentContact.PreferredShippingAddressId,
                    BillingDefault = _customerContext.CurrentContact.PreferredBillingAddress != null
                                            && customerAddress.AddressId == _customerContext.CurrentContact.PreferredBillingAddressId
                }));
            }

            return addresses;
        }

        public IEnumerable<string> GetRegionsByCountryCode(string countryCode)
        {
            var country = _countryManager.GetCountryByCountryCode(countryCode);
            return country != null ? GetRegionsForCountry(country) : Enumerable.Empty<string>();
        }

        public void LoadCountriesAndRegionsForAddress(AddressModel addressModel)
        {
            addressModel.CountryOptions = GetAllCountries();

            // Try get the address country first by country code, then by name, else use the first in list as final fallback.
            var selectedCountry = (GetCountryByCode(addressModel) ??
                                   GetCountryByName(addressModel)) ??
                                   addressModel.CountryOptions.FirstOrDefault();

            addressModel.CountryRegion.RegionOptions = selectedCountry != null ?
                GetRegionsByCountryCode(selectedCountry.Code) :
                Enumerable.Empty<string>();
        }

        public bool UseBillingAddressForShipment()
        {
            var customer = _customerContext.CurrentContact.CurrentContact;
            return customer == null ||
                   (customer.PreferredShippingAddressId.HasValue &&
                    customer.PreferredShippingAddressId == customer.PreferredBillingAddressId);
        }

        private CountryViewModel GetCountryByCode(AddressModel addressModel)
        {
            var selectedCountry = addressModel.CountryOptions.FirstOrDefault(x => x.Code == addressModel.CountryCode);
            if (selectedCountry != null)
            {
                addressModel.CountryName = selectedCountry.Name;
            }
            return selectedCountry;
        }

        private CountryViewModel GetCountryByName(AddressModel addressModel)
        {
            var selectedCountry = addressModel.CountryOptions.FirstOrDefault(x => x.Name == addressModel.CountryName);
            if (selectedCountry != null)
            {
                addressModel.CountryCode = selectedCountry.Code;
            }
            return selectedCountry;
        }

        private IEnumerable<string> GetRegionsForCountry(CountryDto.CountryRow country)
        {
            return country == null ? Enumerable.Empty<string>() : country.GetStateProvinceRows().Select(x => x.Name).ToList();
        }

        private CustomerAddress CreateOrUpdateCustomerAddress(CurrentContactFacade contact, AddressModel addressModel)
        {

            var customerAddress = GetAddress(contact, addressModel.AddressId);
            var isNew = customerAddress == null;
            IEnumerable<PrimaryKeyId> existingId = contact.ContactAddresses.Select(a => a.AddressId).ToList();
            if (isNew)
            {
                customerAddress = CustomerAddress.CreateInstance();
            }

            MapToAddress(addressModel, customerAddress);

            if (isNew)
            {
                contact.AddContactAddress(customerAddress);
            }
            else
            {
                contact.UpdateContactAddress(customerAddress);
            }

            contact.SaveChanges();
            if (isNew)
            {
                customerAddress.AddressId = contact.ContactAddresses
                    .Where(a => !existingId.Contains(a.AddressId))
                    .Select(a => a.AddressId)
                    .Single();
                addressModel.AddressId = customerAddress.Name;
            }
            return customerAddress;
        }

        private AddressModel ConvertAddress(CustomerAddress customerAddress)
        {
            AddressModel addressModel = null;

            if (customerAddress != null)
            {
                addressModel = new AddressModel();
                MapToModel(customerAddress, addressModel);
            }

            return addressModel;
        }

        private CustomerAddress GetAddress(CurrentContactFacade contact, string addressId)
        {
            return contact.ContactAddresses.FirstOrDefault(x => x.Name == addressId);
        }

        private IEnumerable<CountryViewModel> GetAllCountries()
        {
            return _countryManager.GetCountries().Country.Select(x => new CountryViewModel { Code = x.Code, Name = x.Name });
        }
    }
}


text:
<?php

class Google_Service_Dialogflow_GoogleCloudDialogflowV2IntentMessageCarouselSelect extends Google_Collection
{
  protected $collection_key = 'items';
  protected $itemsType = 'Google_Service_Dialogflow_GoogleCloudDialogflowV2IntentMessageCarouselSelectItem';
  protected $itemsDataType = 'array';

  /**
   * @param Google_Service_Dialogflow_GoogleCloudDialogflowV2IntentMessageCarouselSelectItem[]
   */
  public function setItems($items)
  {
    $this->items = $items;
  }
  /**
   * @return Google_Service_Dialogflow_GoogleCloudDialogflowV2IntentMessageCarouselSelectItem[]
   */
  public function getItems()
  {
    return $this->items;
  }
}


text:
The treasure of your life

Lorem ipsum dolor sit amet, consectetur adipisicing elit,

Products

Filter By

 Selected Category: {{ catName }}

{{category.name}}

Price

            <input type="range" name="range" ng-model="priceValue" min="{{min}}"  max="{{max}}" ng-change="sortPriceFilter(priceValue)">

{{min | currency}}

{{priceValue | currency}}

{{max | currency}}

                  Sort By:
                  <select ng-model="sort" class="" ng-change="sortProduct(sort)">
                      <option value="">Select</option>
                      <option value="new">Newest</option>
                      <option value="low">Price Low to High</option>
                      <option value="high">Price High to Low</option>

                 </select>

No products found.


text:
By downloading this font package you agree to the following terms of use:

    - This FONT PACKAGE is freeware.

    -   This FONT PACKAGE may be distributed ONLY via the Internet for FREE.
        Under NO circumstances may this FONT PACKAGE be sold for a profit nor be
        included as part of another product or CD-ROM compilation. If you wish
        to include this FONT PACKAGE for FREE distribution on your Web Site,
        please  include all of the fonts and original documentation supplied
        with this FONT PACKAGE.

    -   You may install and use this FONT PACKAGE on an unlimited amount of
        machines.

    -   You may NOT rename, edit, or create any alternate variations of the
        fonts included in this FONT PACKAGE.

    -   This FONT PACKAGE comes "as is" with NO warranty whatsoever. SHYFONTS
        accepts NO responsibility for any damages or loss of any kind due to the
        use of this FONT PACKAGE. The use of this FONT PACKAGE is solely your
        responsibility -- you use this FONT PACKAGE at your own risk.

    -   Enjoy the fonts!

If you have any question regarding this document or the usage of this font pack-
age, feel free to contact us at info@shyfonts.com. Thank you for downloading
this font package and enjoy!

---
© 2001 ShyFonts Type Foundry – http://www.shyfonts.com


text:
var express = require('express');
var router = express.Router();
//Importando o modelo do usuario
var User = require('../business/model/user')

//Importando controller do usuario
var LoginController = require('../business/control/loginController')

var controller = new LoginController();

router.get('/', (req, res, next) => {
  res.render('login', { title: 'Authentication | API' });
});

router.post('/', (req, res, next) => {
  var new_user = new User(req.body.login, req.body.password);

  try {
    controller.singIn(new_user);
    res.redirect('/dashboard');
  } catch (error) {
    res.render('login', { flash: { type: 'alert-danger', msg: error.message } });
  }

});
module.exports = router;


text:
(english translation below)

N.B: Vanaf versie 1.3 moeten de ingelezen csv een puntkomma (;) als scheidingsteken hebben. In vorige versies was dit een komma (,).

Dit is een maven plugin om een set aan util/helper klassen te maken op basis van de DUO vakkentabel (http://www.duo.nl/zakelijk/klantenservice/softwareleveranciers/Programmas_van_eisen.asp). Deze klassen bevatten methoden als `public static boolean isBeroepsgerichtVak(int opleidingIlt, int vakIlt)`.

De plugin is gebouwd voor Maven3 en geschikt voor zowel commandline uitvoer als m2e.

Zie hieronder wat je moet toevoegen in je pom.xml om deze plugin te gebruiken

Releasen
=========

* mvn release:prepare
* mvn release:perform

# English translation

This is a maven plugin to convert Dutch educational information from DUO to util classes which answer such questions as whether or not a subject is required for a specific curriculum.

It probably won't be of use for non-Dutch except as an example of how to create a source-generating maven plugin. This plugin should work from the commandline as well as integrate with m2e. See below for how to configure your pom to use this plugin.

# Example usage (pom.xml)

```
<build>
  <pluginManagement>
    <plugins>
      <plugin>
        <groupId>nl.topicus.onderwijs.vakkentabel</groupId>
        <artifactId>vakkentabel-maven-plugin</artifactId>
        <version>0.9-SNAPSHOT</version>
        <executions>
          <execution>
            <id>vakkentabel</id>
            <goals>
              <goal>generate</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <vakkentabel>src/main/resources/vakkentabel.csv</vakkentabel>
          <packagePrefix>org.example.util.vakkentabel</packagePrefix>
          <matcherClass>org.example.VakMatcher</matcherClass>
          <matcherFactory>org.example.MatcherFactory</matcherFactory>
          <outputDirectory>${project.build.directory}/generated-sources/vakkentabel</outputDirectory>
        </configuration>
      </plugin>
    </plugins>
  </pluginManagement>
</build>

<profiles>
	<profile>
		<id>codegen</id>
		<build>
			<plugins>
				<plugin>
					<groupId>nl.topicus.onderwijs.vakkentabel</groupId>
					<artifactId>vakkentabel-maven-plugin</artifactId>
				</plugin>
			</plugins>
	</build>
</profile>
```


text:
ALTER TABLE tblRegoFormRulesAdded
    ADD COLUMN ynVolunteer CHAR(1) NOT NULL DEFAULT 'N' AFTER ynMisc,
    DROP COLUMN intAssocID,
    DROP COLUMN intClubID
;


text:
<?php

namespace TheCodeEngine\Pipeline;

/**
 * Command from the Command Pipeline
 *
 * Running a logical command and get the $data from the task
 *
 * @package TheCodeEngine\Pipeline
 */
use Exception;

/**
 * Class Command
 *
 * validate() --> run()
 *
 * @package TheCodeEngine\Pipeline
 */
class Command
{
    /**
     * @var Pipeline
     */
    protected $command_pipeline;

    /**
     * Data thats returned from the pipeline
     * @var mixed
     */
    protected $data;

    /**
     * @var bool is command running
     */
    public $is_runned = false;
    /**
     * @var bool is command successful running
     */
    public $is_success = false;
    /**
     * @var bool is command running with error
     */
    public $is_failed = false;
    /**
     * @var bool is command has exec the undo action
     */
    public $is_undo_run = false;

    /**
     * @var Exception|null exception for the exec
     */
    public $exec_exception;

    /**
     * Create A Command from Class string
     * @param string|object $class_name Object only for test purpose
     * @param Pipeline $pipeline
     * @param $input_data
     * @return mixed
     */
    public static function createFromClassName($class_name, $pipeline, $input_data)
    {
        if (is_object($class_name)) {
            return $class_name;
        }
        return new $class_name($pipeline, $input_data);
    }

    /**
     * Command constructor.
     * @param $command_pipeline
     */
    public function __construct($command_pipeline, $input_data=[])
    {
        $this->command_pipeline = $command_pipeline;
    }

    /**
     * validate if the Command can run with the given Data
     * @return array [Boolean can_run, array of errormessages]
     */
    public function is_valid()
    {
        return [true, []];
    }

    /**
     * Run the Commands
     * @return bool
     */
    public function run()
    {
        $this->is_runned = true;
        $this->is_valid();
        return true;
    }

    /**
     * Run when the Command is failing
     *
     * Undo only things thats not done in the database the Pipline has make a transaction !
     *
     * @return bool
     */
    public function undo_run()
    {
        $this->is_undo_run = true;
        return true;
    }

    /**
     * Run when failed
     */
    public function failed()
    {
        $this->is_failed = true;
    }

    /**
     * Run when success
     */
    public function success()
    {
        $this->is_success = true;
    }

    /**
     * Return the next Command class with and his $input_data
     * @return array
     */
    public function nextTaskSuccess()
    {
        return [null, []];
    }

    /**
     * * Return the next Command class with and his $input_data
     * @return array
     */
    public function nextTaskfailed()
    {
        return [null, []];
    }

    /**
     * Exec Command
     * @return array [returnvalue, $new_class, $input_data]
     */
    public function exec()
    {
        $new_class = null;
        $input_data = [];
        $rv = false;
        try {
            $rv = $this->run();
            if ($rv === false) {
                $this->failed();
                $this->undo_run();
                list($new_class, $input_data) = $this->nextTaskfailed();
            } else {
                $this->success();
                list($new_class, $input_data) = $this->nextTaskSuccess();
            }
        } catch (Exception $e) {
            $this->exec_exception = $e;
            $this->failed();
            $this->undo_run();
            list($new_class, $input_data) = $this->nextTaskfailed();
        }

        return [$rv, $new_class, $input_data];
    }

    /**
     * Return if the command is runned
     * @return boolean
     */
    public function isRunned()
    {
        return $this->is_runned;
    }

    /**
     * Return ig the command has runned the undo action
     * @return boolean
     */
    public function isUndoRun()
    {
        return $this->is_undo_run;
    }

    public function getExecException()
    {
        return $this->exec_exception;
    }
}


text:
/* tasn_utl.c */
/* Written by Dr Stephen N Henson (shenson@bigfoot.com) for the OpenSSL
 * project 2000.
 */
/* ====================================================================
 * Copyright (c) 2000-2004 The OpenSSL Project.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. All advertising materials mentioning features or use of this
 *    software must display the following acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
 *
 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission. For written permission, please contact
 *    licensing@OpenSSL.org.
 *
 * 5. Products derived from this software may not be called "OpenSSL"
 *    nor may "OpenSSL" appear in their names without prior written
 *    permission of the OpenSSL Project.
 *
 * 6. Redistributions of any form whatsoever must retain the following
 *    acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
 *
 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 * ====================================================================
 *
 * This product includes cryptographic software written by Eric Young
 * (eay@cryptsoft.com).  This product includes software written by Tim
 * Hudson (tjh@cryptsoft.com).
 *
 */

#include <stddef.h>
#include <string.h>
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/objects.h>
#include <openssl/err.h>

/* Utility functions for manipulating fields and offsets */

/* Add 'offset' to 'addr' */
#define offset2ptr(addr, offset) (void *)(((char *) addr) + offset)

/* Given an ASN1_ITEM CHOICE type return
 * the selector value
 */

int asn1_get_choice_selector(ASN1_VALUE **pval, const ASN1_ITEM *it)
	{
	int *sel = offset2ptr(*pval, it->utype);
	return *sel;
	}

/* Given an ASN1_ITEM CHOICE type set
 * the selector value, return old value.
 */

int asn1_set_choice_selector(ASN1_VALUE **pval, int value, const ASN1_ITEM *it)
	{
	int *sel, ret;
	sel = offset2ptr(*pval, it->utype);
	ret = *sel;
	*sel = value;
	return ret;
	}

/* Do reference counting. The value 'op' decides what to do.
 * if it is +1 then the count is incremented. If op is 0 count is
 * set to 1. If op is -1 count is decremented and the return value
 * is the current refrence count or 0 if no reference count exists.
 */

int asn1_do_lock(ASN1_VALUE **pval, int op, const ASN1_ITEM *it)
	{
	const ASN1_AUX *aux;
	int *lck, ret;
	if ((it->itype != ASN1_ITYPE_SEQUENCE)
	   && (it->itype != ASN1_ITYPE_NDEF_SEQUENCE))
		return 0;
	aux = it->funcs;
	if (!aux || !(aux->flags & ASN1_AFLG_REFCOUNT))
		return 0;
	lck = offset2ptr(*pval, aux->ref_offset);
	if (op == 0)
		{
		*lck = 1;
		return 1;
		}
	ret = CRYPTO_add(lck, op, aux->ref_lock);
#ifdef REF_PRINT
	fprintf(stderr, "%s: Reference Count: %d\n", it->sname, *lck);
#endif
#ifdef REF_CHECK
	if (ret < 0)
		fprintf(stderr, "%s, bad reference count\n", it->sname);
#endif
	return ret;
	}

static ASN1_ENCODING *asn1_get_enc_ptr(ASN1_VALUE **pval, const ASN1_ITEM *it)
	{
	const ASN1_AUX *aux;
	if (!pval || !*pval)
		return NULL;
	aux = it->funcs;
	if (!aux || !(aux->flags & ASN1_AFLG_ENCODING))
		return NULL;
	return offset2ptr(*pval, aux->enc_offset);
	}

void asn1_enc_init(ASN1_VALUE **pval, const ASN1_ITEM *it)
	{
	ASN1_ENCODING *enc;
	enc = asn1_get_enc_ptr(pval, it);
	if (enc)
		{
		enc->enc = NULL;
		enc->len = 0;
		enc->modified = 1;
		}
	}

void asn1_enc_free(ASN1_VALUE **pval, const ASN1_ITEM *it)
	{
	ASN1_ENCODING *enc;
	enc = asn1_get_enc_ptr(pval, it);
	if (enc)
		{
		if (enc->enc)
			OPENSSL_free(enc->enc);
		enc->enc = NULL;
		enc->len = 0;
		enc->modified = 1;
		}
	}

int asn1_enc_save(ASN1_VALUE **pval, const unsigned char *in, int inlen,
							 const ASN1_ITEM *it)
	{
	ASN1_ENCODING *enc;
	enc = asn1_get_enc_ptr(pval, it);
	if (!enc)
		return 1;

	if (enc->enc)
		OPENSSL_free(enc->enc);
	enc->enc = OPENSSL_malloc(inlen);
	if (!enc->enc)
		return 0;
	memcpy(enc->enc, in, inlen);
	enc->len = inlen;
	enc->modified = 0;

	return 1;
	}

int asn1_enc_restore(int *len, unsigned char **out, ASN1_VALUE **pval,
							const ASN1_ITEM *it)
	{
	ASN1_ENCODING *enc;
	enc = asn1_get_enc_ptr(pval, it);
	if (!enc || enc->modified)
		return 0;
	if (out)
		{
		memcpy(*out, enc->enc, enc->len);
		*out += enc->len;
		}
	if (len)
		*len = enc->len;
	return 1;
	}

/* Given an ASN1_TEMPLATE get a pointer to a field */
ASN1_VALUE ** asn1_get_field_ptr(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt)
	{
	ASN1_VALUE **pvaltmp;
	if (tt->flags & ASN1_TFLG_COMBINE)
		return pval;
	pvaltmp = offset2ptr(*pval, tt->offset);
	/* NOTE for BOOLEAN types the field is just a plain
 	 * int so we can't return int **, so settle for
	 * (int *).
	 */
	return pvaltmp;
	}

/* Handle ANY DEFINED BY template, find the selector, look up
 * the relevant ASN1_TEMPLATE in the table and return it.
 */

const ASN1_TEMPLATE *asn1_do_adb(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt,
								int nullerr)
	{
	const ASN1_ADB *adb;
	const ASN1_ADB_TABLE *atbl;
	long selector;
	ASN1_VALUE **sfld;
	int i;
	if (!(tt->flags & ASN1_TFLG_ADB_MASK))
		return tt;

	/* Else ANY DEFINED BY ... get the table */
	adb = ASN1_ADB_ptr(tt->item);

	/* Get the selector field */
	sfld = offset2ptr(*pval, adb->offset);

	/* Check if NULL */
	if (!sfld)
		{
		if (!adb->null_tt)
			goto err;
		return adb->null_tt;
		}

	/* Convert type to a long:
	 * NB: don't check for NID_undef here because it
	 * might be a legitimate value in the table
	 */
	if (tt->flags & ASN1_TFLG_ADB_OID)
		selector = OBJ_obj2nid((ASN1_OBJECT *)*sfld);
	else
		selector = ASN1_INTEGER_get((ASN1_INTEGER *)*sfld);

	/* Try to find matching entry in table
	 * Maybe should check application types first to
	 * allow application override? Might also be useful
	 * to have a flag which indicates table is sorted and
	 * we can do a binary search. For now stick to a
	 * linear search.
	 */

	for (atbl = adb->tbl, i = 0; i < adb->tblcount; i++, atbl++)
		if (atbl->value == selector)
			return &atbl->tt;

	/* FIXME: need to search application table too */

	/* No match, return default type */
	if (!adb->default_tt)
		goto err;
	return adb->default_tt;

	err:
	/* FIXME: should log the value or OID of unsupported type */
	if (nullerr)
		ASN1err(ASN1_F_ASN1_DO_ADB,
			ASN1_R_UNSUPPORTED_ANY_DEFINED_BY_TYPE);
	return NULL;
	}


text:
package org.apache.commons.pool2;

import static org.junit.Assert.assertTrue;

import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.junit.Test;

/**
 * @version $Revision: 1537253 $
 */
public class TestBasePoolableObjectFactory {

    @Test
    public void testDefaultMethods() throws Exception {
        PooledObjectFactory<Object> factory = new TestFactory();

        factory.activateObject(null); // a no-op
        factory.passivateObject(null); // a no-op
        factory.destroyObject(null); // a no-op
        assertTrue(factory.validateObject(null)); // constant true
    }

    private static class TestFactory extends BasePooledObjectFactory<Object> {
        @Override
        public Object create() throws Exception {
            return null;
        }
        @Override
        public PooledObject<Object> wrap(Object value) {
            return new DefaultPooledObject<Object>(value);
        }
    }
}


text:
"""
A URI has the following form:
scheme:[//[user:password@]host[:port]][/]path[?query][#fragment]

This module handles the "path" part of a URI
Paths also appear in filesystem (obvs) so this module can handle those as well

UPaths are created by passing a pathname to the constructor:
E.g
    pwd = UPath(os.getcwd())

UPaths can be concatenated together using the '/' operator (__div__ method)
UPaths can also be concatenated with strings
E.g
>>> abso = UPath('/usr/lib')
>>> rel = UPath('python2.7/site-packages')
>>> abso / rel
UPath('/usr/lib/python2.7/site-packages')
>>> abso / "ruby/gems"
UPath('/usr/lib/ruby/gems')
>>> "~/local" / rel
UPath('~/local/python2.7/site-packages')

The dirname and basename can be extracted using slicing/subscription
E.g
>>> u = UPath('/usr/lib/python2.7/site-packages/uripath.py')
>>> dirn = u[:-1]
>>> dirn
UPath('/usr/lib/python2.7/site-packages')
>>> base = u[-1]
>>> base
UPath('uripath.py')
"""
import os.path
import sys

# if you need to make this module OS-specific (rather than for URIs)
# set these variables after importing the uripath module:-
#   uripath.sep = os.sep
#   uripath.curdir = os.curdir
sep = '/'
curdir = '.'

class _UPath(object):
    """A Universal Path; for use in URIs and filesystem paths."""
    def __init__(self, norma):
        self.normalised = norma

    def _appendpath(self, other):
        'Generate a new UPath by joining self to other'
        other = _otherpath(other)
        if os.path.isabs(other):
            raise RuntimeError("Can't append absolute path %s" % other)
        return UPath(
            os.path.join(
                self.normalised,
                other
            )
        )

    def _prependpath(self, other):
        'Generate a new UPath by joining other to self'
        if os.path.isabs(self.normalised):
            raise RuntimeError("Can't append %s to absolute path" % other)
        other = _otherpath(other)
        return UPath(
            os.path.join(
                other,
                self.normalised
            )
        )

    def __div__(self, other):
        return self._appendpath(other)

    def __truediv__(self, other):
        return self._appendpath(other)

    def __rtruediv__(self, other):
        return self._prependpath(other)

    def __rdiv__(self, other):
        return self._prependpath(other)

    def __eq__(self, other):
        other = _otherpath(other)
        return self.normalised == other

    def __lt__(self, other):
        other = _otherpath(other)
        return self.normalised < other

    def __hash__(self):
        return hash(self.normalised)

    def __len__(self):
        return len(self.normalised)

    def __str__(self):
        return self.normalised

    def __unicode__(self):
        return self.normalised.decode('utf-8')

    def __repr__(self):
        return 'UPath(%s)' % repr(self.normalised)

class RootUPath(_UPath):
    """The root path '/'

    Since dirname('/') is still '/',
    and in most cases a slice [:-1] would give us the dirname of a path
    we need to ensure slicing '/' gives us the same result.
    """
    def __init__(self):
        _UPath.__init__(self, sep)

    def __getitem__(self, key):
        if isinstance(key, slice):
            if key.start in (0, None) and key.stop in (-1, None):
                ans = sep
            else:
                sli = [''].__getitem__(key)
                ans = sep.join(sli)
        elif key == 0:
            ans = sep
        else:
            ans = [''][key]
        return UPath(ans) if ans != '' else ans

    def __len__(self):
        return 1

class _NonRootUPath(_UPath):
    def __init__(self, norm):
        _UPath.__init__(self, norm)
        self.split = self.normalised.split(sep)

    def __getitem__(self, key):
        if isinstance(key, slice):
            sli = self.split.__getitem__(key)
            ans = sep.join(sli) if sli != [''] else sep
        else:
            ans = self.split[key]
            if ans == '':
                ans = sep
        return UPath(ans) if ans else ''

    def __len__(self):
        return len(self.split)

class AbsoluteUPath(_NonRootUPath):
    def __init__(self, norm):
        _NonRootUPath.__init__(self, norm)

class RelativeUPath(_NonRootUPath):
    def __init__(self, norm):
        _NonRootUPath.__init__(self, norm)

_AbsoluteUPath = AbsoluteUPath
_RelativeUPath = RelativeUPath
del AbsoluteUPath, RelativeUPath

def _otherpath(other):
    if isUPath(other):
        other = other.normalised
    elif sys.version_info.major < 3 and isinstance(other, unicode):
        other = other.encode('utf-8')
    elif sys.version_info.major >= 3 and isinstance(other, bytes):
        other = other.decode('utf-8')
    elif not isinstance(other, str):
        raise RuntimeError('bad arg [%s] type %s' % (other, type(other)))
    return other

def isUPath(obj):
    return isinstance(obj, _UPath)

def UPath(other=None):
    """UPath factory."""
    if other is None:
        other = curdir

    other = _otherpath(other)
    norm = os.path.normpath(other)

    if norm == '/' or norm == '//':
        return RootUPath()
    elif norm[0] == '/':
        return _AbsoluteUPath(norm)
    else:
        return _RelativeUPath(norm)


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

#ifndef CEF_LIBCEF_BROWSER_URL_REQUEST_CONTEXT_GETTER_H_
#define CEF_LIBCEF_BROWSER_URL_REQUEST_CONTEXT_GETTER_H_
#pragma once

#include <set>
#include <string>
#include <vector>

#include "base/compiler_specific.h"
#include "base/files/file_path.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "content/public/browser/content_browser_client.h"
#include "net/url_request/url_request_context_getter.h"
#include "net/url_request/url_request_job_factory.h"

namespace base {
class MessageLoop;
}

namespace net {
class FtpTransactionFactory;
class HostResolver;
class ProxyConfigService;
class URLRequestContextStorage;
class URLRequestJobFactory;
class URLRequestJobFactoryImpl;
class URLSecurityManager;
}

class CefRequestInterceptor;
class CefURLRequestContextProxy;

/*
// Classes used in network request processing:
//
// RC = net::URLRequestContext
//   Owns various network-related objects including the global cookie manager.
//
// RCP = CefURLRequestContextProxy
//    Creates the CSP and forwards requests to the objects owned by RC.
//
// CSP = CefCookieStoreProxy
//    Gives the CefCookieManager associated with CefBrowserHostImpl an
//    opportunity to handle cookie requests. Otherwise forwards requests via RC
//    to the global cookie manager.
//
// RCG = CefURLRequestContextGetter
//    Creates the RC and manages RCP lifespan.
//
// RCGP = CefURLRequestContextGetterProxy
//    Causes the RCG to create and destroy browser-specific RCPs.
//
// Relationship diagram:
//    ref = reference (scoped_refptr)
//    own = ownership (scoped_ptr)
//    ptr = raw pointer
//
//                          global cookie manager, etc...
//                                      ^
//                                      |
//                              /-own-> RC <-ptr-\
//                             /                  \
//                            / /<-ptr-\           \
//                           / /        \           \
// CefBrowserContext -ref-> RCG --own-> RCP --ref-> CSP
//                           ^          ^           /
//                          ref        ptr         /
//                           |        /           /
// CefBrowserHostImpl -ref-> RCGP----/           /
//             ^                                /
//              \-ref--------------------------/
*/

class CefURLRequestContextGetter : public net::URLRequestContextGetter {
 public:
  CefURLRequestContextGetter(
      base::MessageLoop* io_loop,
      base::MessageLoop* file_loop,
      content::ProtocolHandlerMap* protocol_handlers);
  virtual ~CefURLRequestContextGetter();

  // net::URLRequestContextGetter implementation.
  virtual net::URLRequestContext* GetURLRequestContext() OVERRIDE;
  virtual scoped_refptr<base::SingleThreadTaskRunner>
      GetNetworkTaskRunner() const OVERRIDE;

  net::HostResolver* host_resolver();
  net::URLRequestJobFactoryImpl* job_factory_impl() const {
    return job_factory_impl_;
  }

  void SetCookieStoragePath(const base::FilePath& path,
                            bool persist_session_cookies);
  void SetCookieSupportedSchemes(const std::vector<std::string>& schemes);

  // Manage URLRequestContext proxy objects. It's important that proxy objects
  // not be destroyed while any in-flight URLRequests exist. These methods
  // manage that requirement.
  CefURLRequestContextProxy* CreateURLRequestContextProxy();
  void ReleaseURLRequestContextProxy(CefURLRequestContextProxy* proxy);

 private:
  void CreateProxyConfigService();

  base::MessageLoop* io_loop_;
  base::MessageLoop* file_loop_;

  scoped_ptr<net::ProxyConfigService> proxy_config_service_;
  scoped_ptr<CefRequestInterceptor> request_interceptor_;
  scoped_ptr<net::URLRequestContextStorage> storage_;
  scoped_ptr<net::URLRequestContext> url_request_context_;
  scoped_ptr<net::URLSecurityManager> url_security_manager_;
  scoped_ptr<net::FtpTransactionFactory> ftp_transaction_factory_;
  content::ProtocolHandlerMap protocol_handlers_;
  net::URLRequestJobFactoryImpl* job_factory_impl_;

  typedef std::set<CefURLRequestContextProxy*> RequestContextProxySet;
  RequestContextProxySet url_request_context_proxies_;

  base::FilePath cookie_store_path_;
  std::vector<std::string> cookie_supported_schemes_;

  DISALLOW_COPY_AND_ASSIGN(CefURLRequestContextGetter);
};

#endif  // CEF_LIBCEF_BROWSER_URL_REQUEST_CONTEXT_GETTER_H_