text:
package au.id.hazelwood.xmltvguidebuilder.config;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.HierarchicalConfiguration;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.lang.time.StopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static au.id.hazelwood.xmltvguidebuilder.utils.ClassPathResourceUtils.toInputStream;
import static au.id.hazelwood.xmltvguidebuilder.utils.DateTimeUtils.formatDurationWords;

/**
 * @author Ricky Hazelwood
 * @version 1.0
 */
public class ConfigFactory
{
    private static final Logger LOGGER = LoggerFactory.getLogger(ConfigFactory.class);
    private final Schema schema;

    public ConfigFactory() throws Exception
    {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        schema = schemaFactory.newSchema(new StreamSource(toInputStream("/config.xsd")));
        stopWatch.stop();
        LOGGER.debug("ConfigFactory created in {}", formatDurationWords(stopWatch.getTime()));
    }

    public Config create(File file) throws InvalidConfigException
    {
        try
        {
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            LOGGER.debug("Validating config file {}", file);
            schema.newValidator().validate(new StreamSource(file));
            LOGGER.debug("Loading config file {}", file);
            HierarchicalConfiguration configuration = new XMLConfiguration(file);
            int offset = configuration.getInt("listing.offset");
            int days = configuration.getInt("listing.days");
            int synopsis = configuration.getInt("listing.synopsis");
            String regionId = configuration.getString("listing.regionId");
            Map<Integer, ChannelConfig> channelConfigById = loadChannelConfigs(configuration);
            Config config = new Config(offset, days, synopsis, regionId, new ArrayList<>(channelConfigById.values()));
            LOGGER.debug("Loaded {} from {} in {}", config, file, formatDurationWords(stopWatch.getTime()));
            return config;
        }
        catch (Throwable e)
        {
            throw new InvalidConfigException(e.getMessage(), e);
        }
    }

    private Map<Integer, ChannelConfig> loadChannelConfigs(HierarchicalConfiguration config)
    {
        Map<Integer, ChannelConfig> channelConfigById = new LinkedHashMap<>();
        for (Configuration channelConfig : getConfigurationList(config.configurationsAt("channels.channel")))
        {
            int id = channelConfig.getInt("[@id]");
            String name = channelConfig.getString("");
            channelConfigById.put(id, new ChannelConfig(id, name));
        }
        return channelConfigById;
    }

    private List<Configuration> getConfigurationList(List list)
    {
        return getTypeList(list, Configuration.class);
    }

    private <T> List<T> getTypeList(List entries, Class<T> clazz)
    {
        List<T> result = new ArrayList<T>();
        for (Object entry : entries)
        {
            result.add(clazz.cast(entry));
        }
        return result;
    }
}


text:
package com.xiaoguang.xtaobao.bean;

import cn.bmob.v3.BmobObject;
import cn.bmob.v3.datatype.BmobFile;

/**
 * 商品类别
 * Created by 11655 on 2016/10/23.
 */

public class GoodsType extends BmobObject {
    //商品类别的名称
    private String typeName;
    //商品类别的图片
    private BmobFile typeImg;

    public BmobFile getTypeImg() {
        return typeImg;
    }

    public void setTypeImg(BmobFile typeImg) {
        this.typeImg = typeImg;
    }

    public String getTypeName() {
        return typeName;
    }

    public void setTypeName(String typeName) {
        this.typeName = typeName;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package gov.med.va.innovations.domain;

import gov.med.va.innovations.service.EventManager;
import gov.med.va.innovations.util.DateConverter;
import gov.va.medora.mdws.emrsvc.AllergyTO;
import gov.va.medora.mdws.emrsvc.TaggedText;

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

public class VistaAllergy extends VistaTO {
 	private static final long serialVersionUID = -952398065858872030L;
 	private static final DateConverter DC = new DateConverter();

	protected String allergenId;
    protected String allergenName;
    protected String allergenType;
    protected String reaction;
    protected String severity;
    protected String comment;
    protected Date timestamp;
    protected List<String> facility = new ArrayList<String>();
    protected VistaLocation location;
    protected VistaObservationType type;
    protected VistaAuthor observer;
    protected VistaAuthor recorder;
    protected List<VistaSymptom> reactions = new ArrayList<VistaSymptom>();
    protected List<String> drugIngredients = new ArrayList<String>();
    protected List<String> drugClasses = new ArrayList<String>();

    public VistaAllergy(AllergyTO mdws) {
    	this.allergenId = mdws.getAllergenId();
    	this.allergenName = mdws.getAllergenName();
    	this.allergenType = mdws.getAllergenType();
    	this.reaction = mdws.getReaction();
    	this.severity = mdws.getSeverity();
    	this.comment = mdws.getComment();
    	this.timestamp = DC.convertVistaDate(mdws.getTimestamp());
    	if (null != mdws.getFacility().getTaggedResults() && null != mdws.getFacility().getTaggedResults().getTaggedText()) {
    		for (TaggedText tt : mdws.getFacility().getTaggedResults().getTaggedText()) {
    			this.facility.add(tt.getText());
    		}
    	}
    	this.location = null == mdws.getLocation() ? null : new VistaLocation(mdws.getLocation());
    	this.type = null == mdws.getType() ? null : new VistaObservationType(mdws.getType());
    	this.observer = null == mdws.getObserver()? null : new VistaAuthor(mdws.getObserver());
    	this.recorder = null == mdws.getRecorder() ? null : new VistaAuthor(mdws.getRecorder());
    	if (null != mdws.getDrugIngredients() && null != mdws.getDrugIngredients().getTaggedText()) {
    		for (TaggedText tt : mdws.getDrugIngredients().getTaggedText()) {
    	    	this.drugIngredients.add(tt.getText());
    		}
    	}
    	if (null != mdws.getDrugClasses() && null != mdws.getDrugClasses().getTaggedText()) {
    		for (TaggedText tt : mdws.getDrugClasses().getTaggedText()) {
    			this.drugClasses.add(tt.getText());
    		}
    	}
    }

	public String getAllergenId() {
		return allergenId;
	}

	public String getAllergenName() {
		return null == allergenName ? "" : allergenName;
	}

	public String getAllergenType() {
		return null == allergenType ? "" : allergenType;
	}

	public String getReaction() {
		return null == reaction ? "" : reaction;
	}

	public String getSeverity() {
		return null == severity ? "" : severity;
	}

	public String getComment() {
		return null == comment ? "" : comment;
	}

	public Date getTimestamp() {
		return timestamp;
	}

	public List<String> getFacility() {
		return facility;
	}

	public VistaLocation getLocation() {
		return location;
	}

	public VistaObservationType getType() {
		return type;
	}

	public VistaAuthor getObserver() {
		return observer;
	}

	public VistaAuthor getRecorder() {
		return recorder;
	}

	public List<VistaSymptom> getReactions() {
		return reactions;
	}

	public List<String> getDrugIngredients() {
		return drugIngredients;
	}

	public List<String> getDrugClasses() {
		return drugClasses;
	}

	@Override
	public Integer getListLength() {
		return null;
	}

	@Override
	public EventManager.EventCode getEventCode() {
		return null;
	}
}


text:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE toc
  PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp TOC Version 2.0//EN"
         "http://java.sun.com/products/javahelp/toc_2_0.dtd">

<toc version="2.0">
	<tocitem text="ZAP Gabay sa Gagamit" tocid="toplevelitem">
		<tocitem text="Magdagdag ng Ons" tocid="addons">
			<tocitem text="Active Scan Rules - Alpha" image="ascanalpha-icon" target="ascanalpha"/>
		</tocitem>
	</tocitem>
</toc>


text:
package org.apache.hadoop.mapred.gridmix;

import java.io.IOException;

import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.BlockLocation;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.mapred.gridmix.RandomAlgorithms.Selector;

/**
 * Class for caching a pool of input data to be used by synthetic jobs for
 * simulating read traffic.
 */
class FilePool {

  public static final Log LOG = LogFactory.getLog(FilePool.class);

  /**
   * The minimum file size added to the pool. Default 128MiB.
   */
  public static final String GRIDMIX_MIN_FILE = "gridmix.min.file.size";

  /**
   * The maximum size for files added to the pool. Defualts to 100TiB.
   */
  public static final String GRIDMIX_MAX_TOTAL = "gridmix.max.total.scan";

  private Node root;
  private final Path path;
  private final FileSystem fs;
  private final Configuration conf;
  private final ReadWriteLock updateLock;

  /**
   * Initialize a filepool under the path provided, but do not populate the
   * cache.
   */
  public FilePool(Configuration conf, Path input) throws IOException {
    root = null;
    this.conf = conf;
    this.path = input;
    this.fs = path.getFileSystem(conf);
    updateLock = new ReentrantReadWriteLock();
  }

  /**
   * Gather a collection of files at least as large as minSize.
   * @return The total size of files returned.
   */
  public long getInputFiles(long minSize, Collection<FileStatus> files)
      throws IOException {
    updateLock.readLock().lock();
    try {
      return root.selectFiles(minSize, files);
    } finally {
      updateLock.readLock().unlock();
    }
  }

  /**
   * (Re)generate cache of input FileStatus objects.
   */
  public void refresh() throws IOException {
    updateLock.writeLock().lock();
    try {
      root = new InnerDesc(fs, fs.getFileStatus(path),
        new MinFileFilter(conf.getLong(GRIDMIX_MIN_FILE, 128 * 1024 * 1024),
                          conf.getLong(GRIDMIX_MAX_TOTAL, 100L * (1L << 40))));
      if (0 == root.getSize()) {
        throw new IOException("Found no satisfactory file in " + path);
      }
    } finally {
      updateLock.writeLock().unlock();
    }
  }

  /**
   * Get a set of locations for the given file.
   */
  public BlockLocation[] locationsFor(FileStatus stat, long start, long len)
      throws IOException {
    // TODO cache
    return fs.getFileBlockLocations(stat, start, len);
  }

  static abstract class Node {

    protected final static Random rand = new Random();

    /**
     * Total size of files and directories under the current node.
     */
    abstract long getSize();

    /**
     * Return a set of files whose cumulative size is at least
     * <tt>targetSize</tt>.
     * TODO Clearly size is not the only criterion, e.g. refresh from
     * generated data without including running task output, tolerance
     * for permission issues, etc.
     */
    abstract long selectFiles(long targetSize, Collection<FileStatus> files)
        throws IOException;
  }

  /**
   * Files in current directory of this Node.
   */
  static class LeafDesc extends Node {
    final long size;
    final ArrayList<FileStatus> curdir;

    LeafDesc(ArrayList<FileStatus> curdir, long size) {
      this.size = size;
      this.curdir = curdir;
    }

    @Override
    public long getSize() {
      return size;
    }

    @Override
    public long selectFiles(long targetSize, Collection<FileStatus> files)
        throws IOException {
      if (targetSize >= getSize()) {
        files.addAll(curdir);
        return getSize();
      }

      Selector selector = new Selector(curdir.size(), (double) targetSize
          / getSize(), rand);

      ArrayList<Integer> selected = new ArrayList<Integer>();
      long ret = 0L;
      do {
        int index = selector.next();
        selected.add(index);
        ret += curdir.get(index).getLen();
      } while (ret < targetSize);

      for (Integer i : selected) {
        files.add(curdir.get(i));
      }

      return ret;
    }
  }

  /**
   * A subdirectory of the current Node.
   */
  static class InnerDesc extends Node {
    final long size;
    final double[] dist;
    final Node[] subdir;

    private static final Comparator<Node> nodeComparator =
      new Comparator<Node>() {
          public int compare(Node n1, Node n2) {
            return n1.getSize() < n2.getSize() ? -1
                 : n1.getSize() > n2.getSize() ? 1 : 0;
          }
    };

    InnerDesc(final FileSystem fs, FileStatus thisDir, MinFileFilter filter)
        throws IOException {
      long fileSum = 0L;
      final ArrayList<FileStatus> curFiles = new ArrayList<FileStatus>();
      final ArrayList<FileStatus> curDirs = new ArrayList<FileStatus>();
      for (FileStatus stat : fs.listStatus(thisDir.getPath())) {
        if (stat.isDir()) {
          curDirs.add(stat);
        } else if (filter.accept(stat)) {
          curFiles.add(stat);
          fileSum += stat.getLen();
        }
      }
      ArrayList<Node> subdirList = new ArrayList<Node>();
      if (!curFiles.isEmpty()) {
        subdirList.add(new LeafDesc(curFiles, fileSum));
      }
      for (Iterator<FileStatus> i = curDirs.iterator();
          !filter.done() && i.hasNext();) {
        // add subdirectories
        final Node d = new InnerDesc(fs, i.next(), filter);
        final long dSize = d.getSize();
        if (dSize > 0) {
          fileSum += dSize;
          subdirList.add(d);
        }
      }
      size = fileSum;
      LOG.debug(size + " bytes in " + thisDir.getPath());
      subdir = subdirList.toArray(new Node[subdirList.size()]);
      Arrays.sort(subdir, nodeComparator);
      dist = new double[subdir.length];
      for (int i = dist.length - 1; i > 0; --i) {
        fileSum -= subdir[i].getSize();
        dist[i] = fileSum / (1.0 * size);
      }
    }

    @Override
    public long getSize() {
      return size;
    }

    @Override
    public long selectFiles(long targetSize, Collection<FileStatus> files)
        throws IOException {
      long ret = 0L;
      if (targetSize >= getSize()) {
        // request larger than all subdirs; add everything
        for (Node n : subdir) {
          long added = n.selectFiles(targetSize, files);
          ret += added;
          targetSize -= added;
        }
        return ret;
      }

      // can satisfy request in proper subset of contents
      // select random set, weighted by size
      final HashSet<Node> sub = new HashSet<Node>();
      do {
        assert sub.size() < subdir.length;
        final double r = rand.nextDouble();
        int pos = Math.abs(Arrays.binarySearch(dist, r) + 1) - 1;
        while (sub.contains(subdir[pos])) {
          pos = (pos + 1) % subdir.length;
        }
        long added = subdir[pos].selectFiles(targetSize, files);
        ret += added;
        targetSize -= added;
        sub.add(subdir[pos]);
      } while (targetSize > 0);
      return ret;
    }
  }

  /**
   * Filter enforcing the minFile/maxTotal parameters of the scan.
   */
  private static class MinFileFilter {

    private long totalScan;
    private final long minFileSize;

    public MinFileFilter(long minFileSize, long totalScan) {
      this.minFileSize = minFileSize;
      this.totalScan = totalScan;
    }
    public boolean done() {
      return totalScan <= 0;
    }
    public boolean accept(FileStatus stat) {
      final boolean done = done();
      if (!done && stat.getLen() >= minFileSize) {
        totalScan -= stat.getLen();
        return true;
      }
      return false;
    }
  }

}


text:
import { DomUtils } from "./";
import { ThreeManager } from "../threeutils";

export class Label
{
	tiedTo: THREE.Object3D;
	tieOffset: THREE.Vector3;

	element: HTMLElement;

	/**
	 * -0.5:left, 0:center, 0.5:right
	 */
	alignx: number;
	aligny: number;

	visibility: boolean;
	color: string;

	tempProjectionVector: THREE.Vector3 = new THREE.Vector3();

	constructor(cssClass: string,
		private parent: HTMLElement,
		private camera: THREE.Camera,
		private renderer: THREE.WebGLRenderer)
	{
		this.element = document.createElement("div");
		this.element.className = cssClass;
		parent.appendChild(this.element);
	}

	/**
	 * Clears this label's settings.
	 */
	public free(): void
	{
		this.tiedTo = undefined;
		this.setColor(undefined);
		this.set("", 0, 0);
		this.hide();
	}

	/**
	 * Ties the label's position to that of the specified object.
	 */
	public tieTo(object: THREE.Object3D, offset: THREE.Vector3): void
	{
		this.tiedTo = object;
		this.tieOffset = offset;
	}

	public show()
	{
		if (!this.visibility)
		{
			this.visibility = true;
			this.element.style.visibility = "visible";
		}
	}

	public hide()
	{
		if (this.visibility)
		{
			this.visibility = false;
			this.element.style.visibility = "hidden";
		}
	}

	/**
	 * Manually set this label's position.
	 */
	public setPosition(position: THREE.Vector3): void
	{
		this.tiedTo = undefined;
		this.setPositionHelper(position);
	}

	private setPositionHelper(position: THREE.Vector3): void
	{
		var unprojected = this.tempProjectionVector.addVectors(position, this.tieOffset).project(this.camera);
		unprojected.x = (unprojected.x / 2 + 0.5) * this.parent.offsetWidth;
		unprojected.y = (-unprojected.y / 2 + 0.5) * this.parent.offsetHeight;

		// align
		unprojected.x -= (this.alignx + 0.5) * this.element.offsetWidth;
		unprojected.y -= (this.aligny + 0.5) * this.element.offsetHeight;

		this.element.style.left = Math.round(unprojected.x) + "px";
		this.element.style.top = Math.round(unprojected.y) + "px";
	}

	/**
	 * @param {number} align -0.5:left, 0:center, 0.5:right
	 */
	public set(text: string, alignx: number, aligny: number): void
	{
		this.alignx = alignx;
		this.aligny = aligny;
		this.element.innerHTML = text;
		this.show();
	}

	/**
	 *
	 * @param color Can be in any HTML/CSS form.
	 */
	public setColor(color: string): void
	{
		this.color = color;
		this.element.style.color = color;
	}

	public update(deltaSec: number): void
	{
		if (this.tiedTo)
		{
			this.setPositionHelper(this.tiedTo.position);
		}
	}
}


text:
/*
 * 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 org.jdbi.v3.sqlobject;

import org.jdbi.v3.core.Handle;
import org.jdbi.v3.testing.JdbiRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;

public class TestConcurrentUpdatingQuery {
    @Rule
    public JdbiRule dbRule = JdbiRule.h2();

    private Handle handle;

    @Before
    public void setUp() {
        handle = dbRule.getHandle();
    }

    @Test
    public void testConcurrentUpdateableResultSet() {
        handle.execute("create table something (id identity primary key, name varchar(50))");
        handle.execute("insert into something (id, name) values (7, 'Tim')");
        handle.createQuery("select id, name from something where id = :id")
                .bind("id", 7)
                .concurrentUpdatable()
                .map((r, ctx) -> {
                    r.updateString("name", "Tom");
                    r.updateRow();
                    return null;
                }).list();

        final String name = handle.createQuery("select name from something where id = :id")
                .bind("id", 7)
                .mapTo(String.class)
                .one();

        assertThat(name).isEqualTo("Tom");
    }
}


text:
#ifndef WebCustomElement_h
#define WebCustomElement_h

#include "../platform/WebCommon.h"

namespace blink {

class WebString;

class WebCustomElement {
 public:
  // Adds a name to the set of names embedders can use
  // WebDocument::registerEmbedderCustomElement to register their
  // own types for. Because Custom Element processing requires the
  // set of valid names to be known ahead of time, this method
  // should be called before an element with this name is created.
  BLINK_EXPORT static void addEmbedderCustomElementName(const WebString& name);

 private:
  WebCustomElement();
};

}  // namespace blink

#endif


text:
/*
 * $Id: FuncNot.java 468655 2006-10-28 07:12:06Z minchau $
 */
package org.apache.xpath.functions;

import org.apache.xpath.XPathContext;
import org.apache.xpath.objects.XBoolean;
import org.apache.xpath.objects.XObject;

/**
 * Execute the Not() function.
 * @xsl.usage advanced
 */
public class FuncNot extends FunctionOneArg
{
    static final long serialVersionUID = 7299699961076329790L;

  /**
   * Execute the function.  The function must return
   * a valid object.
   * @param xctxt The current execution context.
   * @return A valid XObject.
   *
   * @throws javax.xml.transform.TransformerException
   */
  public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException
  {
    return m_arg0.execute(xctxt).bool() ? XBoolean.S_FALSE : XBoolean.S_TRUE;
  }
}


text:
/*
 * Boot support
 */
#include <common.h>
#include <bootm.h>
#include <command.h>
#include <environment.h>
#include <errno.h>
#include <image.h>
#include <malloc.h>
#include <nand.h>
#include <asm/byteorder.h>
#include <linux/ctype.h>
#include <linux/err.h>
#include <u-boot/zlib.h>

DECLARE_GLOBAL_DATA_PTR;

#if defined(CONFIG_CMD_IMI)
static int image_info(unsigned long addr);
#endif

#if defined(CONFIG_CMD_IMLS)
#include <flash.h>
#include <mtd/cfi_flash.h>
extern flash_info_t flash_info[]; /* info for FLASH chips */
#endif

#if defined(CONFIG_CMD_IMLS) || defined(CONFIG_CMD_IMLS_NAND)
static int do_imls(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]);
#endif

/* we overload the cmd field with our state machine info instead of a
 * function pointer */
static cmd_tbl_t cmd_bootm_sub[] = {
	U_BOOT_CMD_MKENT(start, 0, 1, (void *)BOOTM_STATE_START, "", ""),
	U_BOOT_CMD_MKENT(loados, 0, 1, (void *)BOOTM_STATE_LOADOS, "", ""),
#ifdef CONFIG_SYS_BOOT_RAMDISK_HIGH
	U_BOOT_CMD_MKENT(ramdisk, 0, 1, (void *)BOOTM_STATE_RAMDISK, "", ""),
#endif
#ifdef CONFIG_OF_LIBFDT
	U_BOOT_CMD_MKENT(fdt, 0, 1, (void *)BOOTM_STATE_FDT, "", ""),
#endif
	U_BOOT_CMD_MKENT(cmdline, 0, 1, (void *)BOOTM_STATE_OS_CMDLINE, "", ""),
	U_BOOT_CMD_MKENT(bdt, 0, 1, (void *)BOOTM_STATE_OS_BD_T, "", ""),
	U_BOOT_CMD_MKENT(prep, 0, 1, (void *)BOOTM_STATE_OS_PREP, "", ""),
	U_BOOT_CMD_MKENT(fake, 0, 1, (void *)BOOTM_STATE_OS_FAKE_GO, "", ""),
	U_BOOT_CMD_MKENT(go, 0, 1, (void *)BOOTM_STATE_OS_GO, "", ""),
};

static int do_bootm_subcommand(cmd_tbl_t *cmdtp, int flag, int argc,
			char * const argv[])
{
	int ret = 0;
	long state;
	cmd_tbl_t *c;

	c = find_cmd_tbl(argv[0], &cmd_bootm_sub[0], ARRAY_SIZE(cmd_bootm_sub));
	argc--; argv++;

	if (c) {
		state = (long)c->cmd;
		if (state == BOOTM_STATE_START)
			state |= BOOTM_STATE_FINDOS | BOOTM_STATE_FINDOTHER;
	} else {
		/* Unrecognized command */
		return CMD_RET_USAGE;
	}

	if (((state & BOOTM_STATE_START) != BOOTM_STATE_START) &&
	    images.state >= state) {
		printf("Trying to execute a command out of order\n");
		return CMD_RET_USAGE;
	}

	ret = do_bootm_states(cmdtp, flag, argc, argv, state, &images, 0);

	return ret;
}

/*******************************************************************/
/* bootm - boot application image from image in memory */
/*******************************************************************/

int do_bootm(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
#ifdef CONFIG_NEEDS_MANUAL_RELOC
	static int relocated = 0;

	if (!relocated) {
		int i;

		/* relocate names of sub-command table */
		for (i = 0; i < ARRAY_SIZE(cmd_bootm_sub); i++)
			cmd_bootm_sub[i].name += gd->reloc_off;

		relocated = 1;
	}
#endif

	/* determine if we have a sub command */
	argc--; argv++;
	if (argc > 0) {
		char *endp;

		simple_strtoul(argv[0], &endp, 16);
		/* endp pointing to NULL means that argv[0] was just a
		 * valid number, pass it along to the normal bootm processing
		 *
		 * If endp is ':' or '#' assume a FIT identifier so pass
		 * along for normal processing.
		 *
		 * Right now we assume the first arg should never be '-'
		 */
		if ((*endp != 0) && (*endp != ':') && (*endp != '#'))
			return do_bootm_subcommand(cmdtp, flag, argc, argv);
	}

	return do_bootm_states(cmdtp, flag, argc, argv, BOOTM_STATE_START |
		BOOTM_STATE_FINDOS | BOOTM_STATE_FINDOTHER |
		BOOTM_STATE_LOADOS |
#if defined(CONFIG_PPC) || defined(CONFIG_MIPS)
		BOOTM_STATE_OS_CMDLINE |
#endif
		BOOTM_STATE_OS_PREP | BOOTM_STATE_OS_FAKE_GO |
		BOOTM_STATE_OS_GO, &images, 1);
}

int bootm_maybe_autostart(cmd_tbl_t *cmdtp, const char *cmd)
{
	const char *ep = getenv("autostart");

	if (ep && !strcmp(ep, "yes")) {
		char *local_args[2];
		local_args[0] = (char *)cmd;
		local_args[1] = NULL;
		printf("Automatic boot of image at addr 0x%08lX ...\n", load_addr);
		return do_bootm(cmdtp, 0, 1, local_args);
	}

	return 0;
}

#ifdef CONFIG_SYS_LONGHELP
static char bootm_help_text[] =
	"[addr [arg ...]]\n    - boot application image stored in memory\n"
	"\tpassing arguments 'arg ...'; when booting a Linux kernel,\n"
	"\t'arg' can be the address of an initrd image\n"
#if defined(CONFIG_OF_LIBFDT)
	"\tWhen booting a Linux kernel which requires a flat device-tree\n"
	"\ta third argument is required which is the address of the\n"
	"\tdevice-tree blob. To boot that kernel without an initrd image,\n"
	"\tuse a '-' for the second argument. If you do not pass a third\n"
	"\ta bd_info struct will be passed instead\n"
#endif
#if defined(CONFIG_FIT)
	"\t\nFor the new multi component uImage format (FIT) addresses\n"
	"\tmust be extened to include component or configuration unit name:\n"
	"\taddr:<subimg_uname> - direct component image specification\n"
	"\taddr#<conf_uname>   - configuration specification\n"
	"\tUse iminfo command to get the list of existing component\n"
	"\timages and configurations.\n"
#endif
	"\nSub-commands to do part of the bootm sequence.  The sub-commands "
	"must be\n"
	"issued in the order below (it's ok to not issue all sub-commands):\n"
	"\tstart [addr [arg ...]]\n"
	"\tloados  - load OS image\n"
#if defined(CONFIG_SYS_BOOT_RAMDISK_HIGH)
	"\tramdisk - relocate initrd, set env initrd_start/initrd_end\n"
#endif
#if defined(CONFIG_OF_LIBFDT)
	"\tfdt     - relocate flat device tree\n"
#endif
	"\tcmdline - OS specific command line processing/setup\n"
	"\tbdt     - OS specific bd_t processing\n"
	"\tprep    - OS specific prep before relocation or go\n"
#if defined(CONFIG_TRACE)
	"\tfake    - OS specific fake start without go\n"
#endif
	"\tgo      - start OS";
#endif

U_BOOT_CMD(
	bootm,	CONFIG_SYS_MAXARGS,	1,	do_bootm,
	"boot application image from memory", bootm_help_text
);

/*******************************************************************/
/* bootd - boot default image */
/*******************************************************************/
#if defined(CONFIG_CMD_BOOTD)
int do_bootd(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
	return run_command(getenv("bootcmd"), flag);
}

U_BOOT_CMD(
	boot,	1,	1,	do_bootd,
	"boot default, i.e., run 'bootcmd'",
	""
);

/* keep old command name "bootd" for backward compatibility */
U_BOOT_CMD(
	bootd, 1,	1,	do_bootd,
	"boot default, i.e., run 'bootcmd'",
	""
);

#endif

/*******************************************************************/
/* iminfo - print header info for a requested image */
/*******************************************************************/
#if defined(CONFIG_CMD_IMI)
static int do_iminfo(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
	int	arg;
	ulong	addr;
	int	rcode = 0;

	if (argc < 2) {
		return image_info(load_addr);
	}

	for (arg = 1; arg < argc; ++arg) {
		addr = simple_strtoul(argv[arg], NULL, 16);
		if (image_info(addr) != 0)
			rcode = 1;
	}
	return rcode;
}

static int image_info(ulong addr)
{
	void *hdr = (void *)addr;

	printf("\n## Checking Image at %08lx ...\n", addr);

	switch (genimg_get_format(hdr)) {
#if defined(CONFIG_IMAGE_FORMAT_LEGACY)
	case IMAGE_FORMAT_LEGACY:
		puts("   Legacy image found\n");
		if (!image_check_magic(hdr)) {
			puts("   Bad Magic Number\n");
			return 1;
		}

		if (!image_check_hcrc(hdr)) {
			puts("   Bad Header Checksum\n");
			return 1;
		}

		image_print_contents(hdr);

		puts("   Verifying Checksum ... ");
		if (!image_check_dcrc(hdr)) {
			puts("   Bad Data CRC\n");
			return 1;
		}
		puts("OK\n");
		return 0;
#endif
#if defined(CONFIG_ANDROID_BOOT_IMAGE)
	case IMAGE_FORMAT_ANDROID:
		puts("   Android image found\n");
		android_print_contents(hdr);
		return 0;
#endif
#if defined(CONFIG_FIT)
	case IMAGE_FORMAT_FIT:
		puts("   FIT image found\n");

		if (!fit_check_format(hdr)) {
			puts("Bad FIT image format!\n");
			return 1;
		}

		fit_print_contents(hdr);

		if (!fit_all_image_verify(hdr)) {
			puts("Bad hash in FIT image!\n");
			return 1;
		}

		return 0;
#endif
	default:
		puts("Unknown image format!\n");
		break;
	}

	return 1;
}

U_BOOT_CMD(
	iminfo,	CONFIG_SYS_MAXARGS,	1,	do_iminfo,
	"print header information for application image",
	"addr [addr ...]\n"
	"    - print header information for application image starting at\n"
	"      address 'addr' in memory; this includes verification of the\n"
	"      image contents (magic number, header and payload checksums)"
);
#endif

/*******************************************************************/
/* imls - list all images found in flash */
/*******************************************************************/
#if defined(CONFIG_CMD_IMLS)
static int do_imls_nor(void)
{
	flash_info_t *info;
	int i, j;
	void *hdr;

	for (i = 0, info = &flash_info[0];
		i < CONFIG_SYS_MAX_FLASH_BANKS; ++i, ++info) {

		if (info->flash_id == FLASH_UNKNOWN)
			goto next_bank;
		for (j = 0; j < info->sector_count; ++j) {

			hdr = (void *)info->start[j];
			if (!hdr)
				goto next_sector;

			switch (genimg_get_format(hdr)) {
#if defined(CONFIG_IMAGE_FORMAT_LEGACY)
			case IMAGE_FORMAT_LEGACY:
				if (!image_check_hcrc(hdr))
					goto next_sector;

				printf("Legacy Image at %08lX:\n", (ulong)hdr);
				image_print_contents(hdr);

				puts("   Verifying Checksum ... ");
				if (!image_check_dcrc(hdr)) {
					puts("Bad Data CRC\n");
				} else {
					puts("OK\n");
				}
				break;
#endif
#if defined(CONFIG_FIT)
			case IMAGE_FORMAT_FIT:
				if (!fit_check_format(hdr))
					goto next_sector;

				printf("FIT Image at %08lX:\n", (ulong)hdr);
				fit_print_contents(hdr);
				break;
#endif
			default:
				goto next_sector;
			}

next_sector:		;
		}
next_bank:	;
	}
	return 0;
}
#endif

#if defined(CONFIG_CMD_IMLS_NAND)
static int nand_imls_legacyimage(struct mtd_info *mtd, int nand_dev,
				 loff_t off, size_t len)
{
	void *imgdata;
	int ret;

	imgdata = malloc(len);
	if (!imgdata) {
		printf("May be a Legacy Image at NAND device %d offset %08llX:\n",
				nand_dev, off);
		printf("   Low memory(cannot allocate memory for image)\n");
		return -ENOMEM;
	}

	ret = nand_read_skip_bad(mtd, off, &len, imgdata);
	if (ret < 0 && ret != -EUCLEAN) {
		free(imgdata);
		return ret;
	}

	if (!image_check_hcrc(imgdata)) {
		free(imgdata);
		return 0;
	}

	printf("Legacy Image at NAND device %d offset %08llX:\n",
			nand_dev, off);
	image_print_contents(imgdata);

	puts("   Verifying Checksum ... ");
	if (!image_check_dcrc(imgdata))
		puts("Bad Data CRC\n");
	else
		puts("OK\n");

	free(imgdata);

	return 0;
}

static int nand_imls_fitimage(struct mtd_info *mtd, int nand_dev, loff_t off,
			      size_t len)
{
	void *imgdata;
	int ret;

	imgdata = malloc(len);
	if (!imgdata) {
		printf("May be a FIT Image at NAND device %d offset %08llX:\n",
				nand_dev, off);
		printf("   Low memory(cannot allocate memory for image)\n");
		return -ENOMEM;
	}

	ret = nand_read_skip_bad(mtd, off, &len, imgdata);
	if (ret < 0 && ret != -EUCLEAN) {
		free(imgdata);
		return ret;
	}

	if (!fit_check_format(imgdata)) {
		free(imgdata);
		return 0;
	}

	printf("FIT Image at NAND device %d offset %08llX:\n", nand_dev, off);

	fit_print_contents(imgdata);
	free(imgdata);

	return 0;
}

static int do_imls_nand(void)
{
	struct mtd_info *mtd;
	int nand_dev = nand_curr_device;
	size_t len;
	loff_t off;
	u32 buffer[16];

	if (nand_dev < 0 || nand_dev >= CONFIG_SYS_MAX_NAND_DEVICE) {
		puts("\nNo NAND devices available\n");
		return -ENODEV;
	}

	printf("\n");

	for (nand_dev = 0; nand_dev < CONFIG_SYS_MAX_NAND_DEVICE; nand_dev++) {
		mtd = nand_info[nand_dev];
		if (!mtd->name || !mtd->size)
			continue;

		for (off = 0; off < mtd->size; off += mtd->erasesize) {
			const image_header_t *header;
			int ret;

			if (nand_block_isbad(mtd, off))
				continue;

			len = sizeof(buffer);

			ret = nand_read(mtd, off, &len, (u8 *)buffer);
			if (ret < 0 && ret != -EUCLEAN) {
				printf("NAND read error %d at offset %08llX\n",
						ret, off);
				continue;
			}

			switch (genimg_get_format(buffer)) {
#if defined(CONFIG_IMAGE_FORMAT_LEGACY)
			case IMAGE_FORMAT_LEGACY:
				header = (const image_header_t *)buffer;

				len = image_get_image_size(header);
				nand_imls_legacyimage(mtd, nand_dev, off, len);
				break;
#endif
#if defined(CONFIG_FIT)
			case IMAGE_FORMAT_FIT:
				len = fit_get_size(buffer);
				nand_imls_fitimage(mtd, nand_dev, off, len);
				break;
#endif
			}
		}
	}

	return 0;
}
#endif

#if defined(CONFIG_CMD_IMLS) || defined(CONFIG_CMD_IMLS_NAND)
static int do_imls(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
	int ret_nor = 0, ret_nand = 0;

#if defined(CONFIG_CMD_IMLS)
	ret_nor = do_imls_nor();
#endif

#if defined(CONFIG_CMD_IMLS_NAND)
	ret_nand = do_imls_nand();
#endif

	if (ret_nor)
		return ret_nor;

	if (ret_nand)
		return ret_nand;

	return (0);
}

U_BOOT_CMD(
	imls,	1,		1,	do_imls,
	"list all images found in flash",
	"\n"
	"    - Prints information about all images found at sector/block\n"
	"      boundaries in nor/nand flash."
);
#endif


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

namespace PortableUserVoice.Data
{
    public class KnowledgeBaseResult
    {
        public ResponseData response_data { get; set; }

        public List<Article> articles { get; set; }

        public class ResponseData
        {
            public int page { get; set; }
            public int per_page { get; set; }
            public int total_records { get; set; }
            public string filter { get; set; }
            public string sort { get; set; }
        }

        public class UpdatedBy
        {
            public int id { get; set; }
            public string name { get; set; }
            public string email { get; set; }
            public string title { get; set; }
            public string url { get; set; }
            public string avatar_url { get; set; }
            public int karma_score { get; set; }
            public string posted_tickets_count { get; set; }
            public string last_message_posted_at { get; set; }
            public string last_ticket_state { get; set; }
            public string last_subscribed_idea_closed_at { get; set; }
            public string created_at { get; set; }
            public string updated_at { get; set; }
        }

        public class Topic
        {
            public int id { get; set; }
            public string name { get; set; }
        }

        public class Article
        {
            public string url { get; set; }
            public string path { get; set; }
            public int id { get; set; }
            public string title { get; set; }
            public string text { get; set; }
            public string formatted_text { get; set; }
            public int uses { get; set; }
            public int instant_answers { get; set; }
            public bool published { get; set; }
            public UpdatedBy updated_by { get; set; }
            public Topic topic { get; set; }
            public int position { get; set; }
            public string created_at { get; set; }
            public string updated_at { get; set; }
            public string question { get; set; }
            public string answer_html { get; set; }
        }

    }
}


text:
  {% if include.category == nil %}
    {% for post in site.posts %}

        {{ post.date | date: site.theme_config.date_format }}»

      {{ post.title }}

    {% endfor %}
  {% else %}
    {% for post in site.categories[include.category] %}

        {{ post.date | date: site.theme_config.date_format }}»

      {{ post.title }}

    {% endfor %}
  {% endif %}


text:
package com.brucezee.jspider.scheduler;

import com.brucezee.jspider.Request;
import com.brucezee.jspider.Task;
import com.brucezee.jspider.monitor.SchedulerMonitor;
import com.brucezee.jspider.paging.PagingRequestFactory;
import com.brucezee.jspider.scheduler.handler.HashSetRepeatHandler;
import com.brucezee.jspider.scheduler.handler.RepeatHandler;
import org.apache.commons.lang3.math.NumberUtils;

import java.util.Comparator;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 实现优先执行的请求任务调度器
 * Created by brucezee on 2017/1/16.
 */
public class QueuePriorityScheduler extends NoRepeatScheduler implements SchedulerMonitor {
    public static final int INITIAL_CAPACITY = 11;
    private Comparator<Request> priorityComparator = new Comparator<Request>() {
        @Override
        public int compare(Request o1, Request o2) {
            return -NumberUtils.compare(o1.getPriority(), o2.getPriority());
        }
    };
    private BlockingQueue<Request> noPriorityQueue = new LinkedBlockingQueue<Request>();
    private PriorityBlockingQueue<Request> priorityQueuePlus = new PriorityBlockingQueue<Request>(INITIAL_CAPACITY, priorityComparator);
    private PriorityBlockingQueue<Request> priorityQueueMinus = new PriorityBlockingQueue<Request>(INITIAL_CAPACITY, priorityComparator);
    private AtomicInteger count = new AtomicInteger(0);

    public QueuePriorityScheduler() {
        this(null, null);
    }

    public QueuePriorityScheduler(RepeatHandler repeatHandler) {
        this(repeatHandler, null);
    }

    public QueuePriorityScheduler(PagingRequestFactory pagingRequestFactory) {
        this(null, pagingRequestFactory);
    }

    public QueuePriorityScheduler(RepeatHandler repeatHandler, PagingRequestFactory pagingRequestFactory) {
        super(repeatHandler != null ? repeatHandler : new HashSetRepeatHandler(), pagingRequestFactory);
    }

    @Override
    public void pushWhenNoRepeat(Task task, Request request) {
        int priority = request.getPriority();
        if (priority == 0) {
            noPriorityQueue.add(request);
        } else if (priority > 0) {
            priorityQueuePlus.add(request);
        } else {
            priorityQueueMinus.add(request);
        }
        count.incrementAndGet();
    }

    @Override
    public Request doPoll(Task task) {
        Request poll = priorityQueuePlus.poll();
        if (poll != null) {
            return poll;
        }
        poll = noPriorityQueue.poll();
        if (poll != null) {
            return poll;
        }
        return priorityQueueMinus.poll();
    }

    @Override
    public int getTotalCount(Task task) {
        return count.get();
    }

    @Override
    public int getLeftCount(Task task) {
        return noPriorityQueue.size() + priorityQueuePlus.size() + priorityQueueMinus.size();
    }
}


text:
<?php

namespace MuzikSpirit\FrontBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use MuzikSpirit\BackBundle\Entity\Video;

/**
 * Class VideoController
 * @package MuzikSpirit\FrontBundle\Controller
 */
class VideoController extends Controller
{

    /**
     * @param int $page
     * @param int $section
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function listAction($page, $section)
    {
        $limit = $this->container->getParameter('max_articles');
        $tabSectionUrl = $this->container->getParameter('sections_url');
        $sectionID = $tabSectionUrl[$section];

        $em = $this->getDoctrine()->getManager();

        if ($sectionID == 0) {
            $query = $em->getRepository('MuzikSpiritBackBundle:Video')->getListVideoQuery()->getQuery();
        } else {
            $query = $em->getRepository('MuzikSpiritBackBundle:Video')->getListVideoBySectionQuery($sectionID)->getQuery();
        }
        $paginator  = $this->get('knp_paginator');
        $paginator = $paginator->paginate(
            $query,
            $page,
            $limit
        );

        return $this->render(
            'MuzikSpiritFrontBundle:Video:list.html.twig',
            [
                'page' => $page,
                'pagination' => $paginator,
            ]
        );
    }

    /**
     * Affichage de l'article
     *
     * @param Video $video
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function viewAction(Video $video)
    {
        return $this->render('MuzikSpiritFrontBundle:Video:view.html.twig', ['video' => $video]);
    }
}


text:
module Oshpark
  class Token

    attr_accessor :expires_at

    def initialize json={}
      super
      @expires_at = Time.now + (@ttl || 0)
    end

    def self.attrs
      %w| token ttl user_id |
    end

    include Model

    def ttl
      expires_at - Time.now
    end

    def user
      User.from_json 'id' => user_id
    end

    def valid?
      ttl > 0
    end

    def authentic?
      valid? && !!user_id
    end

  end
end


text:
package ooo.oxo.library.databinding.support.app;

import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.v7.app.AppCompatActivity;

public abstract class BindingAppCompatActivity<V extends ViewDataBinding> extends AppCompatActivity {

    protected V binding;

    @LayoutRes
    protected abstract int provideContentView(Bundle savedInstanceState);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, provideContentView(savedInstanceState));
    }

}


text:
package org.onosproject.net.resource.link;

import com.google.common.base.MoreObjects;
import org.onosproject.net.resource.ResourceRequest;
import org.onosproject.net.resource.ResourceType;

/**
 * Representation of a request for lambda resource.
 */
public class LambdaResourceRequest implements ResourceRequest {

    @Override
    public ResourceType type() {
        return ResourceType.LAMBDA;
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                .toString();
    }
}


text:
package com.dianping.cat.servlet;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;

public class MonitorResponse extends HttpServletResponseWrapper {
    private int status;

    MonitorResponse(HttpServletResponse response) {
        super(response);
    }

    int getCurrentStatus() {
        return status;
    }

    @Override
    public void reset() {
        super.reset();
        status = 0;
    }

    @Override
    public void sendError(int error) throws IOException {
        super.sendError(error);
        this.status = error;
    }

    @Override
    public void sendError(int error, String message) throws IOException {
        super.sendError(error, message);
        this.status = error;
    }

    @Override
    public void setStatus(int status) {
        super.setStatus(status);
        this.status = status;
    }
}


text:
---
layout: post
title:  Spring 使用笔记之(四) - 配置DataSource多数据源
date:   2015-02-25 16:33:00 +0800
categories: 技术文档
tag: Spring
---

* content
{:toc}

> 核心思想:Spring在每次操作数据库的时候都会通过AbstractRoutingDataSource类中的determineTargetDataSource()方法获取当前数据源,我们就可以通过切面技术,在不同的切面,切入不同的数据源名称,使Spring获取的时候拿到的是不同的数据源。

![AbstractRoutingDataSource类中的determineTargetDataSource()方法的源码](/images/blog/spring/07-spring-datasource/01_source_determinate.png)

而`determineCurrentLookupKey()`方法是抽象的,所以,我们可以实现这个类,重写determineCurrentLookupKey方法,通过切面技术实现多数据源之间切换
{% highlight java %}
/**
 * Determine the current lookup key. This will typically be
 * implemented to check a thread-bound transaction context.
 *
Allows for arbitrary keys. The returned key needs
 * to match the stored lookup key type, as resolved by the
 * {@link #resolveSpecifiedLookupKey} method.
 */
protected abstract Object determineCurrentLookupKey();
{% endhighlight %}

具体实现如下
----------------------------

Spring 中DataSource的定义如下
============================
{% highlight java %}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

	<bean
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="ignoreResourceNotFound" value="true" />
		<property name="locations" value="classpath*:/db/jdbc.properties" />
	</bean>

	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">

		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />

		<property name="maxActive" value="${dbcp.maxActive}" />
		<property name="maxIdle" value="${dbcp.maxIdle}" />
		<property name="defaultAutoCommit" value="false" />
		<property name="timeBetweenEvictionRunsMillis" value="3600000" />
		<property name="minEvictableIdleTimeMillis" value="3600000" />
	</bean>

	<bean id="dataSource2" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">

		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url2}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />

		<property name="maxActive" value="${dbcp.maxActive}" />
		<property name="maxIdle" value="${dbcp.maxIdle}" />
		<property name="defaultAutoCommit" value="false" />
		<property name="timeBetweenEvictionRunsMillis" value="3600000" />
		<property name="minEvictableIdleTimeMillis" value="3600000" />
	</bean>

	<bean id="dynamicDataSource"
		class="com.freud.test.db.multires.DynamicDataSource">
		<property name="targetDataSources">
			<map key-type="java.lang.String">
				<entry value-ref="dataSource" key="dataSource" />
				<entry value-ref="dataSource2" key="dataSource2" />
			</map>
		</property>
		<property name="defaultTargetDataSource" ref="dataSource" />
	</bean>

	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dynamicDataSource" />
	</bean>

	<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage"
			value="com.freud.**.mapper;" />
		<property name="sqlSessionFactory" ref="sqlSessionFactory" />
	</bean>

	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dynamicDataSource" />
	</bean>

	<tx:annotation-driven transaction-manager="transactionManager" />

	<bean id="dataSourceInterceptor" class="com.freud.db.multires.DataSourceInterceptor"/>

	<aop:config>
		<aop:aspect ref="dataSourceInterceptor">
			<aop:pointcut id="default"
				expression="execution(* com.freud.**.*(..))" />
			<aop:pointcut id="test1"
				expression="execution(* com.freud.test1.*.mapper.*.*(..))" />
			<aop:pointcut id="test2"
				expression="execution(* com.freud.test2.*.mapper.*.*(..))" />
			<aop:before pointcut-ref="default" method="setdataSourceOne" />
			<aop:before pointcut-ref="test1" method="setdataSourceOne" />
			<aop:before pointcut-ref="test2" method="setdataSourceTwo" />
		</aop:aspect>
	</aop:config>

</beans>
{% endhighlight %}

DynamicDataSource.java
============================
{% highlight java %}
package com.freud.test.db.multires;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
 * @author Freud
 */
public class DynamicDataSource extends AbstractRoutingDataSource {

	@Override
	protected Object determineCurrentLookupKey() {
		return DatabaseContextHolder.getCustomerType();
	}

}
{% endhighlight %}

DataSourceInterceptor.java
============================
{% highlight java %}
package com.freud.test.db.multires;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;

public class DataSourceInterceptor {

	private static final String DATESOURCE_ONE = "dataSource";
	private static final String DATESOURCE_TWO = "dataSource2";

	public void setdataSourceOne() {
		DatabaseContextHolder.setCustomerType(DATESOURCE_ONE);
	}

	public void setdataSourceTwo() {
		DatabaseContextHolder.setCustomerType(DATESOURCE_TWO);
	}
}
{% endhighlight %}

DatabaseContextHolder.java
============================
{% highlight java %}
package com.freud.test.db.multires;

import com.freud.common.thread.ThreadLocalUtils;

public class DatabaseContextHolder {

	public static final String DATA_DOURCE = "DATA_SOURCE";

	public static void setCustomerType(String customerType) {
		ThreadLocalUtils.put(DATA_DOURCE, customerType);
	}

	public static String getCustomerType() {
		return ThreadLocalUtils.get(DATA_DOURCE);
	}

	public static void clearCustomerType() {
		ThreadLocalUtils.remove(DATA_DOURCE);
	}
}
{% endhighlight %}

ThreadLocalUtils.java
============================
{% highlight java %}
package com.freud.common.thread;

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

public final class ThreadLocalUtils {

	private static final ThreadLocal<Map<String, String>> threadContext = new ThreadLocal<Map<String, String>>();

	public static void put(String key, String value) {
		getContext().put(key, value);
	}

	public static String get(String key) {
		return getContext().get(key);
	}

	public static void remove(String key) {
		getContext().remove(key);
	}

	public static Map<String, String> getContext() {
		Map<String, String> value = threadContext.get();
		if (null == value) {
			threadContext.set(new HashMap<String, String>());
		}
		return threadContext.get();
	}
}
{% endhighlight %}

> 如上操作之后,只需要将需要不同Datasource的Mapper层配置在Spring的DataSource切面配置中就可以实现多数据源的自由切换。

总结
----------------------------
这个方案完全是在spring的框架下解决的,数据源依然配置在spring的配置文件中,sessionFactory依然去配置它的dataSource属性,它甚至都不知道dataSource的改变。唯一不同的是在真正的dataSource与sessionFactory之间基于Decorator(装饰者)模式增加了一个MultiDataSource。

参考资料
======================

[Spring mvc动态多数据源](http://blog.csdn.net/geloin/article/details/7580685)

[spring框架中多数据源创建加载并且实现动态切换的配置实例代码](http://www.zuidaima.com/share/1774074130205696.htm)


text:
from ckan.plugins import toolkit
try:
    from ckan.new_tests import helpers
    from ckan.new_tests import factories
except ImportError:
    from ckan.tests import helpers
    from ckan.tests import factories

from ckanext.issues.tests import factories as issue_factories

import bs4
from nose.tools import (assert_equals, assert_is_not_none, assert_is_none,
                        assert_raises, assert_not_in)

class TestIssuesController(helpers.FunctionalTestBase):
    def test_unauthorized_users_cannot_see_issues_on_a_dataset(self):
        '''test that a 401 is returned, previously this would just 500'''
        user = factories.User()
        org = factories.Organization(user=user)
        dataset = factories.Dataset(user=user, owner_org=org['name'],
                                    private=True)
        issue = issue_factories.Issue(user=user,
                                      user_id=user['id'],
                                      dataset_id=dataset['id'])
        unauthorized_user = factories.User()

        app = self._get_test_app()
        env = {'REMOTE_USER': unauthorized_user['name'].encode('ascii')}

        response = app.get(
            url=toolkit.url_for('issues_show',
                                dataset_id=dataset['id'],
                                issue_number=issue['number']),
            extra_environ=env,
            expect_errors=True
        )
        assert_equals(response.status_int, 401)

class TestIssuesControllerUpdate(helpers.FunctionalTestBase):
    def test_user_cannot_edit_another_users_issue(self):
        owner = factories.User()
        user = factories.User()
        org = factories.Organization(user=owner)
        dataset = factories.Dataset(user=owner, owner_org=org['name'])
        issue = issue_factories.Issue(user=owner, dataset_id=dataset['id'])

        app = self._get_test_app()
        env = {'REMOTE_USER': user['name'].encode('ascii')}

        response = app.post(
            url=toolkit.url_for('issues_edit',
                                dataset_id=dataset['id'],
                                issue_number=issue['number']),
            params={'title': 'edit', 'description': 'edited description'},
            extra_environ=env,
            expect_errors=True
        )
        assert_equals(response.status_int, 401)

class TestShow(helpers.FunctionalTestBase):
    def setup(self):
        super(TestShow, self).setup()
        self.owner = factories.User()
        self.org = factories.Organization(user=self.owner)
        self.dataset = factories.Dataset(user=self.owner,
                                         owner_org=self.org['name'])
        self.app = self._get_test_app()

    def test_not_found_issue_raises_404(self):
        env = {'REMOTE_USER': self.owner['name'].encode('ascii')}
        response = self.app.get(
            url=toolkit.url_for('issues_show',
                                dataset_id=self.dataset['id'],
                                issue_number='some nonsense'),
            extra_environ=env,
            expect_errors=True,
        )
        assert_equals(response.status_int, 404)

    def test_issue_show_with_non_existing_package_404s(self):
        env = {'REMOTE_USER': self.owner['name'].encode('ascii')}
        response = self.app.get(
            url=toolkit.url_for('issues_show',
                                dataset_id='does not exist',
                                issue_number=1),
            extra_environ=env,
            expect_errors=True,
        )
        assert_equals(response.status_int, 404)

class TestDelete(helpers.FunctionalTestBase):
    def setup(self):
        super(TestDelete, self).setup()
        self.owner = factories.User()
        self.org = factories.Organization(user=self.owner)
        self.dataset = factories.Dataset(user=self.owner,
                                         owner_org=self.org['name'])
        self.issue = issue_factories.Issue(user=self.owner,
                                           user_id=self.owner['id'],
                                           dataset_id=self.dataset['id'])
        self.app = self._get_test_app()

    def test_delete(self):
        env = {'REMOTE_USER': self.owner['name'].encode('ascii')}
        response = self.app.post(
            url=toolkit.url_for('issues_delete',
                                dataset_id=self.dataset['id'],
                                issue_number=self.issue['number']),
            extra_environ=env,
        )
        # check we get redirected back to the issues overview page
        assert_equals(302, response.status_int)
        response = response.follow()
        assert_equals(200, response.status_int)
        assert_equals(
            toolkit.url_for('issues_dataset', dataset_id=self.dataset['id']),
            response.request.path
        )
        # check the issue is now deleted.
        assert_raises(toolkit.ObjectNotFound,
                      helpers.call_action,
                      'issue_show',
                      issue_number=self.issue['number'],
                      dataset_id=self.dataset['id'])

    def test_delete_unauthed_401s(self):
        user = factories.User()
        env = {'REMOTE_USER': user['name'].encode('ascii')}
        response = self.app.post(
            url=toolkit.url_for('issues_delete',
                                dataset_id=self.dataset['id'],
                                issue_number=self.issue['number']),
            extra_environ=env,
            expect_errors=True
        )
        assert_equals(401, response.status_int)

    def test_delete_button_appears_for_authed_user(self):
        env = {'REMOTE_USER': self.owner['name'].encode('ascii')}
        response = self.app.get(
            url=toolkit.url_for('issues_show',
                                dataset_id=self.dataset['id'],
                                issue_number=self.issue['number']),
            extra_environ=env,
        )
        form = response.forms['issue-comment-form']
        soup = bs4.BeautifulSoup(form.text)
        delete_link = soup.find_all('a')[-1]
        # check the link of the delete
        assert_equals('Delete', delete_link.text)
        assert_equals(
            toolkit.url_for('issues_delete',
                            dataset_id=self.dataset['id'],
                            issue_number=self.issue['number']),
            delete_link.attrs['href']
        )

    def test_delete_confirm_page(self):
        '''test the confirmation page renders and cancels correctly'''
        env = {'REMOTE_USER': self.owner['name'].encode('ascii')}
        response = self.app.get(
            url=toolkit.url_for('issues_delete',
                                dataset_id=self.dataset['id'],
                                issue_number=self.issue['number']),
            extra_environ=env,
        )
        form = response.forms['ckanext-issues-confirm-delete']
        # check the form target
        assert_equals(
            toolkit.url_for('issues_delete',
                            dataset_id=self.dataset['id'],
                            issue_number=self.issue['number']),
            form.action
        )
        assert_equals([u'cancel', u'delete'], form.fields.keys())
        response = helpers.submit_and_follow(self.app, form, env, 'cancel')
        # check we have been redirected without deletion
        assert_equals(
            toolkit.url_for('issues_show',
                            dataset_id=self.dataset['id'],
                            issue_number=self.issue['number']),
            response.request.path_qs
        )

    def test_delete_button_not_present_for_unauthed_user(self):
        user = factories.User()
        env = {'REMOTE_USER': user['name'].encode('ascii')}
        response = self.app.get(
            url=toolkit.url_for('issues_show',
                                dataset_id=self.dataset['id'],
                                issue_number=self.issue['number']),
            extra_environ=env,
        )
        form = response.forms['issue-comment-form']
        assert_not_in('Delete', form.text)

class TestOrganization(helpers.FunctionalTestBase):
    def setup(self):
        super(TestOrganization, self).setup()
        self.owner = factories.User()
        self.org = factories.Organization(user=self.owner)
        self.dataset = factories.Dataset(user=self.owner,
                                         owner_org=self.org['name'])
        self.issue = issue_factories.Issue(user=self.owner,
                                           user_id=self.owner['id'],
                                           dataset_id=self.dataset['id'])
        self.app = self._get_test_app()

    def test_basic(self):
        env = {'REMOTE_USER': self.owner['name'].encode('ascii')}
        response = self.app.get(
            url=toolkit.url_for('issues_for_organization',
                                org_id=self.org['id']),
            extra_environ=env
        )
        soup = bs4.BeautifulSoup(response.body)
        issues = soup.find('section', {'class': 'issues-home'}).text
        assert '1 issue found' in issues
        issue_page = soup.find('div', {'id': 'issue-page'}).text
        assert self.dataset['title'] in issue_page
        assert self.issue['title'] in issue_page
        assert self.issue['description'] not in issue_page


text:
typedef struct _GLFWtlsPOSIX
{
    pthread_key_t   context;

} _GLFWtlsPOSIX;

int _glfwCreateContextTLS(void);
void _glfwDestroyContextTLS(void);
void _glfwSetContextTLS(_GLFWwindow* context);

#endif // _glfw3_posix_tls_h_


text:
require File.dirname(__FILE__) + '/abstract_unit'

class TestController < ActionController::Base
	def action_attempt_auto_redirect
		if !attempt_auto_redirect
			render :text => 'false'
		end
	end

	def action_auto_redirect
		auto_redirect(:exclude => %r{^/forbidden}, :default => '/')
	end

	def action_save_redirection_information
		if params[:what]
			what = params[:what].to_sym
		else
			what = :current_request
		end
		save_redirection_information(what)
		render :nothing => true
	end

	def action_pass_redirection_information
		render :inline => '<%= pass_redirection_information %>'
	end

	def action_get_redirection_information
		begin
			get_redirection_information
			render :text => 'ok'
		rescue => e
			render :text => e.class.to_s
		end
	end
end

class UsersController < ActionController::Base
end

class SimpleRedirectionTest < ActionController::TestCase
	include AutoRedirection
	include TestHelpers
	tests TestController

	test "attempt_auto_redirect returns false if there's no redirection information" do
		get :action_attempt_auto_redirect
		assert_equal 'false', @response.body
	end

	##### URL GET redirections #####

	test "attempt_auto_redirect redirects to the URL given by the Referer HTTP header" do
		@controller.request.headers["Referer"] = '/foo'
		get :action_attempt_auto_redirect
		assert_redirected_to '/foo'
	end

	test "attempt_auto_redirect redirects to the URL given by the
	      _redirection_information HTTP parameter" do
		info = UrlRedirectionInformation.new('http://www.google.com')
		get(:action_attempt_auto_redirect, :_redirection_information => info.marshal)
		assert_redirected_to 'http://www.google.com'
	end

	test "attempt_auto_redirect redirects to the URL given by the
	      _redirection_information flash" do
		info = UrlRedirectionInformation.new('http://www.google.com')
		get(:action_attempt_auto_redirect, nil, nil,
			:_redirection_information => info.marshal(true, false))
		assert_redirected_to 'http://www.google.com'
	end

	##### Non-URL (controller information) GET redirections #####

	test "attempt_auto_redirect redirects to the non-URL location given by the
	      _redirection_information HTTP parameter" do
		info = ControllerRedirectionInformation.new('users', 'show')
		get(:action_attempt_auto_redirect, :_redirection_information => info.marshal)
		assert_redirected_to '/users/show'
	end

	test "attempt_auto_redirect redirects to the non-URL location given by the
	      _redirection_information HTTP flash" do
		info = ControllerRedirectionInformation.new('users', 'show')
		get(:action_attempt_auto_redirect, nil, nil,
			:_redirection_information => info.marshal(true, false))
		assert_redirected_to '/users/show'
	end

	##### Non-GET redirections #####

	test "attempt_auto_redirect renders a page with a form when the redirection
	      information does not pertain a GET request" do
		info = ControllerRedirectionInformation.new('users', 'create', nil, :post)
		get(:action_attempt_auto_redirect, :_redirection_information => info.marshal)
		assert_response :ok
		assert_select 'form'
	end

	test "the form that attempt_auto_redirect renders contains the correct form action" do
		info = ControllerRedirectionInformation.new('users', 'create',
			{ :hello => "world", :foo => "bar" }, :post)
		get(:action_attempt_auto_redirect, :_redirection_information => info.marshal)
		path, query = parse_form_action
		assert_equal '/users/create', path
		assert_equal({ "hello" => ["world"], "foo" => ["bar"] }, query)
	end

	test "action_save_redirection_information saves the current request details into the flash" do
		post(:action_save_redirection_information, :hello => "world", :foo => ["bar", "baz"])
		info = RedirectionInformation.load(@response.flash[:_redirection_information], true, false)
		assert_kind_of ControllerRedirectionInformation, info
		assert_equal :post, info.method
		assert_equal({
				'controller' => @controller.controller_path,
				'action' => "action_save_redirection_information",
				'hello' => "world",
				'foo' => ["bar", "baz"],
				'_redirection_information' => NoRedirectionInformation.new.marshal
			}, info.params)
	end

	##### View helpers #####

	test "the pass_redirection_information view helper returns nil if there's no redirection information" do
		get(:action_pass_redirection_information)
		assert_equal [], css_select("input")
	end

	test "the pass_redirection_information view helper saves the passed redirection information" do
		info = ControllerRedirectionInformation.new('users', 'create',
			{ :hello => "world", :foo => "bar" }, :post)
		get(:action_pass_redirection_information, :_redirection_information => info.marshal)
		info2 = RedirectionInformation.load(input_value)
		assert_equal info, info2
	end

	test "the pass_redirection_information view helper saves the HTTP referer" do
		@controller.request.headers["Referer"] = '/foo'
		get(:action_pass_redirection_information)
		info = RedirectionInformation.load(input_value)
		assert_kind_of UrlRedirectionInformation, info
		assert_equal '/foo', info.url
	end

	##### Other tests #####

	test "auto_redirect(:exclude => ...) works" do
		@controller.request.headers["Referer"] = '/forbidden'
		get(:action_auto_redirect)
		assert_redirected_to '/'
	end

	test "match_exclusion_list with a Regexp" do
		info = ControllerRedirectionInformation.new('users', 'create', { :id => 1 })
		assert @controller.send(:match_exclusion_list, info, %r{^/users/create})
		assert @controller.send(:match_exclusion_list, info, %r{^/users})
	end

	test "match_exclusion_list with a String" do
		info = ControllerRedirectionInformation.new('users', 'create', { :id => 1 })
		assert @controller.send(:match_exclusion_list, info, '/users/create')

		info = ControllerRedirectionInformation.new('users', 'create', { :id => 1, :hello => 'world' })
		assert @controller.send(:match_exclusion_list, info, '/users/create')

		assert !@controller.send(:match_exclusion_list, info, '/users')
	end

	test "get_redirection_information raises SecurityError if the redirection information cannot be decrypted" do
		get(:action_get_redirection_information, { :_redirection_information => "foo" })
		assert_equal 'SecurityError', @response.body
	end

	test "get_redirection_information(:passed) saves the passed direction information into the flash" do
		info = AutoRedirection::UrlRedirectionInformation.new('http://www.foo.com')
		@controller.expects(:get_redirection_information).returns(info)
		post(:action_save_redirection_information, :hello => "world", :what => :passed)
		info2 = AutoRedirection::RedirectionInformation.load(
			@controller.response.flash[:_redirection_information], true, false)
		assert_equal info, info2
	end
end


text:
package com.twitter.finagle.zipkin.core

import com.twitter.finagle.tracing.{TraceId, Record, Tracer, Annotation, Trace}
import com.twitter.io.Buf
import com.twitter.util.events.{Event, Sink}
import com.twitter.util.{Time, Throw, Try}
import scala.util.control.NoStackTrace

private object Json {
  import com.fasterxml.jackson.annotation.{JsonTypeInfo, JsonInclude}
  import com.fasterxml.jackson.core.`type`.TypeReference
  import com.fasterxml.jackson.databind.{ObjectMapper, JavaType, JsonNode}
  import com.fasterxml.jackson.databind.annotation.JsonDeserialize
  import com.fasterxml.jackson.module.scala.DefaultScalaModule
  import java.lang.reflect.{Type, ParameterizedType}

  // Note: This type is a just a convenience for deserialization in other
  // other Event.Type constructions, but we actually require it for Trace
  // because we're using Jackson's default typing mechanism for Annotation.
  // If we use a Map, somewhere in Jackson's type resolution the type of
  // Annotation is forgotten, and it is passed into the type resolver as an
  // Object. Defining this Envelope preserves the type information.
  @JsonInclude(JsonInclude.Include.NON_ABSENT)
  case class Envelope(
      id: String,
      when: Long,
      // We require an annotation here, because for small numbers, this gets
      // deserialized with a runtime type of int.
      // See: https://github.com/FasterXML/jackson-module-scala/issues/106.
      @JsonDeserialize(contentAs=classOf[java.lang.Long]) traceId: Option[Long],
      @JsonDeserialize(contentAs=classOf[java.lang.Long]) spanId: Option[Long],
      data: Annotation)

  val mapper = new ObjectMapper()
  mapper.registerModule(DefaultScalaModule)

  // Configures the mapper to include class information for Annotation.
  object TypeResolverBuilder
    extends ObjectMapper.DefaultTypeResolverBuilder(ObjectMapper.DefaultTyping.NON_FINAL) {
    override def useForType(typ: JavaType) =
      // Note: getRawClass would be an Object if not for `Envelope`.
      typ.getRawClass == classOf[Annotation]
  }

  mapper.setDefaultTyping(
    TypeResolverBuilder
      .init(JsonTypeInfo.Id.CLASS, null)
      .inclusion(JsonTypeInfo.As.WRAPPER_ARRAY))

  def serialize(o: AnyRef): String = mapper.writeValueAsString(o)

  def deserialize[T: Manifest](value: String): T =
    mapper.readValue(value, typeReference[T])

  def deserialize[T: Manifest](node: JsonNode): T =
    mapper.readValue(node.traverse, typeReference[T])

  private[this] def typeReference[T: Manifest] = new TypeReference[T] {
    override def getType = typeFromManifest(manifest[T])
  }

  private[this] def typeFromManifest(m: Manifest[_]): Type =
    if (m.typeArguments.isEmpty) m.runtimeClass else new ParameterizedType {
      def getRawType = m.runtimeClass
      def getActualTypeArguments = m.typeArguments.map(typeFromManifest).toArray
      def getOwnerType = null
    }
}

object SamplingTracer {

  /**
   * The [[com.twitter.util.events.Event.Type Event.Type]] for trace events.
   */
  val Trace: Event.Type = {

    new Event.Type {
      val id = "Trace"

      def serialize(event: Event) = event match {
        case Event(etype, _, _, _: Annotation.BinaryAnnotation, _, _, _) if etype eq this =>
          Throw(new IllegalArgumentException("unsupported format: " + event) with NoStackTrace)

        case Event(etype, when, _, ann: Annotation, _, tid, sid) if etype eq this =>
          val (t, s) = serializeTrace(tid, sid)
          val data = Json.Envelope(id, when.inMilliseconds, t, s, ann)
          Try(Buf.Utf8(Json.serialize(data)))

        case _ =>
          Throw(new IllegalArgumentException("unknown format: " + event))
      }

      def deserialize(buf: Buf) = for {
        env <- Buf.Utf8.unapply(buf) match {
          case None => Throw(new IllegalArgumentException("unknown format"))
          case Some(str) => Try(Json.deserialize[Json.Envelope](str))
        }
        if env.id == id
      } yield {
        val when = Time.fromMilliseconds(env.when)
        // This line fails without the JsonDeserialize annotation in Envelope.
        val tid = env.traceId.getOrElse(Event.NoTraceId)
        val sid = env.spanId.getOrElse(Event.NoSpanId)
        Event(this, when, objectVal = env.data, traceIdVal = tid, spanIdVal = sid)
      }
    }
  }

}

/**
 * Tracer that supports sampling. Will pass through a subset of the records.
 * @param underlyingTracer Underlying tracer that accumulates the traces and sends off
 *          to the collector.
 * @param initialSampleRate Start off with this sample rate. Can be changed later.
 * @param sink where to send sampled trace events to.
 */
class SamplingTracer(
    underlyingTracer: Tracer,
    initialSampleRate: Float,
    sink: Sink)
  extends Tracer
{

  /**
   * Tracer that supports sampling. Will pass through a subset of the records.
   * @param underlyingTracer Underlying tracer that accumulates the traces and sends off
   *          to the collector.
   * @param initialSampleRate Start off with this sample rate. Can be changed later.
   */
  def this(underlyingTracer: Tracer, initialSampleRate: Float) =
    this(underlyingTracer, initialSampleRate, Sink.default)

  private[this] val sampler = new Sampler
  setSampleRate(initialSampleRate)

  def sampleTrace(traceId: TraceId): Option[Boolean] = sampler.sampleTrace(traceId)

  def setSampleRate(sampleRate: Float): Unit = sampler.setSampleRate(sampleRate)
  def getSampleRate: Float = sampler.sampleRate

  def record(record: Record) {
    if (sampler.sampleRecord(record)) {
      underlyingTracer.record(record)
      if (sink.recording) {
        if (Trace.hasId) {
          val traceId = Trace.id
          sink.event(SamplingTracer.Trace, objectVal = record.annotation,
            traceIdVal = traceId.traceId.self, spanIdVal = traceId.spanId.self)
        } else {
          sink.event(SamplingTracer.Trace, objectVal = record.annotation)
        }
      }
    }
  }
}


text:
"""Processes references for evaluation (except for tokenization)."""
import json
import os

from absl import app
from absl import flags
import six

FLAGS = flags.FLAGS

flags.DEFINE_string("input_prediction_path", None, "Prediction txt file.")
flags.DEFINE_string("input_target_path", None, "Target json file.")
flags.DEFINE_string("output_dir", None, "Output directory.")

def write_predictions(predictions, output_path):
  """Write predictions to file."""
  with open(output_path, "w", encoding="utf-8") as f:
    for prediction in predictions:
      if not prediction:
        prediction = "<null>"
      f.write(prediction.lower() + "\n")

def main(_):
  input_prediction_path = FLAGS.input_prediction_path
  input_target_path = FLAGS.input_target_path
  output_dir = FLAGS.output_dir

  predictions = []
  overlap_predictions = []
  nonoverlap_predictions = []
  with open(input_prediction_path, "r", encoding="utf-8") as input_file:
    for line in input_file:
      line = line.strip()
      predictions.append(line)

  json_examples = []
  with open(input_target_path, "r", encoding="utf-8") as input_file:
    for line in input_file:
      line = six.ensure_text(line, "utf-8")
      json_example = json.loads(line)
      json_examples.append(json_example)

  assert len(predictions) == len(json_examples)
  for index, prediction in enumerate(predictions):
    json_example = json_examples[index]
    if json_example["overlap_subset"]:
      overlap_predictions.append(prediction)
    else:
      nonoverlap_predictions.append(prediction)

  print("Writing predictions.")
  all_output_path = os.path.join(output_dir, "predictions")
  overlap_output_path = os.path.join(output_dir, "overlap_predictions")
  nonoverlap_output_path = os.path.join(output_dir, "nonoverlap_predictions")
  write_predictions(predictions, all_output_path)
  write_predictions(overlap_predictions, overlap_output_path)
  write_predictions(nonoverlap_predictions, nonoverlap_output_path)

if __name__ == "__main__":
  flags.mark_flags_as_required(
      ["input_prediction_path", "input_target_path", "output_dir"])
  app.run(main)


text:
"""GRR Colab magics module.

The module contains implementation of **magic** commands that use GRR API.
"""
import shlex
from typing import Text

from IPython.core import magic_arguments
import pandas as pd

from grr_colab import magics_impl

_PATH_TYPE_CHOICES = [
    magics_impl.OS, magics_impl.TSK, magics_impl.NTFS, magics_impl.REGISTRY
]

def grr_set_no_flow_timeout(line: Text) -> None:
  """Disables flow timeout (it means wait forever).

  Args:
    line: A string representing arguments passed to the magic command.

  Returns:
    Nothing.
  """
  del line  # Unused.
  magics_impl.grr_set_no_flow_timeout_impl()

def grr_set_default_flow_timeout(line: Text) -> None:
  """Sets flow timeout to default value (30 seconds).

  Args:
    line: A string representing arguments passed to the magic command.

  Returns:
    Nothing.
  """
  del line  # Unused.
  magics_impl.grr_set_default_flow_timeout_impl()

@magic_arguments.magic_arguments()
@magic_arguments.argument(
    'timeout', help='Timeout in seconds', type=int, nargs='?', default=None)
def grr_set_flow_timeout(line: Text) -> None:
  """Sets flow timeout.

  Specifying 0 as timeout means not to wait.

  Args:
    line: A string representing arguments passed to the magic command.

  Returns:
    Nothing.
  """
  args = grr_set_flow_timeout.parser.parse_args(shlex.split(line))
  magics_impl.grr_set_flow_timeout_impl(args.timeout)

def grr_list_artifacts(line: Text) -> pd.DataFrame:
  """Lists all registered GRR artifacts.

  Args:
    line: A string representing arguments passed to the magic command.

  Returns:
    Sequence of artifact descriptors.
  """
  del line  # Unused.
  return magics_impl.grr_list_artifacts_impl()

@magic_arguments.magic_arguments()
@magic_arguments.argument('-i', '--ip', help='IP address', type=str)
@magic_arguments.argument('-m', '--mac', help='MAC address', type=str)
@magic_arguments.argument('-h', '--host', help='Hostname', type=str)
@magic_arguments.argument('-u', '--user', help='Username', type=str)
@magic_arguments.argument('-v', '--version', help='Client version', type=str)
@magic_arguments.argument(
    '-l', '--label', help='Client label', type=str, action='append')
def grr_search_clients(line: Text) -> pd.DataFrame:
  """Searches for clients with specified keywords.

  Args:
    line: A string representing arguments passed to the magic command.

  Returns:
    List of clients.
  """
  args = grr_search_clients.parser.parse_args(shlex.split(line))
  return magics_impl.grr_search_clients_impl(
      ip=args.ip,
      mac=args.mac,
      host=args.host,
      user=args.user,
      version=args.version,
      labels=args.label)

@magic_arguments.magic_arguments()
@magic_arguments.argument('-i', '--ip', help='IP address', type=str)
@magic_arguments.argument('-m', '--mac', help='MAC address', type=str)
@magic_arguments.argument('-h', '--host', help='Hostname', type=str)
@magic_arguments.argument('-u', '--user', help='Username', type=str)
@magic_arguments.argument('-v', '--version', help='Client version', type=str)
@magic_arguments.argument(
    '-l', '--label', help='Client label', type=str, action='append')
def grr_search_online_clients(line: Text) -> pd.DataFrame:
  """Searches for online clients with specified keywords.

  Args:
    line: A string representing arguments passed to the magic command.

  Returns:
    List of online clients.
  """
  args = grr_search_online_clients.parser.parse_args(shlex.split(line))
  return magics_impl.grr_search_online_clients_impl(
      ip=args.ip,
      mac=args.mac,
      host=args.host,
      user=args.user,
      version=args.version,
      labels=args.label)

@magic_arguments.magic_arguments()
@magic_arguments.argument('-h', '--hostname', help='Hostname', type=str)
@magic_arguments.argument('-c', '--client', help='Client ID', type=str)
def grr_set_client(line: Text) -> None:
  """Sets a new client for the current state.

  Args:
    line: A string representing arguments passed to the magic command.

  Returns:
    Nothing.
  """
  args = grr_set_client.parser.parse_args(shlex.split(line))
  magics_impl.grr_set_client_impl(args.hostname, args.client)

@magic_arguments.magic_arguments()
@magic_arguments.argument(
    '-r', '--reason', help='Reason for the approval', type=str)
@magic_arguments.argument(
    '-a',
    '--approvers',
    help='Notified users who can approve the request',
    type=str,
    nargs='+')
@magic_arguments.argument(
    '-w', '--wait', action='store_true', help='Wait until approval is granted')
def grr_request_approval(line: Text) -> None:
  """Sends approval request to the selected client for the current user.

  Args:
    line: A string representing arguments passed to the magic command.

  Returns:
    Nothing.

  Raises:
    NoClientSelectedError: Client is not selected to perform this operation.
  """
  args = grr_request_approval.parser.parse_args(shlex.split(line))
  magics_impl.grr_request_approval_impl(args.reason, args.approvers, args.wait)

def grr_id(line: Text) -> Text:
  """Returns ID of the selected client.

  Args:
    line: A string representing arguments passed to the magic command.

  Returns:
    String representing ID of a client.

  Raises:
    NoClientSelectedError: Client is not selected to perform this operation.
  """
  del line  # Unused.
  return magics_impl.grr_id_impl()

@magic_arguments.magic_arguments()
@magic_arguments.argument('path', help='Directory path', type=str)
def grr_cd(line: Text) -> None:
  """Changes the current directory.

  Args:
    line: A string representing arguments passed to the magic command.

  Returns:
    Nothing.

  Raises:
    NoClientSelectedError: Client is not selected to perform this operation.
  """
  args = grr_cd.parser.parse_args(shlex.split(line))
  magics_impl.grr_cd_impl(args.path)

def grr_pwd(line: Text) -> Text:
  """Returns absolute path to the current directory.

  Args:
    line: A string representing arguments passed to the magic command.

  Returns:
    Absolute path to the current directory.

  Raises:
    NoClientSelectedError: Client is not selected to perform this operation.
  """
  del line  # Unused.
  return magics_impl.grr_pwd_impl()

@magic_arguments.magic_arguments()
@magic_arguments.argument('path', help='Directory path', type=str, nargs='?')
@magic_arguments.argument(
    '-C',
    '--cached',
    action='store_true',
    help='Use cached filesystem instead of making call to a client')
@magic_arguments.argument(
    '-P',
    '--path-type',
    help='Path type',
    type=str,
    choices=_PATH_TYPE_CHOICES,
    default=magics_impl.OS)
def grr_ls(line: Text) -> pd.DataFrame:
  """Lists files in the specified directory or the current directory.

  Args:
    line: A string representing arguments passed to the magic command.

  Returns:
    A sequence of stat entries.

  Raises:
    NoClientSelectedError: Client is not selected to perform this operation.
  """
  args = grr_ls.parser.parse_args(shlex.split(line))
  return magics_impl.grr_ls_impl(
      path=args.path, cached=args.cached, path_type=args.path_type)

@magic_arguments.magic_arguments()
@magic_arguments.argument('path', help='File path', type=str)
@magic_arguments.argument(
    '-P',
    '--path-type',
    help='Path type',
    type=str,
    choices=_PATH_TYPE_CHOICES,
    default=magics_impl.OS)
def grr_stat(line: Text) -> pd.DataFrame:
  """Stats the file specified.

  Accepts glob expressions as a file path.

  Args:
    line: A string representing arguments passed to the magic command.

  Returns:
    A sequence of stat entries.

  Raises:
    NoClientSelectedError: Client is not selected to perform this operation.
  """
  args = grr_stat.parser.parse_args(shlex.split(line))
  return magics_impl.grr_stat_impl(path=args.path, path_type=args.path_type)

@magic_arguments.magic_arguments()
@magic_arguments.argument('path', help='File path', type=str)
@magic_arguments.argument(
    '-c', '--bytes', default=4096, help='Number of bytes to read', type=int)
@magic_arguments.argument(
    '-o', '--offset', default=0, help='Number of bytes to skip', type=int)
@magic_arguments.argument(
    '-C',
    '--cached',
    action='store_true',
    help='Use cached filesystem instead of making call to a client')
@magic_arguments.argument(
    '-P',
    '--path-type',
    help='Path type',
    type=str,
    choices=_PATH_TYPE_CHOICES,
    default=magics_impl.OS)
def grr_head(line: Text) -> bytes:
  """Reads the first bytes of a specified file.

  Args:
    line: A string representing arguments passed to the magic command.

  Returns:
    Specified number of the first bytes of the file.

  Raises:
    NoClientSelectedError: Client is not selected to perform this operation.
  """
  args = grr_head.parser.parse_args(shlex.split(line))
  return magics_impl.grr_head_impl(
      path=args.path,
      bytes=args.bytes,
      offset=args.offset,
      cached=args.cached,
      path_type=args.path_type)

@magic_arguments.magic_arguments()
@magic_arguments.argument('pattern', help='Pattern to search for', type=str)
@magic_arguments.argument('path', help='File path', type=str)
@magic_arguments.argument(
    '-F',
    '--fixed-strings',
    action='store_true',
    help='Interpret pattern as a fixed string (literal)')
@magic_arguments.argument(
    '-P',
    '--path-type',
    help='Path type',
    type=str,
    choices=_PATH_TYPE_CHOICES,
    default=magics_impl.OS)
@magic_arguments.argument(
    '-X',
    '--hex-string',
    action='store_true',
    help='Interpret pattern as a hex-encoded byte string')
def grr_grep(line: Text) -> pd.DataFrame:
  """Greps for a given content of a specified file.

  Args:
    line: A string representing arguments passed to the magic command.

  Returns:
    A list of buffer references to the matched content.

  Raises:
    NoClientSelectedError: Client is not selected to perform this operation.
  """
  args = grr_grep.parser.parse_args(shlex.split(line))
  return magics_impl.grr_grep_impl(
      pattern=args.pattern,
      path=args.path,
      fixed_strings=args.fixed_strings,
      path_type=args.path_type,
      hex_string=args.hex_string)

@magic_arguments.magic_arguments()
@magic_arguments.argument('literal', help='Literal to search for', type=str)
@magic_arguments.argument('path', help='File path', type=str)
@magic_arguments.argument(
    '-P',
    '--path-type',
    help='Path type',
    type=str,
    choices=_PATH_TYPE_CHOICES,
    default=magics_impl.OS)
@magic_arguments.argument(
    '-X',
    '--hex-string',
    action='store_true',
    help='Interpret pattern as a hex-encoded byte string')
def grr_fgrep(line: Text) -> pd.DataFrame:
  """Greps for a given literal content of a specified file.

  Is the same as running: %grr_grep -F

  Args:
    line: A string representing arguments passed to the magic command.

  Returns:
    A list of buffer references to the matched content.

  Raises:
    NoClientSelectedError: Client is not selected to perform this operation.
  """
  args = grr_fgrep.parser.parse_args(shlex.split(line))
  return magics_impl.grr_fgrep_impl(
      literal=args.literal,
      path=args.path,
      path_type=args.path_type,
      hex_string=args.hex_string)

def grr_interrogate(line: Text) -> pd.DataFrame:
  """Creates Interrogate flow for the chosen client.

  Args:
    line: A string representing arguments passed to the magic command.

  Returns:
    Client summary including system and client info, interfaces, and users.

  Raises:
    NoClientSelectedError: Client is not selected to perform this operation.
  """
  del line  # Unused.
  return magics_impl.grr_interrogate_impl()

def grr_hostname(line: Text) -> Text:
  """Returns hostname of the selected client.

  Args:
    line: A string representing arguments passed to the magic command.

  Returns:
    String representing hostname of a client.

  Raises:
    NoClientSelectedError: Client is not selected to perform this operation.
  """
  del line  # Unused.
  return magics_impl.grr_hostname_impl()

def grr_ifconfig(line: Text) -> pd.DataFrame:
  """Lists network interfaces of the selected client.

  Args:
    line: A string representing arguments passed to the magic command.

  Returns:
    Sequence of interfaces.

  Raises:
    NoClientSelectedError: Client is not selected to perform this operation.
  """
  del line  # Unused.
  return magics_impl.grr_ifconfig_impl()

@magic_arguments.magic_arguments()
@magic_arguments.argument(
    '-m', '--machine', action='store_true', help='Get machine hardware name')
@magic_arguments.argument(
    '-r',
    '--kernel-release',
    action='store_true',
    help='Get kernel release string')
def grr_uname(line: Text) -> Text:
  """Returns certain system infornamtion.

  Args:
    line: A string representing arguments passed to the magic command.

  Returns:
    String representing some system information.

  Raises:
    NoClientSelectedError: Client is not selected to perform this operation.
  """
  args = grr_uname.parser.parse_args(shlex.split(line))
  return magics_impl.grr_uname_impl(args.machine, args.kernel_release)

def grr_ps(line: Text) -> pd.DataFrame:
  """Lists processes of the selected client.

  Args:
    line: A string representing arguments passed to the magic command.

  Returns:
    Sequence of processes.

  Raises:
    NoClientSelectedError: Client is not selected to perform this operation.
  """
  del line  # Unused.
  return magics_impl.grr_ps_impl()

@magic_arguments.magic_arguments()
@magic_arguments.argument('sql', help='SQL statement', type=str)
def grr_osqueryi(line: Text) -> pd.DataFrame:
  """Runs given SQL statement on client osquery.

  Args:
    line: A string representing arguments passed to the magic command.

  Returns:
    Osquery table.

  Raises:
    NoClientSelectedError: Client is not selected to perform this operation.
  """
  args = grr_osqueryi.parser.parse_args(shlex.split(line))
  return magics_impl.grr_osqueryi_impl(args.sql)

@magic_arguments.magic_arguments()
@magic_arguments.argument('artifact', help='Name of the artifact', type=str)
def grr_collect(line: Text) -> pd.DataFrame:
  """Collects specified artifact.

  Args:
    line: A string representing arguments passed to the magic command.

  Returns:
    Sequence of results that artifact collection yielded.

  Raises:
    NoClientSelectedError: Client is not selected to perform this operation.
  """
  args = grr_collect.parser.parse_args(shlex.split(line))
  return magics_impl.grr_collect_impl(args.artifact)

@magic_arguments.magic_arguments()
@magic_arguments.argument('signature', help='YARA rule to use', type=str)
@magic_arguments.argument('-r', '--regex', help='Process name regex', type=str)
@magic_arguments.argument(
    '-p', '--pids', help='Pids of processes to scan', type=int, nargs='+')
def grr_yara(line: Text) -> pd.DataFrame:
  """Scans processes using provided YARA rule.

  Args:
    line: A string representing arguments passed to the magic command.

  Returns:
    A sequence of YARA matches.

  Raises:
    NoClientSelectedError: Client is not selected to perform this operation.
  """
  args = grr_yara.parser.parse_args(shlex.split(line))
  return magics_impl.grr_yara_impl(args.signature, args.pids, args.regex)

@magic_arguments.magic_arguments()
@magic_arguments.argument('path', help='File path', type=str)
@magic_arguments.argument(
    '-C',
    '--cached',
    action='store_true',
    help='Use cached filesystem instead of making call to a client')
@magic_arguments.argument(
    '-P',
    '--path-type',
    help='Path type',
    type=str,
    choices=_PATH_TYPE_CHOICES,
    default=magics_impl.OS)
def grr_wget(line: Text) -> Text:
  """Downloads a file and returns a link to it.

  Args:
    line: A string representing arguments passed to the magic command.

  Returns:
    A link to the file.

  Raises:
    NoClientSelectedError: Client is not selected to perform this operation.
  """
  args = grr_wget.parser.parse_args(shlex.split(line))
  return magics_impl.grr_wget_impl(
      path=args.path, cached=args.cached, path_type=args.path_type)


text:
using System;

namespace PowerLib.System.Collections
{
	public interface ISelfRef<T>
		where T : ISelfRef<T>
	{
		T This
		{
			get;
		}
	}
}


text:
<?php

//Loop through the groupings to find grouping file you want to append to
foreach ($js_groupings as $key => $groupings)
{
    foreach  ($groupings as $file => $target)
    {
        //if the target grouping is found
        if ($target == 'include/javascript/sugar_grp7.min.js')
        {
            //append the custom JavaScript file to existing grouping
            $js_groupings[$key]['custom/modules/Accounts/myCustomButton.js'] = 'include/javascript/sugar_grp7.min.js';
        }
        break;
    }
}


text:
package slurp

import (
  "github.com/omeid/slurp/log"
)

type C struct {
	log.Log
	done <-chan struct{}
}

func (c *C) New(prefix string) *C {
  return &C{Log: c.Log.New(prefix), done: c.done}
}

// Done returns a channel that's closed when the current build is
// canceled. You should return as soon as possible.
// Successive calls to Done return the same value.
func (c  *C) Done() <-chan struct{} {
  return c.done
}


text:
*6lowPAN Border Router for Biotz System*

# Overview

This is the code for a border router for the BIotz System.

Run ./runrouter.sh to start router communications with PC

Run ./testrouter to doi some simple tests of the router.


text:
<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "mysay_address".
 *
 * @property integer $id
 * @property string $name
 */
class MysayAddress extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'mysay_address';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name'], 'required'],
            [['name'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Name',
        ];
    }

    public static function allAddress(){
        $address=MysayAddress::find()->asArray()->all();
        $arr=[];
        foreach ($address as $k=>$v){
            $arr[$v['id']]=$v['name'];
        }
        return $arr;
    }
}


text:
title: go
e2eSpecific: true
---

Navigate back or forward to the previous or next URL in the browser's history.

## Syntax

```javascript
cy.go(direction)
cy.go(direction, options)
```

### Usage

**<Icon name="check-circle" color="green"></Icon> Correct Usage**

```javascript
cy.go('back')
```

### Arguments

**<Icon name="angle-right"></Icon> direction** **_(String, Number)_**

The direction to navigate.

You can use `back` or `forward` to go one step back or forward. You could also
navigate to a specific history position (`-1` goes back one page, `1` goes
forward one page, etc).

**<Icon name="angle-right"></Icon> options** **_(Object)_**

Pass in an options object to change the default behavior of `cy.go()`.

| Option    | Default                                                        | Description                                                                              |
| --------- | -------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
| `log`     | `true`                                                         | Displays the command in the [Command log](/guides/core-concepts/cypress-app#Command-Log) |
| `timeout` | [`pageLoadTimeout`](/guides/references/configuration#Timeouts) | Time to wait for `cy.go()` to resolve before [timing out](#Timeouts)                     |

### Yields [<Icon name="question-circle"/>](/guides/core-concepts/introduction-to-cypress#Subject-Management)

<List>
`cy.go()` 'yields the `window` object after the page finishes loading'

</List>

## Examples

### Direction

#### Go back in browser's history

```javascript
cy.go('back') // equivalent to clicking back button
```

#### Go forward in browser's history

```javascript
cy.go('forward') // equivalent to clicking forward button
```

### Number

#### Go back in browser's history

```javascript
cy.go(-1) // equivalent to clicking back button
```

#### Go forward in browser's history

```javascript
cy.go(1) // equivalent to clicking forward button
```

## Notes

#### Refreshing and loading the page

If going forward or back causes a full page refresh, Cypress will wait for the
new page to load before moving on to new commands.

Cypress additionally handles situations where a page load was not caused (such
as hash routing) and will resolve immediately.

## Rules

### Requirements [<Icon name="question-circle"/>](/guides/core-concepts/introduction-to-cypress#Chains-of-Commands)

<List>
`cy.go()` requires being chained off of `cy`.

`cy.go()`
requires the response to be `content-type: text/html`.

`cy.go()`
requires the response code to be `2xx` after following
redirects.

`cy.go()` requires the load `load` event to eventually
fire.
</List>

### Assertions [<Icon name="question-circle"/>](/guides/core-concepts/introduction-to-cypress#Assertions)

<List>
`cy.go()` will automatically wait for assertions you have chained to
pass
</List>

### Timeouts [<Icon name="question-circle"/>](/guides/core-concepts/introduction-to-cypress#Timeouts)

<List>
`cy.go()` can time out waiting for the page to fire its `load`
event.

`cy.go()` can time out waiting for assertions you've added to
pass.
</List>

## Command Log

**_Go back in browser's history_**

```javascript
cy.visit('http://localhost:8000/folders').go('back')
```

The commands above will display in the Command Log as:

<DocsImage src="/img/api/go/test-showing-go-back-browser-button.png" alt="Command Log go" ></DocsImage>

When clicking on the `go` command within the command log, the console outputs
the following:

<DocsImage src="/img/api/go/window-is-logged-when-go-back-in-browser-history.png" alt="console Log go" ></DocsImage>

## See also

- [`cy.reload()`](/api/commands/reload)
- [`cy.visit()`](/api/commands/visit)