text:
<?php

namespace Symfony\Component\HttpFoundation\Session;

use Symfony\Component\HttpFoundation\Session\Storage\SessionStorageInterface;
use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;
use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBagInterface;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
use Symfony\Component\HttpFoundation\Session\SessionBagInterface;
use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;

/**
 * Session.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 * @author Drak <drak@zikula.org>
 *
 * @api
 */
class Session implements SessionInterface
{
    /**
     * Storage driver.
     *
     * @var SessionStorageInterface
     */
    protected $storage;

    /**
     * @var string
     */
    private $flashName;

    /**
     * @var string
     */
    private $attributeName;

    /**
     * Constructor.
     *
     * @param SessionStorageInterface $storage    A SessionStorageInterface instance.
     * @param AttributeBagInterface   $attributes An AttributeBagInterface instance, (defaults null for default AttributeBag)
     * @param FlashBagInterface       $flashes    A FlashBagInterface instance (defaults null for default FlashBag)
     */
    public function __construct(SessionStorageInterface $storage = null, AttributeBagInterface $attributes = null, FlashBagInterface $flashes = null)
    {
        $this->storage = $storage ?: new NativeSessionStorage();

        $attributeBag = $attributes ?: new AttributeBag();
        $this->attributeName = $attributeBag->getName();
        $this->registerBag($attributeBag);

        $flashBag = $flashes ?: new FlashBag();
        $this->flashName = $flashBag->getName();
        $this->registerBag($flashBag);
    }

    /**
     * {@inheritdoc}
     */
    public function start()
    {
        return $this->storage->start();
    }

    /**
     * {@inheritdoc}
     */
    public function has($name)
    {
        return $this->storage->getBag($this->attributeName)->has($name);
    }

    /**
     * {@inheritdoc}
     */
    public function get($name, $default = null)
    {
        return $this->storage->getBag($this->attributeName)->get($name, $default);
    }

    /**
     * {@inheritdoc}
     */
    public function set($name, $value)
    {
        $this->storage->getBag($this->attributeName)->set($name, $value);
    }

    /**
     * {@inheritdoc}
     */
    public function all()
    {
        return $this->storage->getBag($this->attributeName)->all();
    }

    /**
     * {@inheritdoc}
     */
    public function replace(array $attributes)
    {
        $this->storage->getBag($this->attributeName)->replace($attributes);
    }

    /**
     * {@inheritdoc}
     */
    public function remove($name)
    {
        return $this->storage->getBag($this->attributeName)->remove($name);
    }

    /**
     * {@inheritdoc}
     */
    public function clear()
    {
        $this->storage->getBag($this->attributeName)->clear();
    }

    /**
     * {@inheritdoc}
     */
    public function invalidate()
    {
        $this->storage->clear();

        return $this->storage->regenerate(true);
    }

    /**
     * {@inheritdoc}
     */
    public function migrate($destroy = false)
    {
        return $this->storage->regenerate($destroy);
    }

    /**
     * {@inheritdoc}
     */
    public function save()
    {
        $this->storage->save();
    }

    /**
     * {@inheritdoc}
     */
    public function getId()
    {
        return $this->storage->getId();
    }

    /**
     * {@inheritdoc}
     */
    public function setId($id)
    {
        $this->storage->setId($id);
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return $this->storage->getName();
    }

    /**
     * {@inheritdoc}
     */
    public function setName($name)
    {
        $this->storage->setName($name);
    }

    /**
     * Registers a SessionBagInterface with the session.
     *
     * @param SessionBagInterface $bag
     */
    public function registerBag(SessionBagInterface $bag)
    {
        $this->storage->registerBag($bag);
    }

    /**
     * Get's a bag instance.
     *
     * @param string $name
     *
     * @return SessionBagInterface
     */
    public function getBag($name)
    {
        return $this->storage->getBag($name);
    }

    /**
     * Gets the flashbag interface.
     *
     * @return FlashBagInterface
     */
    public function getFlashBag()
    {
        return $this->getBag($this->flashName);
    }

    // the following methods are kept for compatibility with Symfony 2.0 (they will be removed for Symfony 2.3)

    /**
     * @return array
     *
     * @deprecated since 2.1, will be removed from 2.3
     */
    public function getFlashes()
    {
        return $this->getBag('flashes')->all();
    }

    /**
     * @param array $values
     *
     * @deprecated since 2.1, will be removed from 2.3
     */
    public function setFlashes($values)
    {
       $this->getBag('flashes')->setAll($values);
    }

    /**
     * @param string $name
     * @param string $default
     *
     * @return string
     *
     * @deprecated since 2.1, will be removed from 2.3
     */
    public function getFlash($name, $default = null)
    {
       return $this->getBag('flashes')->get($name, $default);
    }

    /**
     * @param string $name
     * @param string $value
     *
     * @deprecated since 2.1, will be removed from 2.3
     */
    public function setFlash($name, $value)
    {
       $this->getBag('flashes')->set($name, $value);
    }

    /**
     * @param string $name
     *
     * @return Boolean
     *
     * @deprecated since 2.1, will be removed from 2.3
     */
    public function hasFlash($name)
    {
       return $this->getBag('flashes')->has($name);
    }

    /**
     * @param string $name
     *
     * @deprecated since 2.1, will be removed from 2.3
     */
    public function removeFlash($name)
    {
       $this->getBag('flashes')->get($name);
    }

    /**
     * @return array
     *
     * @deprecated since 2.1, will be removed from 2.3
     */
    public function clearFlashes()
    {
       return $this->getBag('flashes')->clear();
    }
}


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ExtAspNet;

namespace CJia.Evaluation.Web.Backstage
{
    public partial class AddDept : CJia.Evaluation.Tools.Page,CJia.Evaluation.Views.Backstage.IAddDept
    {
        CJia.Evaluation.Views.Backstage.AddDeptArgs addDeptArgs = new Views.Backstage.AddDeptArgs();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                OnQueryAllDept(null, null);
            }
        }

        protected override object CreatePresenter()
        {
            return new Presenters.Backstage.AddDeptPresenter(this);
        }

        #region【时间方法】
        protected void btn_Save_Click(object sender, EventArgs e)
        {
            DataTable dtUser = Session["User"] as DataTable;
            addDeptArgs.DeptName = txt_Dept_Name.Text;
            addDeptArgs.ParentId = ddl_Parent_Dept.SelectedValue;
            addDeptArgs.UserId = dtUser.Rows[0]["USER_ID"].ToString();
            OnInsertDept(null, addDeptArgs);
        }

        protected void btn_Cancle_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
        }
        #endregion

        #region【实现接口】
        public event EventHandler<Views.Backstage.AddDeptArgs> OnQueryAllDept;

        public event EventHandler<Views.Backstage.AddDeptArgs> OnInsertDept;

        public void ExeReturnAddDeptMsg(bool isInsert)
        {
            if (!isInsert)
            {
                Session["IsDeptUpdate"] = "1";
                ExtAspNet.Alert.ShowInTop("添加失败!", ExtAspNet.MessageBoxIcon.Error);
            }
            else
            {
                Session["IsDeptUpdate"] = "1";
                PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
            }
        }

        public void ExeBindDept(System.Data.DataTable dtDept)
        {
            ddl_Parent_Dept.DataValueField = "DEPT_ID";
            ddl_Parent_Dept.DataTextField = "DEPT_NAME";
            ddl_Parent_Dept.DataSource = dtDept;
            ddl_Parent_Dept.DataBind();
        }
        #endregion

    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Threading.Tasks;
using System.Web.Http;

namespace WebStack.QA.Share.Controllers
{
    public class PrimitiveOperationsController : ApiController
    {
        [AcceptVerbs("GET", "PUT", "POST", "DELETE")]
        public int EchoInt32(int input)
        {
            return input;
        }

        [AcceptVerbs("GET", "PUT", "POST", "DELETE")]
        public short EchoInt16(short input)
        {
            return input;
        }

        [AcceptVerbs("GET", "PUT", "POST", "DELETE")]
        public long EchoInt64(long input)
        {
            return input;
        }

        [AcceptVerbs("GET", "PUT", "POST", "DELETE")]
        public uint EchoUInt32(uint input)
        {
            return input;
        }

        [AcceptVerbs("GET", "PUT", "POST", "DELETE")]
        public ushort EchoUInt16(ushort input)
        {
            return input;
        }

        [AcceptVerbs("GET", "PUT", "POST", "DELETE")]
        public ulong EchoUInt64(ulong input)
        {
            return input;
        }

        [AcceptVerbs("GET", "PUT", "POST", "DELETE")]
        public byte EchoByte(byte input)
        {
            return input;
        }

        [AcceptVerbs("GET", "PUT", "POST", "DELETE")]
        public sbyte EchoSByte(sbyte input)
        {
            return input;
        }

        [AcceptVerbs("GET", "PUT", "POST", "DELETE")]
        public double EchoDouble(double input)
        {
            return input;
        }

        [AcceptVerbs("GET", "PUT", "POST", "DELETE")]
        public float EchoSingle(float input)
        {
            return input;
        }

        [AcceptVerbs("GET", "PUT", "POST", "DELETE")]
        public decimal EchoDecimal(decimal input)
        {
            return input;
        }

        [AcceptVerbs("GET", "PUT", "POST", "DELETE")]
        public char EchoChar(char input)
        {
            return input;
        }

        [AcceptVerbs("GET", "PUT", "POST", "DELETE")]
        public bool EchoBoolean(bool input)
        {
            return input;
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public int EchoInt32FromBody([FromBody]int input)
        {
            return input;
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public short EchoInt16FromBody([FromBody]short input)
        {
            return input;
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public long EchoInt64FromBody([FromBody]long input)
        {
            return input;
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public uint EchoUInt32FromBody([FromBody]uint input)
        {
            return input;
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public ushort EchoUInt16FromBody([FromBody]ushort input)
        {
            return input;
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public ulong EchoUInt64FromBody([FromBody]ulong input)
        {
            return input;
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public byte EchoByteFromBody([FromBody]byte input)
        {
            return input;
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public sbyte EchoSByteFromBody([FromBody]sbyte input)
        {
            return input;
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public double EchoDoubleFromBody([FromBody]double input)
        {
            return input;
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public float EchoSingleFromBody([FromBody]float input)
        {
            return input;
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public decimal EchoDecimalFromBody([FromBody]decimal input)
        {
            return input;
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public char EchoCharFromBody([FromBody]char input)
        {
            return input;
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public bool EchoBooleanFromBody([FromBody]bool input)
        {
            return input;
        }
    }

    public class PrimitiveOperationsAsyncController : ApiController
    {
        [AcceptVerbs("GET", "PUT", "POST", "DELETE")]
        public Task<int> EchoInt32(int input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("GET", "PUT", "POST", "DELETE")]
        public Task<short> EchoInt16(short input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("GET", "PUT", "POST", "DELETE")]
        public Task<long> EchoInt64(long input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("GET", "PUT", "POST", "DELETE")]
        public Task<uint> EchoUInt32(uint input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("GET", "PUT", "POST", "DELETE")]
        public Task<ushort> EchoUInt16(ushort input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("GET", "PUT", "POST", "DELETE")]
        public Task<ulong> EchoUInt64(ulong input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("GET", "PUT", "POST", "DELETE")]
        public Task<byte> EchoByte(byte input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("GET", "PUT", "POST", "DELETE")]
        public Task<sbyte> EchoSByte(sbyte input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("GET", "PUT", "POST", "DELETE")]
        public Task<double> EchoDouble(double input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("GET", "PUT", "POST", "DELETE")]
        public Task<float> EchoSingle(float input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("GET", "PUT", "POST", "DELETE")]
        public Task<decimal> EchoDecimal(decimal input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("GET", "PUT", "POST", "DELETE")]
        public Task<char> EchoChar(char input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("GET", "PUT", "POST", "DELETE")]
        public Task<bool> EchoBoolean(bool input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<int> EchoInt32FromBody([FromBody]int input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<short> EchoInt16FromBody([FromBody]short input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<long> EchoInt64FromBody([FromBody]long input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<uint> EchoUInt32FromBody([FromBody]uint input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<ushort> EchoUInt16FromBody([FromBody]ushort input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<ulong> EchoUInt64FromBody([FromBody]ulong input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<byte> EchoByteFromBody([FromBody]byte input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<sbyte> EchoSByteFromBody([FromBody]sbyte input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<double> EchoDoubleFromBody([FromBody]double input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<float> EchoSingleFromBody([FromBody]float input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<decimal> EchoDecimalFromBody([FromBody]decimal input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<char> EchoCharFromBody([FromBody]char input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<bool> EchoBooleanFromBody([FromBody]bool input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<string> EchoStringFromBody([FromBody]string input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<Guid> EchoGuidFromBody([FromBody]Guid input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<Uri> EchoUriFromBody([FromBody]Uri input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<TimeSpan> EchoTimeSpanFromBody([FromBody]TimeSpan input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<DBNull> EchoDBNullFromBody(DBNull input) // FromBody by default
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<DateTime> EchoDateTimeFromBody([FromBody] DateTime input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<DateTimeOffset> EchoDateTimeOffsetFromBody([FromBody] DateTimeOffset input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<int?> EchoNullableInt32FromBody([FromBody] int? input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<short?> EchoNullableInt16FromBody([FromBody] short? input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<long?> EchoNullableInt64FromBody([FromBody] long? input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<uint?> EchoNullableUInt32FromBody([FromBody] uint? input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<ushort?> EchoNullableUInt16FromBody([FromBody] ushort? input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<ulong?> EchoNullableUInt64FromBody([FromBody] ulong? input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<byte?> EchoNullableByteFromBody([FromBody] byte? input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<sbyte?> EchoNullableSByteFromBody([FromBody] sbyte? input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<double?> EchoNullableDoubleFromBody([FromBody] double? input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<float?> EchoNullableSingleFromBody([FromBody] float? input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<decimal?> EchoNullableDecimalFromBody([FromBody] decimal? input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<char?> EchoNullableCharFromBody([FromBody] char? input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<bool?> EchoNullableBooleanFromBody([FromBody] bool? input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<Guid?> EchoNullableGuidFromBody([FromBody]Guid? input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<TimeSpan?> EchoNullableTimeSpanFromBody([FromBody]TimeSpan? input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<DateTime?> EchoNullableDateTimeFromBody([FromBody] DateTime? input)
        {
            return Task.Factory.StartNew(() => input);
        }

        [AcceptVerbs("PUT", "POST", "DELETE")]
        public Task<DateTimeOffset?> EchoNullableDateTimeOffsetFromBody([FromBody] DateTimeOffset? input)
        {
            return Task.Factory.StartNew(() => input);
        }
    }
}


text:
export const description = `
Basic tests.
`;

import { makeTestGroup } from '../../../../common/framework/test_group.js';
import { memcpy } from '../../../../common/util/util.js';
import { GPUTest } from '../../../gpu_test.js';

export const g = makeTestGroup(GPUTest);

g.test('empty').fn(async t => {
  const encoder = t.device.createCommandEncoder();
  const cmd = encoder.finish();
  t.device.queue.submit([cmd]);
});

g.test('b2t2b').fn(async t => {
  const data = new Uint32Array([0x01020304]);

  const src = t.device.createBuffer({
    mappedAtCreation: true,
    size: 4,
    usage: GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST,
  });
  memcpy({ src: data }, { dst: src.getMappedRange() });
  src.unmap();

  const dst = t.device.createBuffer({
    size: 4,
    usage: GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST,
  });

  const mid = t.device.createTexture({
    size: { width: 1, height: 1, depthOrArrayLayers: 1 },
    format: 'rgba8uint',
    usage: GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST,
  });

  const encoder = t.device.createCommandEncoder();
  encoder.copyBufferToTexture(
    { buffer: src, bytesPerRow: 256 },
    { texture: mid, mipLevel: 0, origin: { x: 0, y: 0, z: 0 } },
    { width: 1, height: 1, depthOrArrayLayers: 1 }
  );
  encoder.copyTextureToBuffer(
    { texture: mid, mipLevel: 0, origin: { x: 0, y: 0, z: 0 } },
    { buffer: dst, bytesPerRow: 256 },
    { width: 1, height: 1, depthOrArrayLayers: 1 }
  );
  t.device.queue.submit([encoder.finish()]);

  t.expectGPUBufferValuesEqual(dst, data);
});

g.test('b2t2t2b').fn(async t => {
  const data = new Uint32Array([0x01020304]);

  const src = t.device.createBuffer({
    mappedAtCreation: true,
    size: 4,
    usage: GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST,
  });
  memcpy({ src: data }, { dst: src.getMappedRange() });
  src.unmap();

  const dst = t.device.createBuffer({
    size: 4,
    usage: GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST,
  });

  const midDesc: GPUTextureDescriptor = {
    size: { width: 1, height: 1, depthOrArrayLayers: 1 },
    format: 'rgba8uint',
    usage: GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST,
  };
  const mid1 = t.device.createTexture(midDesc);
  const mid2 = t.device.createTexture(midDesc);

  const encoder = t.device.createCommandEncoder();
  encoder.copyBufferToTexture(
    { buffer: src, bytesPerRow: 256 },
    { texture: mid1, mipLevel: 0, origin: { x: 0, y: 0, z: 0 } },
    { width: 1, height: 1, depthOrArrayLayers: 1 }
  );
  encoder.copyTextureToTexture(
    { texture: mid1, mipLevel: 0, origin: { x: 0, y: 0, z: 0 } },
    { texture: mid2, mipLevel: 0, origin: { x: 0, y: 0, z: 0 } },
    { width: 1, height: 1, depthOrArrayLayers: 1 }
  );
  encoder.copyTextureToBuffer(
    { texture: mid2, mipLevel: 0, origin: { x: 0, y: 0, z: 0 } },
    { buffer: dst, bytesPerRow: 256 },
    { width: 1, height: 1, depthOrArrayLayers: 1 }
  );
  t.device.queue.submit([encoder.finish()]);

  t.expectGPUBufferValuesEqual(dst, data);
});


text:
package com.bjorktech.promotion.server.coupon.dto;

import lombok.Data;

/**
 * User: sheshan
 * Date: 2018/7/20
 * content:
 */
@Data
public class CouponDTO {
    private String couponName;
}


text: package com.asura.framework.commons.json;


text:
from django.db import connection

def nextval(sequence, cursor=None):
    if cursor is None:
        cursor = connection.cursor()

    cursor.execute("SELECT NEXTVAL(%s)", (sequence,))

    return cursor.fetchone()[0]


text:
import * as React from "react";
import { SurveyQuestionElementBase } from "./reactquestion_element";
import { QuestionImagePickerModel } from "../question_imagepicker";
import { ItemValue } from "../itemvalue";
import { ReactQuestionFactory } from "./reactquestion_factory";

export class SurveyQuestionImagePicker extends SurveyQuestionElementBase {
  constructor(props: any) {
    super(props);
    this.handleOnChange = this.handleOnChange.bind(this);
  }
  protected get question(): QuestionImagePickerModel {
    return this.questionBase as QuestionImagePickerModel;
  }
  handleOnChange(event: any) {
    if (this.question.multiSelect) {
      if (event.target.checked) {
        this.question.value = this.question.value.concat(event.target.value);
      } else {
        var currValue = this.question.value;
        currValue.splice(this.question.value.indexOf(event.target.value), 1);
        this.question.value = currValue;
      }
    } else {
      this.question.value = event.target.value;
    }
    this.setState({ value: this.question.value });
  }
  protected renderElement(): JSX.Element {
    var cssClasses = this.question.cssClasses;
    return (
      <fieldset className={cssClasses.root}>
        <legend aria-label={this.question.locTitle.renderedHtml} />
        {this.getItems(cssClasses)}
      </fieldset>
    );
  }
  protected getItems(cssClasses: any): Array<any> {
    var items = [];
    for (var i = 0; i < this.question.visibleChoices.length; i++) {
      var item = this.question.visibleChoices[i];
      var key = "item" + i;
      items.push(this.renderItem(key, item, cssClasses));
    }
    return items;
  }
  protected get textStyle(): any {
    return { marginLeft: "3px", display: "inline", position: "static" };
  }
  protected renderItem(
    key: string,
    item: ItemValue,
    cssClasses: any
  ): JSX.Element {
    var isChecked = this.question.isItemSelected(item);
    var id = this.question.inputId + "_" + item.value;
    var itemClass = this.question.getItemClass(item);
    var text = null;
    if (this.question.showLabel) {
      text = (

          {item.text || item.value}

      );
    }

    var style: any = { objectFit: this.question.imageFit };

    var control = null;
    if (this.question.contentMode === "image") {
      control = (

      );
    }
    if (this.question.contentMode === "video") {
      control = (
        <embed
          className={cssClasses.image}
          src={item["imageLink"]}
          width={
            this.question.imageWidth
              ? this.question.imageWidth + "px"
              : undefined
          }
          height={
            this.question.imageHeight
              ? this.question.imageHeight + "px"
              : undefined
          }
          style={style}
        />
      );
    }

    return (

          <input
            style={{ display: "none" }}
            className={cssClasses.itemControl}
            id={id}
            type={this.question.multiSelect ? "checkbox" : "radio"}
            name={this.question.name + "_" + this.questionBase.id}
            checked={isChecked}
            value={item.value}
            disabled={this.isDisplayMode || !item.isEnabled}
            onChange={this.handleOnChange}
            aria-label={this.question.locTitle.renderedHtml}
            aria-invalid={this.question.errors.length > 0}
            aria-describedby={
              this.question.errors.length > 0
                ? this.question.id + "_errors"
                : null
            }
          />

            {control}
            {text}

    );
  }
}

ReactQuestionFactory.Instance.registerQuestion("imagepicker", (props) => {
  return React.createElement(SurveyQuestionImagePicker, props);
});


text:
Ad-hoc Casts
============

A simple application for creating ad-hoc podcasts from directories of mp3s.

------------------
About Ad-hoc Casts

Ad-hoc Casts is an easy way to generate ad-hoc podcasts from directories of mp3s.
I often find talks on the internet that provide an mp3. I want to listen to them
on my phone but listening to individual mp3's from the internet is much more
cumbersome than listening to a podcast. For example my podcast app can play the
audio at a higher speed, automatically delete audio when it's been played,
download the file when I'm not on a cellular connection, queue up multiple files
to play etc. With Ad-hoc Casts. I can quickly download one or more mp3's to my
laptop and turn them into a podcast that can be subscribed to on my phone.

-----
Usage

The program takes two arguments. The first -url is the base url to publish the
podcasts under. The hostname should be the hostname of your machine. The -dir is
the root directory where the application will look for podcast directories.

./adhoccasts -dir /Users/efarrer/Podcasts/ -url http://adhoccasts.duckdns.org:8080

------------------------------------
Directory layout for ad-hoc podcasts
Each directory is it's own podcast and any mp3s under that directory will be
treated as episodes. The title of the podcast is the portion of the directory
name before a double underscore. . The description is the portion after the
double underscore. Any single underscores will be converted to spaces. So a
podcast titled "Old Yeller" with the description of "A sad podcast about a dog"
Could be created by the following directory name:
"Old_Yeller__A_sad_podcast_about_a_dog"

------------
Code Quality

This is a quick and dirty program that's currently at the "runs on my machine"
state. It could probably use a refactor and improved unit tests. Feel free to
use it, modify it and send patches. Don't use it as a good example of Go code
(it's not).


text:
namespace :rake do
  desc "TASK='rake tasks' (RAILS_ENV is cap's rails_env [default: 'production'])"
  task :default do
    rails_env = fetch(:rails_env, "production")
    run "(cd #{current_path}; RAILS_ENV=#{rails_env} rake #{ENV['TASK']})"
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;

using NFluent;

using PygmentSharp.Core.Extensions;

using Xunit;

namespace PygmentSharp.UnitTests.Extensions
{
    public class StringExtensionsTests
    {
        [Theory]
        [InlineData("", "foo", "")]
        [InlineData(null, "foo", null)]
        [InlineData("cat", "dog", "dog")]
        public void PythonAnd(string left, string right, string expectedResult)
        {
            var result = left.PythonAnd(right);

            Check.That(result).IsEqualTo(expectedResult);
        }

        [Theory]
        [InlineData("", "foo", "foo")]
        [InlineData(null, "foo", "foo")]
        [InlineData("cat", "dog", "cat")]
        public void PythonOr(string left, string right, string expectedResult)
        {
            var result = left.PythonOr(right);

            Check.That(result).IsEqualTo(expectedResult);
        }

        [Theory]
        [InlineData("a", "b", "c", "b")]
        [InlineData(null, "b", "c", "c")]
        [InlineData("", "b","c","c")]
        public void PythonAndOr(string a, string b, string c, string expectedResult)
        {
            var result = a.PythonAnd(b).PythonOr(c);

            Check.That(result).IsEqualTo(expectedResult);
        }

        [Theory]
        [InlineData("foobar", "raboof")]
        [InlineData("racecar", "racecar")]
        public void Backwards(string input, string expectedOutput)
        {
            var result = input.Backwards();
            Check.That(result).IsEqualTo(expectedOutput);
        }

        [Theory]
        [InlineData("code.cs", "*.cs")]
        [InlineData(@"C:\some\directory\code.cs", "*.cs")]
        [InlineData(@"some\relative-directory\code.cs", "*.cs")]
        [InlineData(@"App.config", "App.config")]
        [InlineData(@"C:\some\directory\Web.config", "Web.config")]
        public void MatchesWildcard(string filename, string wildcard)
        {
            Check.That(filename.MatchesFileWildcard(wildcard)).IsTrue();
        }

        [Theory]
        [InlineData(@"/home/bob/some/directory/code.cs", "*.cs")]
        [InlineData(@"~/some/directory/code.cs", "*.cs")]
        [InlineData(@"some/relative-directory/code.cs", "*.cs")]
        [InlineData(@"C:/some/directory/Web.config", "Web.config")]
        public void MatchesWildcard_SupportsUnixPathSeparator(string filename, string wildcard)
        {
            Check.That(filename.MatchesFileWildcard(wildcard)).IsTrue();
        }

        [Fact]
        public void MatchesWildcard_CaseInsensitive()
        {
            Check.That("SomeFile.CS".MatchesFileWildcard("*.cs")).IsTrue();
        }

        [Theory]
        [InlineData(@"c:\somefile\stuff.cs\myfile.pdf", "*.cs")]
        [InlineData(@"relative/directory/app.configs/foo.bar", "app.config")]
        public void DoesntMatchDirectoryNames(string filename, string wildcard)
        {
            Check.That(filename.MatchesFileWildcard(wildcard)).IsFalse();
        }
    }
}


text:
This plugin provides Gradle-based assembly of DEB packages, typically for Linux distributions
derived from Debian, e.g. Ubuntu.  It leverages [JDeb](https://github.com/tcurdt/jdeb) Java library.

# Basic Usage

```
    buildscript {
        repositories {
            jcenter()
        }

        dependencies {
            classpath 'com.netflix.nebula:gradle-ospackage-plugin:1.12.2'
        }
    }

    apply plugin: 'deb'

    task fooDeb(type: Deb) {
        release '1'
    }

```

# Task Usage

The DEB plugin provides a Task based on a standard copy task, similar to the Zip and Tar tasks. The power comes from
specifying "from" and "into" calls, read more in the [Copying files](http://www.gradle.org/docs/current/userguide/working_with_files.html#sec:copying_files)
section of the Gradle documentation.  On top of the standard available methods, there are some additional values that
be set, which are specific to DEBs. Quite of them have defaults which fall back to fields on the project.

* _packageName_ - Default to project.name
* _release_ - DEB Release
* _version_ - Version field, defaults to project.version
* _user_ - Default user to permission files to
* _permissionGroup_ - Default group to permission files to, "group" is used by Gradle for the display of tasks
* _packageGroup_
* _buildHost_
* _summary_
* _packageDescription_
* _license_
* _packager_
* _distribution_
* _vendor_
* _url_
* _sourcePackage_
* _provides_
* _createDirectoryEntry [Boolean]_
* uid - Default uid of files
* gid - Default gid of files
* _multiArch_ - Configure multi-arch behavior: NONE (default), SAME, FOREIGN, ALLOWED (see: https://wiki.ubuntu.com/MultiarchSpec

# Symbolic Links

Symbolic links are specified via the links method, where the permissions umask is optional:

```
link(String symLinkPath, String targetPath, int permissions)
```

# Requires

Required packages are specified via the required method:

```
requires(String packageName, String version)
```

# Scripts

To provide the scripts traditionally seen in the spec files, they are provided as Strings or as files. Their
corresponding methods can be called multiple times, and the contents will be appended in the order provided.

* _preInstall_
* _postInstall_
* _preUninstall_
* _postUninstall_
* _installUtils_ - Scripts which are prefixed to all the other scripts.

# Copy Spec

The following attributes can be used inside _from_ and _into_ closures to complement the [Copy Spec](http://www.gradle.org/docs/current/userguide/working_with_files.html#sec:copying_files).

* user
* permissionGroup
* fileType
* uid
* gid

(Above can be set via property syntax, e.g. "user='jryan'", or method syntax, e.g. "user 'jryan'")

# Example

```
    task fooRpm(type: Deb) {
        packageName = 'foo'
        version = '1.2.3'
        release = 1

        installUtils file('scripts/rpm/utils.sh')
        preInstall file('scripts/rpm/preInstall.sh')
        postInstall file('scripts/rpm/postInstall.sh')
        preUninstall file('scripts/rpm/preUninstall.sh')
        postUninstall file('scripts/rpm/postUninstall.sh')

        requires('bar', '2.2')
        requires('baz', '1.0.1')
        requires('qux')

        into '/opt/foo'

        from(jar.outputs.files) {
            into 'lib'
        }
        from(configurations.runtime) {
            into 'lib'
        }
        from('lib') {
            into 'lib'
        }
        from('scripts') {
            into 'bin'
            exclude 'database'
            fileMode 0550
        }
        from('src/main/resources') {
            fileType CONFIG | NOREPLACE
            into 'conf'
        }
        from('home') {
            createDirectoryEntry = true
            fileMode 0500
            into 'home'
        }
        from('endorsed') {
            into '/usr/share/tomcat/endorsed'
        }

        link('/etc/init.d/foo', '/opt/foo/bin/foo.init')
    }
```


text:
require 'markdown_renderer'

class Chapter < ActiveRecord::Base
  PARTS = ["frontmatter", "mainmatter", "backmatter"]

  # Provides an accessor to get to the git repository where the chapter is contained
  attr_accessor :git

  attr_accessor :footnote_count
  attr_accessor :section_count
  attr_accessor :image_count
  attr_accessor :listing_count

  belongs_to :book

  has_many :elements, -> { order("id ASC") }
  has_many :images
  has_many :notes, through: :elements

  scope :ordered, -> { order("position ASC") }
  scope :frontmatter, -> { ordered.where(part: "frontmatter") }
  scope :mainmatter, -> { ordered.where(part: "mainmatter") }
  scope :backmatter, -> { ordered.where(part: "backmatter") }

  after_save :expire_cache

  # Defaults footnote_count to something.
  # Would use attr_accessor_with_default if it wasn't deprecated.
  def footnote_count
    @footnote_count ||= 0
  end

  # Default image count to 0, increments when we call process_figure! in Processor
  def image_count
    @image_count ||= 0
  end

  # Default listing count to 0, increments when we call process_example! in
  # Processor
  def listing_count
    @listing_count ||= 0
  end

  # Used for correctly counting + labelling the sections.
  # Works with the within_section method contained in the Processor module.
  #
  # Let's assume we're processing the first chapter of a book
  # For the first section, this variable will become:
  # [1, 1]
  # Next section:
  # [1, 1]
  # A sub-section of that section:
  # [1, 1, 1]
  # Then the next top-level section would be:
  # [1, 2]
  def section_count
    @section_count ||= [position, 0]
  end

  def process!
    # Keep any elements that have notes, ditch the rest
    elements.where("notes_count > 0").update_all(old: true)
    elements.where("notes_count = 0").delete_all

    images.delete_all

    html = to_html
    self.title = html.css("h1").text
    self.permalink = title.parameterize
    elements = html.css("body > *")
    elements.each { |element| Element.process!(self, element) }
    save
  end

  def previous_chapter
    # A previous chapter in the same part
    prev = book.chapters.find_by(part: part, position: position - 1)
    return prev if prev

    # The last chapter in the previous part
    current_part_index = PARTS.index(part)
    if current_part_index != 0
      book.chapters.where(part: PARTS[current_part_index-1]).order(position: :asc).last
    end
  end

  def next_chapter
    # The next chapter in the same part
    next_ch = book.chapters.find_by(part: part, position: position + 1)
    return next_ch if next_ch

    # The first chapter in the next part
    current_part_index = PARTS.index(part)
    if current_part_index != PARTS.count - 1
      book.chapters.where(part: PARTS[current_part_index+1]).order(position: :asc).first
    end
  end

  def to_html
    markdown = File.read(File.join(book.path, file_name))
    renderer = Redcarpet::Markdown.new(MarkdownRenderer, :fenced_code_blocks => true)
    html = Nokogiri::HTML(renderer.render(markdown))
  end

  def to_param
    permalink
  end

  def expire_cache
    Rails.cache.delete_matched("*chapters/#{id}")
  end

end


text:
var SWING_MARGIN_PCT    = 6;
var POLL_DEFAULT_MARGIN = 4;

// bahhh how does Math not have sign builtin?
_sign = function(x) {
  if (x < 0) return -1;
  if (x > 0) return  1;
  return 0;
}

function flatten(nested) {
  return nested.reduce(function (prev,curr) {
    return prev.concat(curr.values);
  },[]);
}
var internalDateFormat = d3.time.format("%Y-%m-%d");
function getDate(dateString) {
  var dateSplit = dateString.split('-');
  //return new Date(Date.UTC(parseInt(dateSplit[0]),parseInt(dateSplit[1]),parseInt(dateSplit[2]),-2,0,0));
  return internalDateFormat.parse(dateString);
}

// calculates the a-priori type of state (swing / safe, if swing adds the type)
// a safe state has voted the same in the last two election by a margin larger than SWING_MARGIN_PCT
// wikipedia article http://en.wikipedia.org/wiki/Swing_state uses 6 pct as the safe/swing differentiator
function calculateStateApriori(state) {
  if (state[2004][0] == state[2008][0] &&
      state[2004][1][0]-state[2004][1][1] > SWING_MARGIN_PCT &&
      state[2008][1][0]-state[2008][1][1] > SWING_MARGIN_PCT)
    state.apriori = state[2004][0] + ' Safe';
  else
    state.apriori = 'Unknown'; // Swing states have unknown outcomes
}

function calculatePollOutcome(poll) {
  var pollValue = 'Unknown';
  var margin    = poll.margin || POLL_DEFAULT_MARGIN;
  var swing     = Math.abs(poll.results.lead_margin) < margin;
  var winner    = 'Unknown';
  if (poll.results.lead_margin>0)
      winner = 'Republican';
  if (poll.results.lead_margin<0)
      winner = 'Democratic';
  if (winner != 'Unknown') {
      pollValue = winner;
      if (swing)
          pollValue += ' Swing';
      else
          pollValue += ' Safe';
  }
  poll.outcome = pollValue;
}

// TODO: need to use finish using preferences to choose polls
function choosePoll(polls) {
  var allpolls      = polls.reduce(function (prev,curr) {
    return prev.concat(curr);
  },[]);
  // stores all removed polls
  var removedpolls  = [];
  var avgpolls      = [];

  // choose by voter type
  var nestedByVoterType = d3.nest().key(function (d) {return d.votertype;})
                                   .entries(allpolls);
  var nestedallpolls=nestedByVoterType.filter(function (pollgrp) {
    var result = preferences.votertypes.use[pollgrp.key];
    if (!result) {
      removedpolls.concat(pollgrp.values);
    }
    return result;
  });

  // need to choose or average
  // if (nestedallpolls.length>1) {
  //   var choicepref = preferences.votertypes.choice;
  //   if (choicepref == 'RV') {
  //     delete nestedallpolls['LV'];
  //   }
  //   if (choicepref == 'LV') {
  //     delete nestedallpolls['RV'];
  //   }
  // }
  // flatten remaining polls
  var polllist = nestedallpolls.reduce(function (prev,curr) {
    return prev.concat(curr.values);
  },[]);

  if (polllist.length>1) {
    avgpolls=polllist;
    var avglead   = d3.mean(polllist,function(poll) {return poll.results.lead_margin;});
    var aggerror  = d3.round(
                      Math.sqrt(
                        d3.sum(polllist,
                          function(poll) {
                            return Math.pow(poll.margin,2);
                          })
                        ),2);
    allpolls = [{ margin:aggerror,
                  toDate:polllist[0].toDate,
                  results:{
                    democrat:polllist[0].results.democrat,
                    republican:polllist[0].results.republican,
                    lead_margin:avglead}}];
  } else {
    allpolls = polllist;
  }
  if (removedpolls.length>1) {
  }
  if (avgpolls.length>1) {
  }
  return allpolls.slice(preferences.polltype)[0];
}

// some states have multiple polls ending on the same day
// sometimes these polls have different sampling types
// - Registered Voters (RV) vs Likely Voters (LV)
// - Different pollers (e.g. Rasmussen vs Gallup)
// if they have different outcomes, we should choose one (since each outcome has it's own bucket)
function processPolls(stateData) {
  var nestedByEndDay  = d3.nest()
                          .key(function (poll) {return poll.toDate;})
                          .entries(stateData.polls);
  nestedByEndDay.forEach(function(polledday) {
    polledday.result = choosePoll(polledday.values);
    if(polledday.result != undefined) {
      calculatePollOutcome(polledday.result);
    }
  });
  return nestedByEndDay
          .filter(function (dayData) {return dayData.result != undefined})
          .map(function (dayData) {return dayData.result})
          .sort(function (poll1,poll2) {
            return _sign(poll1.toDate-poll2.toDate);
          });
}

function extendLastPoll(polls,enddate) {
  var lastPollResult = polls.slice(-1)[0];

  interpolated_range = d3.time.day.range(d3.time.day.offset(lastPollResult.date,1),enddate)
                                  .map(function(d) {
                                        return {state:lastPollResult.state,
                                                date:d,
                                                value:lastPollResult.value,
                                                outcome:lastPollResult.outcome};}
                                      );
  return polls.concat(interpolated_range)
}

// generate a timeline from jan 1st until the current day of predicted state outcome for a state
function generateDaily(stateData) {
  calculateStateApriori(stateData);
  var processedPolls = processPolls(stateData);
  dailyData = processedPolls.reduce(function (previousResults,currentPoll) {
      var lastPollResult = previousResults.slice(-1)[0];

      var pollDate = currentPoll.toDate;
      var pollOutcome = currentPoll.outcome;

      var newResult = extendLastPoll(previousResults,pollDate);
      newResult.push({state:stateData.name,date:pollDate,
                      outcome:pollOutcome,value:stateData.votes});

      return newResult;
  },[{state:stateData.name,date:getDate('2012-01-01'),
      outcome:stateData.apriori,value:stateData.votes}])
  return extendLastPoll(dailyData,new Date());
}

// generate the timelines of all states
function generateStateData() {
  return window.data.concat(window.UNKNOWN_STATES).map(function (state) {return generateDaily(state);});
}

// aggregate by category from the state timelines
function generateCategoryData() {
  var dataByState           = generateStateData();
  var flattenedPollResults  = dataByState.reduce(function (previousStates,currentState) {
    return previousStates.concat(currentState);
  },[]);
  var nestedByPollDayResult = d3.nest()
                                .key(function (poll) { return poll.outcome;})
                                .key(function (poll) { return poll.date;})
                                .entries(flattenedPollResults);
  nestedByPollDayResult.forEach(function (outcome) {
    // calculate total for each day
    outcome.values.forEach(function (outComeDay) {
      outComeDay.value = outComeDay.values.reduce(function (previous,current) {
                                                    return previous+current.value;
                                                  },0);
    });

    // fill in missing days
    //  step 1: sort
    outcome.values.sort(function (day1,day2) {
      return _sign((new Date(day1.key)) - (new Date(day2.key)));
    });

    //  step 2: fill in the blanks
    outcome.values = outcome.values.reduce(
      function (prev,curr) {
        var last = prev.slice(-1)[0];
        curr['date'] = new Date(curr.key);
        curr['key']=outcome.key;
        var interpolated_blank = d3.time.days( d3.time.day.offset(
                                                  new Date(last.date),1),
                                               new Date(curr.date))
                                        .map(function (d) {
                                            return {key:outcome.key,
                                                    date:d,
                                                    value:0};
                                          });
        var newprevious = prev.concat(interpolated_blank);
        newprevious.push(curr);
        return newprevious;
    },[{date:getDate("2011-12-31"),value:0,key:outcome.key}]).splice(1);

    // pad the end
    var last = outcome.values.slice(-1)[0];
    var lastDate = last.date;
    var today = new Date();
    var interpolated_end = d3.time.days(d3.time.day.offset(lastDate,1),
                                        d3.time.day.offset(today,-1))
                                  .map(function (d) {
                                    return {date:d,
                                            value:0,
                                            key:outcome.key};
                                  });
    outcome.values = outcome.values.concat(interpolated_end);
    outcome.values = outcome.values.slice(0,
      d3.time.days(getDate("2012-01-01"),
                   d3.time.day.offset(today,-1)).length);
  });
  return nestedByPollDayResult;
}

stack = d3.layout.stack()
    .offset("zero")
    .values(function(d) { return d.values; })
    .x(function(d) { return d.date; })
    .y(function(d) { return d.value; });

function calculateData() {
  sdata = generateCategoryData();
  var sortorder   = { 'Republican Safe':5,
                      'Republican Swing':4,
                      'Unknown':3,
                      'Democratic Swing':2,
                      'Democratic Safe':1
                    };
  for (var datatype in sortorder) {
    if (sdata.filter(function (d) {return d.key==datatype;}).length==0) {
      var newarray = {};
      newarray.key = datatype;
      newarray.values = sdata[0].values.map(function (el) {
        return {date:el.date,key:datatype,value:0};
      });
      sdata.push(newarray);
    }
  }
  sdata.sort(function (l,r) {
    return _sign(sortorder[l.key]-sortorder[r.key]);
  });

  fdata = flatten(sdata);
  layers = stack(sdata);

}

function getLVRVuseprefs() {
  preferences.votertypes.use.RV = document.getElementById("LVRV_RV").checked;
  preferences.votertypes.use.LV = document.getElementById("LVRV_LV").checked;
  preferences.votertypes.use.UK = document.getElementById("LVRV_UK").checked;
}

function LVRVuse(choicetype) {
  getLVRVuseprefs();
  transition();
}

function LVRVchoice(choicetype) {
  preferences.votertypes.choice=choicetype;
  transition();
}

function transition() {
  duration = 1500;
  calculateData();
  d3.selectAll(".layer")
  .data(layers)
  .transition()
  .duration(duration)
  .attr("d",function(d) { return area(d.values);})
  .attr("fill", function (d, i) { return z(i); });
}


text:
Transaction Flow
================

This document outlines the transactional mechanics that take place during a standard asset
exchange.  The scenario includes two clients, A and B, who are buying and selling
radishes.  They each have a peer on the network through which they send their
transactions and interact with the ledger.

.. image:: images/step0.png

**Assumptions**

This flow assumes that a channel is set up and running.  The application user
has registered and enrolled with the organization's certificate authority (CA)
and received back necessary cryptographic material, which is used to authenticate
to the network.

The chaincode (containing a set of key value pairs representing the initial
state of the radish market) is installed on the peers and instantiated on the
channel.  The chaincode contains logic defining a set of transaction
instructions and the agreed upon price for a radish. An endorsement policy has
also been set for this chaincode, stating that both ``peerA`` and ``peerB`` must endorse
any transaction.

.. image:: images/step1.png

1. **Client A initiates a transaction**

What's happening? - Client A is sending a request to purchase radishes.  The
request targets ``peerA`` and ``peerB``, who are respectively representative of
Client A and Client B. The endorsement policy states that both peers must endorse
any transaction, therefore the request goes to ``peerA`` and ``peerB``.

Next, the transaction proposal is constructed.  An application leveraging a supported
SDK (Node, Java, Python) utilizes one of the available API's which generates a
transaction proposal.  The proposal is a request to invoke a chaincode function
so that data can be read and/or written to the ledger (i.e. write new key value
pairs for the assets).  The SDK serves as a shim to package the transaction proposal
into the properly architected format (protocol buffer over gRPC) and takes the user's
cryptographic credentials to produce a unique signature for this transaction proposal.

.. image:: images/step2.png

2. **Endorsing peers verify signature & execute the transaction**

The endorsing peers verify (1) that the transaction proposal is well formed,
(2) it has not been submitted already in the past (replay-attack protection),
(3) the signature is valid (using MSP), and (4) that the
submitter (Client A, in the example) is properly authorized to perform
the proposed operation on that channel (namely, each endorsing peer ensures that
the submitter satisfies the channel's *Writers* policy).
The endorsing peers take the transaction proposal inputs as
arguments to the invoked chaincode's function. The chaincode is then
executed against the current state database to produce transaction
results including a response value, read set, and write set.  No updates are
made to the ledger at this point. The set of these values, along with the
endorsing peer's signature and a YES/NO endorsement statement is passed back as
a "proposal response" to the SDK which parses the payload for the application to
consume.

*{The MSP is a peer component that allows them to verify
transaction requests arriving from clients and to sign transaction results(endorsements).
The *Writing* policy is defined at channel creation time, and determines
which user is entitled to submit a transaction to that channel.}*

.. image:: images/step3.png

3. **Proposal responses are inspected**

The application verifies the endorsing peer signatures and compares the proposal
responses (link to glossary term which will contain a representation of the payload)
to determine if the proposal responses are the same and if the specified endorsement
policy has been fulfilled (i.e. did peerA and peerB both endorse).  The architecture
is such that even if an application chooses not to inspect responses or otherwise
forwards an unendorsed transaction, the policy will still be enforced by peers
and upheld at the commit validation phase.

.. image:: images/step4.png

4. **Client assembles endorsements into a transaction**

The application "broadcasts" the transaction proposal and response within a
"transaction message" to the Ordering Service. The transaction will contain the
read/write sets, the endorsing peers signatures and the Channel ID.  The
Ordering Service does not need to inspect the entire content of a transaction in order to perform
its operation, it simply receives
transactions from all channels in the network, orders them chronologically by
channel, and creates blocks of transactions per channel.

.. image:: images/step5.png

5. **Transaction is validated and committed**

The blocks of transactions are "delivered" to all peers on the channel.  The
transactions within the block are validated to ensure endorsement policy is
fulfilled and to ensure that there have been no changes to ledger state for read
set variables since the read set was generated by the transaction execution.
Transactions in the block are tagged as being valid or invalid.

.. image:: images/step6.png

6. **Ledger updated**

Each peer appends the block to the channel's chain, and for each valid transaction
the write sets are committed to current state database. An event is emitted, to
notify the client application that the transaction (invocation) has been
immutably appended to the chain, as well as notification of whether the
transaction was validated or invalidated.

**Note**: See the :ref:`swimlane` diagram to better understand the server side flow and the
protobuffers.

.. Licensed under Creative Commons Attribution 4.0 International License
   https://creativecommons.org/licenses/by/4.0/


text:
layout: default
title: Deployment
nav_order: 5
has_children: true
---

# Deployment


text:
package logging

import (
	"testing"
	"time"

	"github.com/stretchr/testify/require"
)

type counter int

func (c *counter) Log(keyvals ...interface{}) error {
	(*c)++
	return nil
}

func TestDedupe(t *testing.T) {
	var c counter
	d := Dedupe(&c, 100*time.Millisecond)
	defer d.Stop()

	// Log 10 times quickly, ensure they are deduped.
	for i := 0; i < 10; i++ {
		err := d.Log("msg", "hello")
		require.NoError(t, err)
	}
	require.Equal(t, 1, int(c))

	// Wait, then log again, make sure it is logged.
	time.Sleep(200 * time.Millisecond)
	err := d.Log("msg", "hello")
	require.NoError(t, err)
	require.Equal(t, 2, int(c))
}


text:
#include "hmac_sha1.h"

#include <string.h>
#include <stdlib.h>

#define IPAD (unsigned char)0x36
#define OPAD (unsigned char)0x5c

/* HMAC-SHA-1 functions */
void sha1(const unsigned char *message, unsigned int len, unsigned char *digest) {
    Sha1Context ctx;
    SHA1_HASH   hash;

    // uint8_t buffer_msg[len];
    uint8_t *buffer_msg = (uint8_t *)malloc(len);
    memcpy(buffer_msg, message, len);

    Sha1Initialise(&ctx);
    Sha1Update(&ctx, buffer_msg, len);
    free(buffer_msg);
    Sha1Finalise(&ctx, &hash);

    memcpy(digest, hash.bytes, SHA1_HASH_SIZE);
}

void hmac_sha1_init(hmac_sha1_ctx *ctx, const unsigned char *key, unsigned int key_size) {
    unsigned int fill;
    unsigned int num;

    const unsigned char *key_used;
    unsigned char key_temp[SHA1_DIGEST_SIZE];
    int i;

    if (key_size == SHA1_BLOCK_SIZE) {
        key_used = key;
        num = SHA1_BLOCK_SIZE;
    } else {
        if (key_size > SHA1_BLOCK_SIZE){
            num = SHA1_DIGEST_SIZE;
            sha1(key, key_size, key_temp);
            key_used = key_temp;
        } else { /* key_size > sha1_BLOCK_SIZE */
            key_used = key;
            num = key_size;
        }
        fill = SHA1_BLOCK_SIZE - num;

        memset(ctx->block_ipad + num, IPAD, fill);
        memset(ctx->block_opad + num, OPAD, fill);
    }

    for (i = 0; i < (int) num; i++) {
        ctx->block_ipad[i] = key_used[i] ^ IPAD;
        ctx->block_opad[i] = key_used[i] ^ OPAD;
    }

    Sha1Initialise(&ctx->ctx_inside);
    Sha1Update(&ctx->ctx_inside, ctx->block_ipad, SHA1_BLOCK_SIZE);

    Sha1Initialise(&ctx->ctx_outside);
    Sha1Update(&ctx->ctx_outside, ctx->block_opad,
            SHA1_BLOCK_SIZE);

    /* for hmac_reinit */
    memcpy(&ctx->ctx_inside_reinit, &ctx->ctx_inside,
            sizeof(Sha1Context));
    memcpy(&ctx->ctx_outside_reinit, &ctx->ctx_outside,
            sizeof(Sha1Context));
}

void hmac_sha1_reinit(hmac_sha1_ctx *ctx) {
    memcpy(&ctx->ctx_inside, &ctx->ctx_inside_reinit,
            sizeof(Sha1Context));
    memcpy(&ctx->ctx_outside, &ctx->ctx_outside_reinit,
            sizeof(Sha1Context));
}

void hmac_sha1_update(hmac_sha1_ctx *ctx, const unsigned char *message,
        unsigned int message_len) {
    Sha1Update(&ctx->ctx_inside, message, message_len);
}

void hmac_sha1_final(hmac_sha1_ctx *ctx, unsigned char *mac,
        unsigned int mac_size) {
    SHA1_HASH digest_inside;
    SHA1_HASH mac_temp;

    Sha1Finalise(&ctx->ctx_inside, &digest_inside);
    Sha1Update(&ctx->ctx_outside, digest_inside.bytes, SHA1_DIGEST_SIZE);
    Sha1Finalise(&ctx->ctx_outside, &mac_temp);
    memcpy(mac, mac_temp.bytes, mac_size);
}

void hmac_sha1(const unsigned char *key,     unsigned int key_size,
               const unsigned char *message, unsigned int message_len,
                     unsigned char *mac,     unsigned     mac_size) {
    hmac_sha1_ctx ctx;

    hmac_sha1_init(&ctx, key, key_size);
    hmac_sha1_update(&ctx, message, message_len);
    hmac_sha1_final(&ctx, mac, mac_size);
}


text:
<?php

namespace Alpha\Controller;

use Alpha\Exception\ResourceNotFoundException;
use Alpha\Exception\IllegalArguementException;
use Alpha\View\Widget\Image;
use Alpha\Util\Config\ConfigProvider;
use Alpha\Util\Logging\Logger;
use Alpha\Util\Http\Request;
use Alpha\Util\Http\Response;
use Alpha\Model\Type\Boolean;

class ImageController extends Controller implements ControllerInterface
{
    /**
     * Trace logger.
     *
     * @var \Alpha\Util\Logging\Logger
     *
     * @since 1.0
     */
    private static $logger = null;

    /**
     * Constructor.
     *
     * @param string $visibility The name of the rights group that can access this controller.
     *
     * @since 1.0
     */
    public function __construct(string $visibility = 'Public')
    {
        self::$logger = new Logger('ImageController');
        self::$logger->debug('>>__construct()');

        // ensure that the super class constructor is called, indicating the rights group
        parent::__construct($visibility);

        self::$logger->debug('<<__construct');
    }

    /**
     * Handles get requests.
     *
     * @param \Alpha\Util\Http\Request $request
     *
     * @since 1.0
     *
     * @throws \Alpha\Exception\ResourceNotFoundException
     * @throws \Alpha\Exception\ResourceNotAllowedException
     */
    public function doGet(\Alpha\Util\Http\Request $request): \Alpha\Util\Http\Response
    {
        self::$logger->debug('>>doGet(request=['.var_export($request, true).'])');

        $config = ConfigProvider::getInstance();

        $params = $request->getParams();

        try {
            $imgSource = urldecode($params['source']);
            $imgWidth = $params['width'];
            $imgHeight = $params['height'];
            $imgType = $params['type'];
            $imgQuality = (float)$params['quality'];
            $imgScale = new Boolean($params['scale']);
            $imgSecure = new Boolean($params['secure']);
        } catch (\Exception $e) {
            self::$logger->error('Required param missing for ImageController controller['.$e->getMessage().']');
            throw new ResourceNotFoundException('File not found');
        }

        $modified = filemtime($imgSource);

        $responseHeaders = array();

        $responseHeaders['Last-Modified'] = date('D, d M Y H:i:s', $modified).' GMT';
        $responseHeaders['Cache-Control'] = 'max-age=1800';

        // exit if not modified
        if ($request->getHeader('If-Modified-Since') != null) {
            if (strtotime($request->getHeader('If-Modified-Since')) == $modified) {
                return new Response(304, '', $responseHeaders);
            }
        }

        // handle secure tokens
        if ($imgSecure->getBooleanValue() && $config->get('cms.images.widget.secure')) {
            $valid = $this->checkSecurityFields();

            // if not valid, just return a blank black image of the same dimensions
            if (!$valid) {
                $im = imagecreatetruecolor($imgWidth, $imgHeight);
                $bgc = imagecolorallocate($im, 0, 0, 0);
                imagefilledrectangle($im, 0, 0, $imgWidth, $imgHeight, $bgc);

                if (pathinfo($imgSource)['extension'] == 'png' && $config->get('cms.images.perserve.png')) {
                    ob_start();
                    imagepng($im);
                    $body = ob_get_contents();
                    $contentType = 'image/png';
                    ob_end_clean();
                } else {
                    ob_start();
                    imagejpeg($im);
                    $body = ob_get_contents();
                    $contentType = 'image/jpeg';
                    ob_end_clean();
                }

                imagedestroy($im);

                self::$logger->warn('The client ['.$request->getUserAgent().'] was blocked from accessing the file ['.$imgSource.'] due to bad security tokens being provided');

                $responseHeaders['Content-Type'] = $contentType;

                return new Response(200, $body, $responseHeaders);
            }
        }

        try {
            $image = new Image($imgSource, $imgWidth, $imgHeight, $imgType, $imgQuality, $imgScale->getBooleanValue(), $imgSecure->getBooleanValue());
            ob_start();
            $image->renderImage();
            $body = ob_get_contents();
            ob_end_clean();
        } catch (IllegalArguementException $e) {
            self::$logger->error($e->getMessage());
            throw new ResourceNotFoundException('File not found');
        }

        self::$logger->debug('<<__doGet');

        if ($imgSource == 'png' && $config->get('cms.images.perserve.png')) {
            $responseHeaders['Content-Type'] = 'image/png';
        } else {
            $responseHeaders['Content-Type'] = 'image/jpeg';
        }

        return new Response(200, $body, $responseHeaders);
    }
}


text:
//
//  ProvinceCityViewController.m
//  市-简称+车牌两级联动
//
//  Created by 樊志远 on 16/3/24.
//  Copyright © 2016年 fzy. All rights reserved.
//

#import "ProvinceCityViewController.h"
#import "DBTool.h"
#import "ProvinceItem.h"
#import "CityViewController.h"

@interface ProvinceCityViewController ()

/** <#注释#> */
@property (nonatomic , strong) NSArray *provinceArr;

@end

@implementation ProvinceCityViewController

- (NSArray *)provinceArr
{
    if (!_provinceArr) {
        DBTool *dbTool = [[DBTool alloc] init];
        NSArray *provinceArr = [dbTool getProvinceList];
        _provinceArr = [NSArray arrayWithArray:provinceArr];
    }
    return _provinceArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"省份";
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.provinceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellID = @"province";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }

    ProvinceItem *pItem = self.provinceArr[indexPath.row];

    cell.textLabel.text = pItem.ProvinceName;

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ProvinceItem *pItem = self.provinceArr[indexPath.row];

    CityViewController *cityVC = [[CityViewController alloc] init];
    cityVC.ProvinceID = pItem.ProvinceID;

    [self.navigationController pushViewController:cityVC animated:YES];
}

@end


text:
import styled from 'styled-components';
import {
	compose,
	space,
	color,
	border,
	shadow,
	layout,
	position,
	SpaceProps,
	ColorProps,
	BorderProps,
	ShadowProps,
	LayoutProps,
	PositionProps,
} from 'styled-system';
import { getPaddingX } from '../styles/getters';

type Props = SpaceProps &
	ColorProps &
	BorderProps &
	ShadowProps &
	LayoutProps &
	PositionProps & {
		expand?: boolean;
	};

/**
 * Responsive image.
 */
export const Image = styled.img<Props>(
	{
		maxWidth: '100%',
		height: 'auto',
	},
	(p) =>
		p.expand && {
			[`@media (max-width: ${p.theme.breakpoints[0]})`]: {
				maxWidth: '100vw',
				marginLeft: `-${getPaddingX(p)}`,
				marginRight: `-${getPaddingX(p)}`,
			},
		},
	compose(space, color, border, shadow, layout, position)
);

Image.defaultProps = {
	alt: '',
	/** Make the image full bleed on narrow screens */
	expand: true,
};

export default Image;


text:
"use strict";

describe("slugify-filter", function() {
    beforeEach(module("slugifier"));

    it("should slugify passed in text", inject(function(slugifyFilter) {
        expect(slugifyFilter("My First Slug")).toBe("my-first-slug");
    }));
});


text:
Project: /_project.yaml
Book: /_book.yaml

# Bazel Tutorial: Build a C++ Project

This tutorial covers the basics of building C++ applications with
Bazel. You will set up your workspace and build a simple C++ project that
illustrates key Bazel concepts, such as targets and `BUILD` files. After
completing this tutorial, take a look at
[Common C++ Build Use Cases](/tutorials/cpp-use-cases) for information on more advanced
concepts such as writing and running C++ tests.

Estimated completion time: 30 minutes.

## What you'll learn

In this tutorial you learn how to:

*  Build a target
*  Visualize the project's dependencies
*  Split the project into multiple targets and packages
*  Control target visibility across packages
*  Reference targets through labels

## Before you begin

To prepare for the tutorial, first [Install Bazel](/install) if
you don't have it installed already. Then, retrieve the sample project from
Bazel's GitHub repository:

```
git clone https://github.com/bazelbuild/examples
```

The sample project for this tutorial is in the `examples/cpp-tutorial` directory
and is structured as follows:

```
examples
└── cpp-tutorial
    ├──stage1
    │  ├── main
    │  │   ├── BUILD
    │  │   └── hello-world.cc
    │  └── WORKSPACE
    ├──stage2
    │  ├── main
    │  │   ├── BUILD
    │  │   ├── hello-world.cc
    │  │   ├── hello-greet.cc
    │  │   └── hello-greet.h
    │  └── WORKSPACE
    └──stage3
       ├── main
       │   ├── BUILD
       │   ├── hello-world.cc
       │   ├── hello-greet.cc
       │   └── hello-greet.h
       ├── lib
       │   ├── BUILD
       │   ├── hello-time.cc
       │   └── hello-time.h
       └── WORKSPACE
```

As you can see, there are three sets of files, each set representing a stage in
this tutorial. In the first stage, you will build a single target residing in a
single package. In the second stage, you will split your project into multiple
targets but keep it in a single package. In the third and final stage, you will
split your project into multiple packages and build it with multiple targets.

## Build with Bazel

### Set up the workspace

Before you can build a project, you need to set up its workspace. A workspace is
a directory that holds your project's source files and Bazel's build outputs. It
also contains files that Bazel recognizes as special:

*  The `WORKSPACE` file, which identifies the directory and its contents as a
   Bazel workspace and lives at the root of the project's directory structure,

*  One or more `BUILD` files, which tell Bazel how to build different parts of
   the project. (A directory within the workspace that contains a `BUILD` file
   is a *package*. You will learn about packages later in this tutorial.)

To designate a directory as a Bazel workspace, create an empty file named
`WORKSPACE` in that directory.

When Bazel builds the project, all inputs and dependencies must be in the same
workspace. Files residing in different workspaces are independent of one
another unless linked, which is beyond the scope of this tutorial.

### Understand the BUILD file

A `BUILD` file contains several different types of instructions for Bazel.
The most important type is the *build rule*, which tells Bazel how to build the
desired outputs, such as executable binaries or libraries. Each instance
of a build rule in the `BUILD` file is called a *target* and points to a
specific set of source files and dependencies. A target can also point to other
targets.

Take a look at the `BUILD` file in the `cpp-tutorial/stage1/main` directory:

```python
cc_binary(
    name = "hello-world",
    srcs = ["hello-world.cc"],
)
```

In our example, the `hello-world` target instantiates Bazel's built-in
[`cc_binary` rule](/reference/be/c-cpp#cc_binary). The rule tells Bazel to build
a self-contained executable binary from the `hello-world.cc` source file with no
dependencies.

The attributes in the target explicitly state its dependencies and options.
While the `name` attribute is mandatory, many are optional. For example, in the
`hello-world` target, `name` is required and self-explanatory, and `srcs` is
optional and specifies the source file(s) from which Bazel builds the target.

### Build the project

To build your sample project, navigate to the `cpp-tutorial/stage1` directory
and run:

```
bazel build //main:hello-world
```

In the target label, the `//main:` part is the location of the `BUILD`
file relative to the root of the workspace, and `hello-world` is the target
name in the `BUILD` file. (You will learn about target labels in more
detail at the end of this tutorial.)

Bazel produces output similar to the following:

```
INFO: Found 1 target...
Target //main:hello-world up-to-date:
  bazel-bin/main/hello-world
INFO: Elapsed time: 2.267s, Critical Path: 0.25s
```

Congratulations, you just built your first Bazel target! Bazel places build
outputs in the `bazel-bin` directory at the root of the workspace. Browse
through its contents to get an idea for Bazel's output structure.

Now test your freshly built binary:

```sh
bazel-bin/main/hello-world
```

### Review the dependency graph

A successful build has all of its dependencies explicitly stated in the `BUILD`
file. Bazel uses those statements to create the project's dependency graph,
which enables accurate incremental builds.

To visualize the sample project's dependencies, you can generate a text
representation of the dependency graph by running this command at the
workspace root:

```
bazel query --notool_deps --noimplicit_deps "deps(//main:hello-world)" \
  --output graph
```

The above command tells Bazel to look for all dependencies for the target
`//main:hello-world` (excluding host and implicit dependencies) and format the
output as a graph.

Then, paste the text into [GraphViz](http://www.webgraphviz.com/).

On Ubuntu, you can view the graph locally by installing GraphViz and the xdot
Dot Viewer:

```
sudo apt update && sudo apt install graphviz xdot
```

Then you can generate and view the graph by piping the text output above
straight to xdot:

```
xdot <(bazel query --notool_deps --noimplicit_deps "deps(//main:hello-world)" \
  --output graph)
```

As you can see, the first stage of the sample project has a single target
that builds a single source file with no additional dependencies:

![Dependency graph for 'hello-world'](/docs/images/cpp-tutorial-stage1.png "Dependency graph")

**Figure 1.** Dependency graph for `hello-world` displays a single target with a single
source file.

After you set up your workspace, build your project, and examine its
dependencies, then you can add some complexity.

## Refine your Bazel build

While a single target is sufficient for small projects, you may want to split
larger projects into multiple targets and packages to allow for fast incremental
builds (that is, only rebuild what's changed) and to speed up your builds by
building multiple parts of a project at once.

### Specify multiple build targets

You can split the sample project build into two targets. Take a look at the
`BUILD` file in the `cpp-tutorial/stage2/main` directory:

```python
cc_library(
    name = "hello-greet",
    srcs = ["hello-greet.cc"],
    hdrs = ["hello-greet.h"],
)

cc_binary(
    name = "hello-world",
    srcs = ["hello-world.cc"],
    deps = [
        ":hello-greet",
    ],
)
```

With this `BUILD` file, Bazel first builds the `hello-greet` library
(using Bazel's built-in [`cc_library` rule](/reference/be/c-cpp#cc_library)),
then the `hello-world` binary. The `deps` attribute in the `hello-world` target
tells Bazel that the `hello-greet` library is required to build the `hello-world`
binary.

Next, build this new version of the project. Change into the
`cpp-tutorial/stage2` directory and run the following command:

```
bazel build //main:hello-world
```

Bazel produces output similar to the following:

```
INFO: Found 1 target...
Target //main:hello-world up-to-date:
  bazel-bin/main/hello-world
INFO: Elapsed time: 2.399s, Critical Path: 0.30s
```

Now test your freshly built binary:

```
bazel-bin/main/hello-world
```

If you now modify `hello-greet.cc` and rebuild the project, Bazel will
only recompile that file.

Looking at the dependency graph, you can see that `hello-world` depends on the
same inputs as it did before, but the structure of the build is different:

![Dependency graph for 'hello-world'](/docs/images/cpp-tutorial-stage2.png "Dependency graph")

**Figure 2.** Dependency graph for `hello-world` displays structure changes after
modification to the file.

You've now built the project with two targets. The `hello-world` target builds
one source file and depends on one other target (`//main:hello-greet`), which
builds two additional source files.

### Use multiple packages

You can split the project into multiple packages. Take a look at the contents
of the `cpp-tutorial/stage3` directory:

```
└──stage3
   ├── main
   │   ├── BUILD
   │   ├── hello-world.cc
   │   ├── hello-greet.cc
   │   └── hello-greet.h
   ├── lib
   │   ├── BUILD
   │   ├── hello-time.cc
   │   └── hello-time.h
   └── WORKSPACE
```
Notice that now there are two sub-directories, and each contains a `BUILD`
file. Therefore, to Bazel, the workspace now contains two packages,
`lib` and `main`.

Take a look at the `lib/BUILD` file:

```python
cc_library(
    name = "hello-time",
    srcs = ["hello-time.cc"],
    hdrs = ["hello-time.h"],
    visibility = ["//main:__pkg__"],
)
```

And at the `main/BUILD` file:

```python
cc_library(
    name = "hello-greet",
    srcs = ["hello-greet.cc"],
    hdrs = ["hello-greet.h"],
)

cc_binary(
    name = "hello-world",
    srcs = ["hello-world.cc"],
    deps = [
        ":hello-greet",
        "//lib:hello-time",
    ],
)
```

As you can see, the `hello-world` target in the `main` package depends on the
`hello-time` target in the `lib` package (hence the target label
`//lib:hello-time`) - Bazel knows this through the `deps` attribute. Take a look
at the dependency graph:

![Dependency graph for 'hello-world'](/docs/images/cpp-tutorial-stage3.png "Dependency graph")

**Figure 3.** Dependency graph for `hello-world`displays how the target in the
main package depends on the target in the lib package.

Notice that for the build to succeed, you make the `//lib:hello-time` target in
`lib/BUILD` explicitly visible to targets in `main/BUILD` using the `visibility`
attribute. This is because by default targets are only visible to other targets
in the same `BUILD` file. (Bazel uses target visibility to prevent issues such
as libraries containing implementation details leaking into public APIs.)

Next you can build this final version of the project. Change into the
`cpp-tutorial/stage3` directory and run the following command:

```
bazel build //main:hello-world
```

Bazel produces output similar to the following:

```
INFO: Found 1 target...
Target //main:hello-world up-to-date:
  bazel-bin/main/hello-world
INFO: Elapsed time: 0.167s, Critical Path: 0.00s
```

Now test the freshly built binary:

```
bazel-bin/main/hello-world
```

You've now built the project as two packages with three targets and understand
the dependencies between them.

## Use labels to reference targets

In `BUILD` files and at the command line, Bazel uses *labels* to reference
targets - for example, `//main:hello-world` or `//lib:hello-time`. Their syntax
is:

```
//path/to/package:target-name
```

If the target is a rule target, then `path/to/package` is the path from the
workspace root (the directory containing the `WORKSPACE` file) to the directory
containing the `BUILD` file, and `target-name` is what you named the target
in the `BUILD` file (the `name` attribute). If the target is a file target,
then `path/to/package` is the path to the root of the package, and
`target-name` is the name of the target file, including its full
path relative to the root of the package (the directory containing the
package's `BUILD` file).

When referencing targets at the repository root, the package path is empty,
just use `//:target-name`. When referencing targets within the same `BUILD`
file, you can even skip the `//` workspace root identifier and just use
`:target-name`.

## Further reading

Congratulations! You now know the basics of building a C++ project with Bazel.
Next, read up on the most common [C++ build use cases](/tutorials/cpp-use-cases).

For more details, see:

*  [External Dependencies](/docs/external) to learn more about working with
   local and remote repositories.

*  The [other rules](/rules) to learn more about Bazel.

*  The [Java build tutorial](/tutorials/java) to get started with
   building Java applications with Bazel.

*  The [Android application tutorial](/tutorials/android-app) to get started with
   building mobile applications for Android with Bazel.

*  The [iOS application tutorial](/tutorials/ios-app) to get started with
   building mobile applications for iOS with Bazel.

Happy building!


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>Alpaca Forms Source: fields/advanced/StateField.js</title>

	<link type="text/css" rel="stylesheet" href="styles/sunlight.default.css">

	<link type="text/css" rel="stylesheet" href="styles/site.cerulean.css">

		Alpaca Forms

				Namespaces

Namespace for all Alpaca Connector Class Implementations.

Namespace for all Alpaca Field Class Implementations.

				Classes

Alpaca.Connector

Alpaca.Field

Alpaca.Fields.CurrencyField

Alpaca.Fields.UploadField

Alpaca.Form

Alpaca.NormalizedView

Alpaca.RuntimeView

				Global

compile

doCompile

doExecute

execute

fileExtension

findCacheKeys

isCached

onDependencyChange

subscribe

supportedMimetypes

Source: fields/advanced/StateField.js

Source: fields/advanced/StateField.js

(function($) {

    var Alpaca = $.alpaca;

    Alpaca.usHoldings = {};

    Alpaca.usHoldings.territories = {
        "American Samoa"                 : "AS",
        "District Of Columbia"           : "DC",
        "Federated States Of Micronesia" : "FM",
        "Guam"                           : "GU",
        "Marshall Islands"               : "MH",
        "Northern Mariana Islands"       : "MP",
        "Palau"                          : "PW",
        "Puerto Rico"                    : "PR",
        "Virgin Islands"                 : "VI"
    };

    Alpaca.usHoldings.states =  {
        "Alabama"                        : "AL",
        "Alaska"                         : "AK",
        "Arizona"                        : "AZ",
        "Arkansas"                       : "AR",
        "California"                     : "CA",
        "Colorado"                       : "CO",
        "Connecticut"                    : "CT",
        "Delaware"                       : "DE",
        "Florida"                        : "FL",
        "Georgia"                        : "GA",
        "Hawaii"                         : "HI",
        "Idaho"                          : "ID",
        "Illinois"                       : "IL",
        "Indiana"                        : "IN",
        "Iowa"                           : "IA",
        "Kansas"                         : "KS",
        "Kentucky"                       : "KY",
        "Louisiana"                      : "LA",
        "Maine"                          : "ME",
        "Maryland"                       : "MD",
        "Massachusetts"                  : "MA",
        "Michigan"                       : "MI",
        "Minnesota"                      : "MN",
        "Mississippi"                    : "MS",
        "Missouri"                       : "MO",
        "Montana"                        : "MT",
        "Nebraska"                       : "NE",
        "Nevada"                         : "NV",
        "New Hampshire"                  : "NH",
        "New Jersey"                     : "NJ",
        "New Mexico"                     : "NM",
        "New York"                       : "NY",
        "North Carolina"                 : "NC",
        "North Dakota"                   : "ND",
        "Ohio"                           : "OH",
        "Oklahoma"                       : "OK",
        "Oregon"                         : "OR",
        "Pennsylvania"                   : "PA",
        "Rhode Island"                   : "RI",
        "South Carolina"                 : "SC",
        "South Dakota"                   : "SD",
        "Tennessee"                      : "TN",
        "Texas"                          : "TX",
        "Utah"                           : "UT",
        "Vermont"                        : "VT",
        "Virginia"                       : "VA",
        "Washington"                     : "WA",
        "West Virginia"                  : "WV",
        "Wisconsin"                      : "WI",
        "Wyoming"                        : "WY"
    };

    Alpaca.Fields.StateField = Alpaca.Fields.SelectField.extend(
    /**
     * @lends Alpaca.Fields.StateField.prototype
     */
    {
        /**
         * @see Alpaca.Fields.TextField#getFieldType
         */
        getFieldType: function() {
            return "state";
        },

        /**
         * @see Alpaca.Fields.TextField#setup
         */
        setup: function()
        {
            // defaults
            if (Alpaca.isUndefined(this.options.capitalize)) {
                this.options.capitalize = false;
            }
            if (Alpaca.isUndefined(this.options.includeStates)) {
                this.options.includeStates = true;
            }
            if (Alpaca.isUndefined(this.options.includeTerritories)) {
                this.options.includeTerritories = true;
            }
            if (Alpaca.isUndefined(this.options.format)) {
                this.options.format = "name";
            }

            // validate settings
            if (this.options.format === "name" || this.options.format === "code")
            {
                // valid formats
            }
            else
            {
                Alpaca.logError("The configured state format: " + this.options.format + " is not a legal value [name, code]");

                // default to name format
                this.options.format = "name";
            }

            // configure
            var holdings = Alpaca.retrieveUSHoldings(
                this.options.includeStates,
                this.options.includeTerritories,
                (this.options.format === "code"),
                this.options.capitalize);

            this.schema["enum"] = holdings.keys;
            this.options.optionLabels = holdings.values;

            this.base();
        }

        /* builder_helpers */
        ,

        /**
         * @see Alpaca.Fields.TextField#getTitle
         */
        getTitle: function() {
            return "State Field";
        },

        /**
         * @see Alpaca.Fields.TextField#getDescription
         */
        getDescription: function() {
            return "Provides a dropdown selector of states and/or territories in the United States, keyed by their two-character code.";
        },

        /**
         * @private
         * @see Alpaca.Fields.TextField#getSchemaOfOptions
         */
        getSchemaOfOptions: function() {

            return Alpaca.merge(this.base(), {
                "properties": {
                    "format": {
                        "title": "Format",
                        "description": "How to represent the state values in the selector",
                        "type": "string",
                        "default": "name",
                        "enum":["name", "code"],
                        "readonly": true
                    },
                    "capitalize": {
                        "title": "Capitalize",
                        "description": "Whether the values should be capitalized",
                        "type": "boolean",
                        "default": false,
                        "readonly": true
                    },
                    "includeStates": {
                        "title": "Include States",
                        "description": "Whether to include the states of the United States",
                        "type": "boolean",
                        "default": true,
                        "readonly": true
                    },
                    "includeTerritories": {
                        "title": "Include Territories",
                        "description": "Whether to include the territories of the United States",
                        "type": "boolean",
                        "default": true,
                        "readonly": true
                    }
                }
            });

        },

        /**
         * @private
         * @see Alpaca.Fields.TextField#getOptionsForOptions
         */
        getOptionsForOptions: function() {
            return Alpaca.merge(this.base(), {
                "fields": {
                    "format": {
                        "type": "text"
                    },
                    "capitalize": {
                        "type": "checkbox"
                    },
                    "includeStates": {
                        "type": "checkbox"
                    },
                    "includeTerritories": {
                        "type": "checkbox"
                    }
                }
            });
        }

        /* end_builder_helpers */
    });

    Alpaca.registerFieldClass("state", Alpaca.Fields.StateField);
    Alpaca.registerDefaultFormatFieldMapping("state", "state");

    /**
     * Helper function to retrieve the holdings of US states and territories.
     *
     * @param {Boolean} includeStates whether to include US states
     * @param {Boolean} includeTerritories whether to include US territories
     * @param {Boolean} codeValue whether to hand back US holding codes (instead of names)
     * @param {Boolean} capitalize whether to capitalize the values handed back
     *
     * @returns {Object} an object containing "keys" and "values", both of which are arrays.
     */
    Alpaca.retrieveUSHoldings = (function()
    {
        return function(includeStates, includeTerritories, codeValue, capitalize) {
            var res  = {
                keys:   [],
                values: []
            };
            var opts = $.extend(
                {},
                includeStates      ? Alpaca.usHoldings.states      : {},
                includeTerritories ? Alpaca.usHoldings.territories : {}
            );
            var sorted = Object.keys(opts);
            sorted.sort();
            for (var i in sorted) {
                var state = sorted[i];
                var key   = opts[state];
                var value = codeValue ? key : state;
                if (capitalize) {
                    value = value.toUpperCase();
                }
                res.keys.push(key);
                res.values.push(value);
            }
            return res;
        };
    })();

})(jQuery);

	Copyright © 2014 Gitana Software, Inc.

	Documentation generated by JSDoc 3.3.2
	on Sat Aug 1st 2015 using the DocStrap template.


text:
class CommentSweeper  < ActionController::Caching::Sweeper
  observe Comment, Identification
  include Shared::SweepersModule

  def after_save(item)
    sweep_comment(item)
    true
  end

  def after_destroy(item)
    sweep_comment(item)
    true
  end

  def sweep_comment(item)
    if item.is_a?(Comment)
      expire_listed_taxon(item.parent) if item.parent.is_a?(ListedTaxon)
    end
  end
end


text:
const fs       = require('fs')
const url      = require('url')
const path     = require('path')
const fetch    = require('node-fetch').default
const uri2path = require('file-uri-to-path')
const data2buf = require('data-uri-to-buffer')
const mime = require('mime-types')
const {expandEnvironmentVariables} = require('../helpers/path')

// TODO: redeuce dep size
const requireg = require('requireg')

const download = (job, settings, asset) => {
    if (asset.type == 'data') return Promise.resolve();

    // eslint-disable-next-line
    const uri = global.URL ? new URL(asset.src) : url.parse(asset.src)
    const protocol = uri.protocol.replace(/:$/, '');
    let destName = '';

    /* if asset doesnt have a file name, make up a random one */
    if (protocol === 'data' && !asset.layerName) {
        destName = Math.random().toString(36).substring(2);
    } else {
        destName = path.basename(asset.src)
        destName = destName.indexOf('?') !== -1 ? destName.slice(0, destName.indexOf('?')) : destName;
        /* ^ remove possible query search string params ^ */
        destName = decodeURI(destName) /* < remove/decode any special URI symbols within filename */

        /* prevent same name file collisions */
        if (fs.existsSync(path.join(job.workpath, destName))) {
            destName = Math.random().toString(36).substring(2) + path.extname(asset.src);
        }
    }

    /* force asset name if it is provided */
    if (asset.name) {
        destName = asset.name
    }

    /* try to guess the extension from data part */
    if (protocol == 'data' && !asset.extension) {
        const databuf = data2buf(asset.src)
        asset.extension = mime.extension(databuf.type) || undefined
    }

    if (asset.extension) {
        destName += '.' + asset.extension
    }

    asset.dest = path.join(job.workpath, destName);

    switch (protocol) {
        /* built-in handlers */
        case 'data':
            return new Promise((resolve, reject) => {
                try {
                    fs.writeFile(
                        asset.dest, data2buf(asset.src),
                        err => err ? reject(err) : resolve()
                    );
                } catch (err) {
                    reject(err)
                }
            });

        case 'http':
        case 'https':
            /* TODO: maybe move to external package ?? */
            const src = decodeURI(asset.src) === asset.src ? encodeURI(asset.src): asset.src
            return fetch(src, asset.params || {})
                .then(res => res.ok ? res : Promise.reject({reason: 'Initial error downloading file', meta: {src, error: res.error}}))
                .then(res => {
                    // Set a file extension based on content-type header if not already set
                    if (!asset.extension) {
                      const contentType = res.headers.get('content-type')
                      const fileExt = mime.extension(contentType) || undefined

                       asset.extension = fileExt
                        const destHasExtension = path.extname(asset.dest) ? true : false
                        //don't do this if asset.dest already has extension else it gives you example.jpg.jpg  like file in case of  assets and aep/aepx file
                        if (asset.extension && !destHasExtension) {
                            asset.dest += `.${fileExt}`
                        }
                    }

                    const stream = fs.createWriteStream(asset.dest)

                    return new Promise((resolve, reject) => {
                        const errorHandler = (error) => {
                            reject(new Error({reason: 'Unable to download file', meta: {src, error}}))
                        };

                        res.body
                            .on('error', errorHandler)
                            .pipe(stream)

                        stream
                            .on('error', errorHandler)
                            .on('finish', resolve)
                    })
                });

        case 'file':
            const filepath = uri2path(expandEnvironmentVariables(asset.src))

            /* add override to use original asset from fs */
            if (asset.useOriginal) {
                asset.dest = filepath
                return Promise.resolve()
            }

            /* plain asset stream copy */
            const rd = fs.createReadStream(filepath)
            const wr = fs.createWriteStream(asset.dest)

            return new Promise(function(resolve, reject) {
                rd.on('error', reject)
                wr.on('error', reject)
                wr.on('finish', resolve)
                rd.pipe(wr);
            }).catch(function(error) {
                rd.destroy()
                wr.end()
                throw error
            })

        /* custom/external handlers */
        default:

            try {
                return requireg('@nexrender/provider-' + protocol).download(job, settings, asset.src, asset.dest, asset.params || {});
            } catch (e) {
                if (e.message.indexOf('Could not require module') !== -1) {
                    return Promise.reject(new Error(`Couldn't find module @nexrender/provider-${protocol}, Unknown protocol provided.`))
                }

                throw e;
            }

    }
}

/**
 * This task is used to download/copy every entry in the "job.assets"
 * and place it nearby the project asset
 */
module.exports = function(job, settings) {
    settings.logger.log(`[${job.uid}] downloading assets...`)

    const promises = [].concat(
        download(job, settings, job.template),
        job.assets.map(asset => download(job, settings, asset))
    )

    return Promise.all(promises).then(() => job);
}


text:
<?php

/*
 *
 *
 *
 */

namespace pfp\components\RedisNoSQLStorage {

    /**
     * Description of RedisNoSQLStorageException
     *
     * @author Zeakis George <zeageorge@gmail.com>
     */
    class RedisNoSQLStorageException extends \pfp\base\ComponentException {

    }

}


text:
package com.github.joseph.core.page.pageObject;

import com.github.joseph.core.page.pageObject.commands.options.OptionByText;
import com.github.joseph.core.page.pageObject.function.CommandFunction;

public class Selects {

    public static CommandFunction optionByText(String text) {
        return new OptionByText();
    }
}