text:
package com.almasb.java.framework.demo;

import java.security.AlgorithmParameters;
import java.security.spec.KeySpec;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

public class EncryptionDemo {

    public static void main(String[] args) throws Exception {
        /*byte[] input = "Hello, how are you doing?".getBytes();

        System.out.println(Arrays.toString(input));

        byte[] keyBytes = "Passwordpasswod".getBytes();
        byte[] ivBytes = new byte[10];
        new java.util.Random().nextBytes(ivBytes);

        // wrap key data in Key/IV specs to pass to cipher
        SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        // create the cipher with the algorithm you choose
        // see javadoc for Cipher class for more info, e.g.
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
        byte[] encrypted= new byte[cipher.getOutputSize(input.length)];
        int enc_len = cipher.update(input, 0, input.length, encrypted, 0);
        enc_len += cipher.doFinal(encrypted, enc_len);

        System.out.println(Arrays.toString(encrypted));

        cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
        byte[] decrypted = new byte[cipher.getOutputSize(enc_len)];
        int dec_len = cipher.update(encrypted, 0, enc_len, decrypted, 0);
        dec_len += cipher.doFinal(decrypted, dec_len);

        System.out.println(Arrays.toString(decrypted));*/

        /* Derive the key, given password and salt. */

        char[] password = "mynAme".toCharArray();
        byte[] salt = new byte[8];
        new java.util.Random().nextBytes(salt);
        String text = "Yo hi what's uo!";

        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(password, salt, 65536, 128);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
        /* Encrypt the message. */
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secret);
        AlgorithmParameters params = cipher.getParameters();
        byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
        byte[] ciphertext = cipher.doFinal(text.getBytes("UTF-8"));

        /* Decrypt the message, given derived key and initialization vector. */
        Cipher cipher2 = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher2.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
        String plaintext = new String(cipher2.doFinal(ciphertext), "UTF-8");
        System.out.println(plaintext);
    }
}


text:
#include "opt_eisa.h"

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/queue.h>
#include <sys/malloc.h>
#include <sys/kernel.h>
#include <sys/module.h>
#include <sys/bus.h>

#include <machine/limits.h>
#include <machine/bus.h>
#include <machine/resource.h>
#include <sys/rman.h>

#include <dev/eisa/eisaconf.h>

typedef struct resvaddr {
        u_long	addr;				/* start address */
        u_long	size;				/* size of reserved area */
	int	flags;
	struct resource *res;			/* resource manager handle */
	LIST_ENTRY(resvaddr) links;		/* List links */
} resvaddr_t;

LIST_HEAD(resvlist, resvaddr);

struct irq_node {
	int	irq_no;
	int	irq_trigger;
	void	*idesc;
	TAILQ_ENTRY(irq_node) links;
};

TAILQ_HEAD(irqlist, irq_node);

struct eisa_ioconf {
	int		slot;
	struct resvlist	ioaddrs;	/* list of reserved I/O ranges */
	struct resvlist maddrs;		/* list of reserved memory ranges */
	struct irqlist	irqs;		/* list of reserved irqs */
};

/* To be replaced by the "super device" generic device structure... */
struct eisa_device {
	eisa_id_t		id;
	struct eisa_ioconf	ioconf;
};

#define MAX_COL		79
#ifndef EISA_SLOTS
#define EISA_SLOTS 10   /* PCI clashes with higher ones.. fix later */
#endif
int num_eisa_slots = EISA_SLOTS;
TUNABLE_INT("hw.eisa_slots", &num_eisa_slots);

static devclass_t eisa_devclass;

static void eisa_reg_print (device_t, char *, char *, int *);
static struct irq_node * eisa_find_irq(struct eisa_device *e_dev, int rid);
static struct resvaddr * eisa_find_maddr(struct eisa_device *e_dev, int rid);
static struct resvaddr * eisa_find_ioaddr(struct eisa_device *e_dev, int rid);

static int
mainboard_probe(device_t dev)
{
	char *idstring;
	eisa_id_t id = eisa_get_id(dev);

	if (eisa_get_slot(dev) != 0)
		return (ENXIO);

	idstring = (char *)malloc(8 + sizeof(" (System Board)") + 1,
				  M_DEVBUF, M_NOWAIT);
	if (idstring == NULL) {
		panic("Eisa probe unable to malloc");
	}
	sprintf(idstring, "%c%c%c%03x%01x (System Board)",
		EISA_MFCTR_CHAR0(id),
		EISA_MFCTR_CHAR1(id),
		EISA_MFCTR_CHAR2(id),
		EISA_PRODUCT_ID(id),
		EISA_REVISION_ID(id));
	device_set_desc(dev, idstring);

	return (0);
}

static int
mainboard_attach(device_t dev)
{
	return (0);
}

static device_method_t mainboard_methods[] = {
	/* Device interface */
	DEVMETHOD(device_probe,		mainboard_probe),
	DEVMETHOD(device_attach,	mainboard_attach),

	{ 0, 0 }
};

static driver_t mainboard_driver = {
	"mainboard",
	mainboard_methods,
	1,
};

static devclass_t mainboard_devclass;

DRIVER_MODULE(mainboard, eisa, mainboard_driver, mainboard_devclass, 0, 0);

/*
** probe for EISA devices
*/
static int
eisa_probe(device_t dev)
{
	int i,slot;
	struct eisa_device *e_dev;
	device_t child;
	int eisaBase = 0xc80;
	eisa_id_t eisa_id;
	int devices_found = 0;

	device_set_desc(dev, "EISA bus");

	for (slot = 0; slot < num_eisa_slots; eisaBase+=0x1000, slot++) {
		int id_size = sizeof(eisa_id);
		eisa_id = 0;
    		for( i = 0; i < id_size; i++ ) {
			outb(eisaBase,0x80 + i); /*Some cards require priming*/
			eisa_id |= inb(eisaBase+i) << ((id_size-i-1)*CHAR_BIT);
		}
		if (eisa_id & 0x80000000)
			continue;  /* no EISA card in slot */

		devices_found++;

		/* Prepare an eisa_device_node for this slot */
		e_dev = (struct eisa_device *)malloc(sizeof(*e_dev),
						     M_DEVBUF, M_NOWAIT|M_ZERO);
		if (!e_dev) {
			device_printf(dev, "cannot malloc eisa_device");
			break; /* Try to attach what we have already */
		}

		e_dev->id = eisa_id;

		e_dev->ioconf.slot = slot;

		/* Initialize our lists of reserved addresses */
		LIST_INIT(&(e_dev->ioconf.ioaddrs));
		LIST_INIT(&(e_dev->ioconf.maddrs));
		TAILQ_INIT(&(e_dev->ioconf.irqs));

		child = device_add_child(dev, NULL, -1);
		device_set_ivars(child, e_dev);
	}

	/*
	 * EISA busses themselves are not easily detectable, the easiest way
	 * to tell if there is an eisa bus is if we found something - there
	 * should be a motherboard "card" there somewhere.
	 */
	return devices_found ? 0 : ENXIO;
}

static void
eisa_probe_nomatch(device_t dev, device_t child)
{
	u_int32_t	eisa_id = eisa_get_id(child);
	u_int8_t	slot = eisa_get_slot(child);

	device_printf(dev, "unknown card %c%c%c%03x%01x (0x%08x) at slot %d\n",
		EISA_MFCTR_CHAR0(eisa_id),
		EISA_MFCTR_CHAR1(eisa_id),
		EISA_MFCTR_CHAR2(eisa_id),
		EISA_PRODUCT_ID(eisa_id),
		EISA_REVISION_ID(eisa_id),
		eisa_id,
		slot);

	return;
}

static void
eisa_reg_print (dev, string, separator, column)
	device_t	dev;
	char *		string;
	char *		separator;
	int *		column;
{
	int length = strlen(string);

	length += (separator ? 2 : 1);

	if (((*column) + length) >= MAX_COL) {
		printf("\n");
		(*column) = 0;
	} else if ((*column) != 0) {
		if (separator) {
			printf("%c", *separator);
			(*column)++;
		}
		printf(" ");
		(*column)++;
	}

	if ((*column) == 0) {
		(*column) += device_printf(dev, "%s", string);
	} else {
		(*column) += printf("%s", string);
	}

	return;
}

static int
eisa_print_child(device_t dev, device_t child)
{
	char			buf[81];
	struct eisa_device *	e_dev = device_get_ivars(child);
	int			rid;
	struct irq_node *	irq;
	struct resvaddr *	resv;
	char			separator = ',';
	int			column = 0;
	int			retval = 0;

	if (device_get_desc(child)) {
		snprintf(buf, sizeof(buf), "<%s>", device_get_desc(child));
		eisa_reg_print(child, buf, NULL, &column);
	}

	rid = 0;
	while ((resv = eisa_find_ioaddr(e_dev, rid++))) {
		if ((resv->size == 1) ||
		    (resv->flags & RESVADDR_BITMASK)) {
			snprintf(buf, sizeof(buf), "%s%lx",
				((rid == 1) ? "at 0x" : "0x"),
				resv->addr);
		} else {
			snprintf(buf, sizeof(buf), "%s%lx-0x%lx",
				((rid == 1) ? "at 0x" : "0x"),
				resv->addr,
				(resv->addr + (resv->size - 1)));
		}
		eisa_reg_print(child, buf,
			((rid == 2) ? &separator : NULL), &column);
	}

	rid = 0;
	while ((resv = eisa_find_maddr(e_dev, rid++))) {
		if ((resv->size == 1) ||
		    (resv->flags & RESVADDR_BITMASK)) {
			snprintf(buf, sizeof(buf), "%s%lx",
				((rid == 1) ? "at 0x" : "0x"),
				resv->addr);
		} else {
			snprintf(buf, sizeof(buf), "%s%lx-0x%lx",
				((rid == 1) ? "at 0x" : "0x"),
				resv->addr,
				(resv->addr + (resv->size - 1)));
		}
		eisa_reg_print(child, buf,
			((rid == 2) ? &separator : NULL), &column);
	}

	rid = 0;
	while ((irq = eisa_find_irq(e_dev, rid++)) != NULL) {
		snprintf(buf, sizeof(buf), "irq %d (%s)", irq->irq_no,
			 (irq->irq_trigger ? "level" : "edge"));
		eisa_reg_print(child, buf,
			((rid == 1) ? &separator : NULL), &column);
	}

	snprintf(buf, sizeof(buf), "on %s slot %d\n",
		device_get_nameunit(dev), eisa_get_slot(child));
	eisa_reg_print(child, buf, NULL, &column);

	return (retval);
}

static struct irq_node *
eisa_find_irq(struct eisa_device *e_dev, int rid)
{
	int i;
	struct irq_node *irq;

	for (i = 0, irq = TAILQ_FIRST(&e_dev->ioconf.irqs);
	     i < rid && irq;
	     i++, irq = TAILQ_NEXT(irq, links))
		;

	if (irq)
		return (irq);
	else
		return (NULL);
}

static struct resvaddr *
eisa_find_maddr(struct eisa_device *e_dev, int rid)
{
	int i;
	struct resvaddr *resv;

	for (i = 0, resv = LIST_FIRST(&e_dev->ioconf.maddrs);
	     i < rid && resv;
	     i++, resv = LIST_NEXT(resv, links))
		;

	return resv;
}

static struct resvaddr *
eisa_find_ioaddr(struct eisa_device *e_dev, int rid)
{
	int i;
	struct resvaddr *resv;

	for (i = 0, resv = LIST_FIRST(&e_dev->ioconf.ioaddrs);
	     i < rid && resv;
	     i++, resv = LIST_NEXT(resv, links))
		;

	return resv;
}

static int
eisa_read_ivar(device_t dev, device_t child, int which, u_long *result)
{
	struct eisa_device *e_dev = device_get_ivars(child);
	struct irq_node *irq;

	switch (which) {
	case EISA_IVAR_SLOT:
		*result = e_dev->ioconf.slot;
		break;

	case EISA_IVAR_ID:
		*result = e_dev->id;
		break;

	case EISA_IVAR_IRQ:
		/* XXX only first irq */
		if ((irq = eisa_find_irq(e_dev, 0)) != NULL) {
			*result = irq->irq_no;
		} else {
			*result = -1;
		}
		break;

	default:
		return (ENOENT);
	}

	return (0);
}

static int
eisa_write_ivar(device_t dev, device_t child, int which, uintptr_t value)
{
	return (EINVAL);
}

static struct resource *
eisa_alloc_resource(device_t dev, device_t child, int type, int *rid,
		    u_long start, u_long end, u_long count, u_int flags)
{
	int isdefault;
	struct eisa_device *e_dev = device_get_ivars(child);
	struct resource *rv, **rvp = 0;

	isdefault = (device_get_parent(child) == dev
		     && start == 0UL && end == ~0UL && count == 1);

	switch (type) {
	case SYS_RES_IRQ:
		if (isdefault) {
			struct irq_node * irq = eisa_find_irq(e_dev, *rid);
			if (irq == NULL)
				return 0;
			start = end = irq->irq_no;
			count = 1;
			if (irq->irq_trigger == EISA_TRIGGER_LEVEL) {
				flags |= RF_SHAREABLE;
			} else {
				flags &= ~RF_SHAREABLE;
			}
		}
		break;

	case SYS_RES_MEMORY:
		if (isdefault) {
			struct resvaddr *resv;

			resv = eisa_find_maddr(e_dev, *rid);
			if (!resv)
				return 0;

			start = resv->addr;
			end = resv->addr + (resv->size - 1);
			count = resv->size;
			rvp = &resv->res;
		}
		break;

	case SYS_RES_IOPORT:
		if (isdefault) {
			struct resvaddr *resv;

			resv = eisa_find_ioaddr(e_dev, *rid);
			if (!resv)
				return 0;

			start = resv->addr;
			end = resv->addr + (resv->size - 1);
			count = resv->size;
			rvp = &resv->res;
		}
		break;

	default:
		return 0;
	}

	rv = BUS_ALLOC_RESOURCE(device_get_parent(dev), child,
				 type, rid, start, end, count, flags);
	if (rvp)
		*rvp = rv;

	return rv;
}

static int
eisa_release_resource(device_t dev, device_t child, int type, int rid,
		      struct resource *r)
{
	int rv;
	struct eisa_device *e_dev = device_get_ivars(child);
	struct resvaddr *resv = 0;

	switch (type) {
	case SYS_RES_IRQ:
		if (eisa_find_irq(e_dev, rid) == NULL)
			return EINVAL;
		break;

	case SYS_RES_MEMORY:
		if (device_get_parent(child) == dev)
			resv = eisa_find_maddr(e_dev, rid);
		break;

	case SYS_RES_IOPORT:
		if (device_get_parent(child) == dev)
			resv = eisa_find_ioaddr(e_dev, rid);
		break;

	default:
		return (ENOENT);
	}

	rv = BUS_RELEASE_RESOURCE(device_get_parent(dev), child, type, rid, r);

	if (rv == 0) {
		if (resv)
			resv->res = 0;
	}

	return rv;
}

int
eisa_add_intr(device_t dev, int irq, int trigger)
{
	struct eisa_device *e_dev = device_get_ivars(dev);
	struct irq_node *irq_info;

	irq_info = (struct irq_node *)malloc(sizeof(*irq_info), M_DEVBUF,
					     M_NOWAIT);
	if (irq_info == NULL)
		return (1);

	irq_info->irq_no = irq;
	irq_info->irq_trigger = trigger;
	irq_info->idesc = NULL;
	TAILQ_INSERT_TAIL(&e_dev->ioconf.irqs, irq_info, links);
	return 0;
}

static int
eisa_add_resvaddr(struct eisa_device *e_dev, struct resvlist *head, u_long base,
		  u_long size, int flags)
{
	resvaddr_t *reservation;

	reservation = (resvaddr_t *)malloc(sizeof(resvaddr_t),
					   M_DEVBUF, M_NOWAIT);
	if(!reservation)
		return (ENOMEM);

	reservation->addr = base;
	reservation->size = size;
	reservation->flags = flags;

	if (!LIST_FIRST(head)) {
		LIST_INSERT_HEAD(head, reservation, links);
	}
	else {
		resvaddr_t *node;
		LIST_FOREACH(node, head, links) {
			if (node->addr > reservation->addr) {
				/*
				 * List is sorted in increasing
				 * address order.
				 */
				LIST_INSERT_BEFORE(node, reservation, links);
				break;
			}

			if (node->addr == reservation->addr) {
				/*
				 * If the entry we want to add
				 * matches any already in here,
				 * fail.
				 */
				free(reservation, M_DEVBUF);
				return (EEXIST);
			}

			if (!LIST_NEXT(node, links)) {
				LIST_INSERT_AFTER(node, reservation, links);
				break;
			}
		}
	}
	return (0);
}

int
eisa_add_mspace(device_t dev, u_long mbase, u_long msize, int flags)
{
	struct eisa_device *e_dev = device_get_ivars(dev);

	return	eisa_add_resvaddr(e_dev, &(e_dev->ioconf.maddrs), mbase, msize,
				  flags);
}

int
eisa_add_iospace(device_t dev, u_long iobase, u_long iosize, int flags)
{
	struct eisa_device *e_dev = device_get_ivars(dev);

	return	eisa_add_resvaddr(e_dev, &(e_dev->ioconf.ioaddrs), iobase,
				  iosize, flags);
}

static device_method_t eisa_methods[] = {
	/* Device interface */
	DEVMETHOD(device_probe,		eisa_probe),
	DEVMETHOD(device_attach,	bus_generic_attach),
	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
	DEVMETHOD(device_suspend,	bus_generic_suspend),
	DEVMETHOD(device_resume,	bus_generic_resume),

	/* Bus interface */
	DEVMETHOD(bus_print_child,	eisa_print_child),
	DEVMETHOD(bus_probe_nomatch,	eisa_probe_nomatch),
	DEVMETHOD(bus_read_ivar,	eisa_read_ivar),
	DEVMETHOD(bus_write_ivar,	eisa_write_ivar),
	DEVMETHOD(bus_driver_added,	bus_generic_driver_added),
	DEVMETHOD(bus_alloc_resource,	eisa_alloc_resource),
	DEVMETHOD(bus_release_resource,	eisa_release_resource),
	DEVMETHOD(bus_activate_resource, bus_generic_activate_resource),
	DEVMETHOD(bus_deactivate_resource, bus_generic_deactivate_resource),
	DEVMETHOD(bus_setup_intr,	bus_generic_setup_intr),
	DEVMETHOD(bus_teardown_intr,	bus_generic_teardown_intr),

	{ 0, 0 }
};

static driver_t eisa_driver = {
	"eisa",
	eisa_methods,
	1,			/* no softc */
};

DRIVER_MODULE(eisa, eisab, eisa_driver, eisa_devclass, 0, 0);
DRIVER_MODULE(eisa, legacy, eisa_driver, eisa_devclass, 0, 0);

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>
<!--
@license
Copyright (C) 2017 The Android Open Source Project

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
<title>keyboard-shortcut-behavior</title>

<script src="../../bower_components/webcomponentsjs/webcomponents.min.js"></script>
<script src="../../bower_components/web-component-tester/browser.js"></script>
<link rel="import" href="../../test/common-test-setup.html"/>
<script>
  /** @type {string} */
  window.CANONICAL_PATH = '/r';
</script>

<link rel="import" href="../base-url-behavior/base-url-behavior.html">
<link rel="import" href="rest-client-behavior.html">

<test-fixture id="basic">
  <template>
    <test-element></test-element>
  </template>
</test-fixture>

<test-fixture id="within-overlay">
  <template>
    <gr-overlay>
      <test-element></test-element>
    </gr-overlay>
  </template>
</test-fixture>

<script>
  suite('rest-client-behavior tests', () => {
    let element;
    // eslint-disable-next-line no-unused-vars
    let overlay;

    suiteSetup(() => {
      // Define a Polymer element that uses this behavior.
      Polymer({
        is: 'test-element',
        _legacyUndefinedCheck: true,
        behaviors: [
          Gerrit.BaseUrlBehavior,
          Gerrit.RESTClientBehavior,
        ],
      });
    });

    setup(() => {
      element = fixture('basic');
      overlay = fixture('within-overlay');
    });

    test('changeBaseURL', () => {
      assert.deepEqual(
          element.changeBaseURL('test/project', '1', '2'),
          '/r/changes/test%2Fproject~1/revisions/2'
      );
    });

    test('changePath', () => {
      assert.deepEqual(element.changePath('1'), '/r/c/1');
    });

    test('Open status', () => {
      const change = {
        change_id: 'Iad9dc96274af6946f3632be53b106ef80f7ba6ca',
        revisions: {
          rev1: {_number: 1},
        },
        current_revision: 'rev1',
        status: 'NEW',
        labels: {},
        mergeable: true,
      };
      let statuses = element.changeStatuses(change);
      const statusString = element.changeStatusString(change);
      assert.deepEqual(statuses, []);
      assert.equal(statusString, '');

      change.submittable = false;
      statuses = element.changeStatuses(change,
          {includeDerived: true});
      assert.deepEqual(statuses, ['Active']);

      // With no missing labels but no submitEnabled option.
      change.submittable = true;
      statuses = element.changeStatuses(change,
          {includeDerived: true});
      assert.deepEqual(statuses, ['Active']);

      // Without missing labels and enabled submit
      statuses = element.changeStatuses(change,
          {includeDerived: true, submitEnabled: true});
      assert.deepEqual(statuses, ['Ready to submit']);

      change.mergeable = false;
      change.submittable = true;
      statuses = element.changeStatuses(change,
          {includeDerived: true});
      assert.deepEqual(statuses, ['Merge Conflict']);

      delete change.mergeable;
      change.submittable = true;
      statuses = element.changeStatuses(change,
          {includeDerived: true, mergeable: true, submitEnabled: true});
      assert.deepEqual(statuses, ['Ready to submit']);

      change.submittable = true;
      statuses = element.changeStatuses(change,
          {includeDerived: true, mergeable: false});
      assert.deepEqual(statuses, ['Merge Conflict']);
    });

    test('Merge conflict', () => {
      const change = {
        change_id: 'Iad9dc96274af6946f3632be53b106ef80f7ba6ca',
        revisions: {
          rev1: {_number: 1},
        },
        current_revision: 'rev1',
        status: 'NEW',
        labels: {},
        mergeable: false,
      };
      const statuses = element.changeStatuses(change);
      const statusString = element.changeStatusString(change);
      assert.deepEqual(statuses, ['Merge Conflict']);
      assert.equal(statusString, 'Merge Conflict');
    });

    test('mergeable prop undefined', () => {
      const change = {
        change_id: 'Iad9dc96274af6946f3632be53b106ef80f7ba6ca',
        revisions: {
          rev1: {_number: 1},
        },
        current_revision: 'rev1',
        status: 'NEW',
        labels: {},
      };
      const statuses = element.changeStatuses(change);
      const statusString = element.changeStatusString(change);
      assert.deepEqual(statuses, []);
      assert.equal(statusString, '');
    });

    test('Merged status', () => {
      const change = {
        change_id: 'Iad9dc96274af6946f3632be53b106ef80f7ba6ca',
        revisions: {
          rev1: {_number: 1},
        },
        current_revision: 'rev1',
        status: 'MERGED',
        labels: {},
      };
      const statuses = element.changeStatuses(change);
      const statusString = element.changeStatusString(change);
      assert.deepEqual(statuses, ['Merged']);
      assert.equal(statusString, 'Merged');
    });

    test('Abandoned status', () => {
      const change = {
        change_id: 'Iad9dc96274af6946f3632be53b106ef80f7ba6ca',
        revisions: {
          rev1: {_number: 1},
        },
        current_revision: 'rev1',
        status: 'ABANDONED',
        labels: {},
      };
      const statuses = element.changeStatuses(change);
      const statusString = element.changeStatusString(change);
      assert.deepEqual(statuses, ['Abandoned']);
      assert.equal(statusString, 'Abandoned');
    });

    test('Open status with private and wip', () => {
      const change = {
        change_id: 'Iad9dc96274af6946f3632be53b106ef80f7ba6ca',
        revisions: {
          rev1: {_number: 1},
        },
        current_revision: 'rev1',
        status: 'NEW',
        is_private: true,
        work_in_progress: true,
        labels: {},
        mergeable: true,
      };
      const statuses = element.changeStatuses(change);
      const statusString = element.changeStatusString(change);
      assert.deepEqual(statuses, ['WIP', 'Private']);
      assert.equal(statusString, 'WIP, Private');
    });

    test('Merge conflict with private and wip', () => {
      const change = {
        change_id: 'Iad9dc96274af6946f3632be53b106ef80f7ba6ca',
        revisions: {
          rev1: {_number: 1},
        },
        current_revision: 'rev1',
        status: 'NEW',
        is_private: true,
        work_in_progress: true,
        labels: {},
        mergeable: false,
      };
      const statuses = element.changeStatuses(change);
      const statusString = element.changeStatusString(change);
      assert.deepEqual(statuses, ['Merge Conflict', 'WIP', 'Private']);
      assert.equal(statusString, 'Merge Conflict, WIP, Private');
    });
  });
</script>


text:
<?php

namespace Admin\ParametersBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class AdminParametersBundle extends Bundle
{
}


text:
using Nwazet.Commerce.Models;
using Orchard.ContentManagement;
using Orchard.Data;
using Orchard.ContentManagement.Handlers;
using Orchard.Environment.Extensions;
using Orchard.Localization;

namespace Nwazet.Commerce.Handlers {
    [OrchardFeature("Stripe")]
    public class StripeSettingsPartHandler : ContentHandler {
        public StripeSettingsPartHandler() {
            T = NullLocalizer.Instance;
            Filters.Add(new ActivatingFilter<StripeSettingsPart>("Site"));
        }

        public Localizer T { get; set; }

        protected override void GetItemMetadata(GetContentItemMetadataContext context) {
            if (context.ContentItem.ContentType != "Site")
                return;
            base.GetItemMetadata(context);
            context.Metadata.EditorGroupInfo.Add(new GroupInfo(T("Stripe")) {
                Id = "Stripe",
                Position = "4.1"
            });
        }
    }
}


text:
package account

import (
	"bytes"
	"context"
	"crypto/hmac"
	"crypto/sha1"
	"encoding/base64"
	"fmt"
	"hash"
	"net/http"
	"strconv"
	"time"

	"go-common/app/interface/main/account/conf"
	"go-common/library/ecode"
	"go-common/library/log"

	"github.com/pkg/errors"
)

// UploadImage upload bfs.
func (d *Dao) UploadImage(c context.Context, fileType string, bs []byte, bfs *conf.BFS) (location string, err error) {
	url := bfs.URL + bfs.Bucket + "/"
	req, err := http.NewRequest(bfs.Method, url, bytes.NewBuffer(bs))
	if err != nil {
		log.Error("account-interface: http.NewRequest error (%v) | fileType(%s)", err, fileType)
		return
	}
	expire := time.Now().Unix()
	authorization := authorize(bfs.Key, bfs.Secret, bfs.Method, bfs.Bucket, expire)
	req.Header.Set("Host", url)
	req.Header.Add("Date", fmt.Sprint(expire))
	req.Header.Add("Authorization", authorization)
	req.Header.Add("Content-Type", fileType)
	// timeout
	ctx, cancel := context.WithTimeout(c, time.Duration(d.c.BFS.Timeout))
	req = req.WithContext(ctx)
	defer cancel()
	resp, err := d.bfsClient.Do(req)
	if err != nil {
		log.Error("account-interface: d.Client.Do error(%v) | url(%s)", err, url)
		err = ecode.BfsUploadServiceUnavailable
		return
	}
	if resp.StatusCode != http.StatusOK {
		log.Error("account-interface: Upload http.StatusCode nq http.StatusOK (%d) | url(%s)", resp.StatusCode, d.c.BFS.URL)
		err = errors.New("Upload failed")
		return
	}
	header := resp.Header
	code := header.Get("Code")
	if code != strconv.Itoa(http.StatusOK) {
		log.Error("account-interface: strconv.Itoa err, code(%s) | url(%s)", code, url)
		err = errors.New("Upload failed")
		return
	}
	location = header.Get("Location")
	return
}

// authorize returns authorization for upload file to bfs
func authorize(key, secret, method, bucket string, expire int64) (authorization string) {
	var (
		content   string
		mac       hash.Hash
		signature string
	)
	content = fmt.Sprintf("%s\n%s\n\n%d\n", method, bucket, expire)
	mac = hmac.New(sha1.New, []byte(secret))
	mac.Write([]byte(content))
	signature = base64.StdEncoding.EncodeToString(mac.Sum(nil))
	authorization = fmt.Sprintf("%s:%s:%d", key, signature, expire)
	return
}


text:
SHADER_STRUCT(GenMipsConsts,
  uint2 outputSize;
  uint2 sourceSize;
);

namespace app::renderer
{
GenerateMips::GenerateMips(higanbana::GpuGroup& dev) {
  using namespace higanbana;
  auto inputDataLayout = ShaderArgumentsLayoutDescriptor()
    .readOnly(ShaderResourceType::Texture2D, "float4", "input")
    .readWrite(ShaderResourceType::Texture2D, "float4", "output");
  m_input = dev.createShaderArgumentsLayout(inputDataLayout);

  PipelineInterfaceDescriptor instancePipeline = PipelineInterfaceDescriptor()
    .constants<GenMipsConsts>()
    .shaderArguments(0, m_input);

  auto pipelineDescriptor = ComputePipelineDescriptor()
    .setInterface(instancePipeline)
    .setShader("/shaders/generate_mips")
    .setThreadGroups(uint3(8,8,1));

  pipeline = dev.createComputePipeline(pipelineDescriptor);
}
void GenerateMips::generateMipsCS(higanbana::GpuGroup& dev, higanbana::CommandGraphNode& node, higanbana::Texture source) {
  using namespace higanbana;
  HIGAN_ASSERT(source.desc().desc.usage == ResourceUsage::GpuRW || source.desc().desc.usage == ResourceUsage::RenderTargetRW, "woo");
  auto mips = source.desc().desc.miplevels-1;
  for (int mip = 0; mip < mips; ++mip) {
    auto srv = dev.createTextureSRV(source, ShaderViewDescriptor().setMostDetailedMip(mip).setMipLevels(1));
    auto uav = dev.createTextureUAV(source, ShaderViewDescriptor().setMostDetailedMip(mip+1).setMipLevels(1));
    generateMipCS(dev, node, srv, uav);
  }
}
void GenerateMips::generateMipCS(higanbana::GpuGroup& dev, higanbana::CommandGraphNode& node, higanbana::TextureSRV sourceMip, higanbana::TextureUAV outputMip) {
  using namespace higanbana;
  auto srcMip = sourceMip.mip();
  auto dstMip = outputMip.mip();
  //HIGAN_LOGi("gen mip %d > %d\n", srcMip, dstMip);
  using namespace higanbana;
  auto bind = node.bind(pipeline);
  auto args = dev.createShaderArguments(ShaderArgumentsDescriptor("genMipsCS", m_input)
    .bind("input", sourceMip)
    .bind("output", outputMip));

  bind.arguments(0, args);
  GenMipsConsts c = {};
  c.sourceSize = sourceMip.size3D().xy();
  c.outputSize = outputMip.size3D().xy();
  bind.constants(c);
  //HIGAN_LOGi("constants %dx%d -> %dx%d\n", c.sourceSize.x, c.sourceSize.y, c.outputSize.x, c.outputSize.y);
  uint3 threads = outputMip.size3D();
  node.dispatchThreads(bind, threads);
}
}


text:
using System;
using System.Net.Http;
using System.Security.Claims;
using System.Web.Http;
using BookArena.App.ViewModels;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;

namespace BookArena.App.Controllers
{
    [Authorize]
    [RoutePrefix("api/Account")]
    public class AccountController : BaseApiController
    {
        private ApplicationUserManager _userManager;

        public AccountController()
        {
        }

        public AccountController(ApplicationUserManager userManager,
            ISecureDataFormat<AuthenticationTicket> accessTokenFormat)
        {
            UserManager = userManager;
            AccessTokenFormat = accessTokenFormat;
        }

        public ApplicationUserManager UserManager
        {
            get { return _userManager ?? Request.GetOwinContext().GetUserManager<ApplicationUserManager>(); }
            private set { _userManager = value; }
        }

        public ISecureDataFormat<AuthenticationTicket> AccessTokenFormat { get; private set; }

        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("UserInfo")]
        public UserInfoViewModel GetUserInfo()
        {
            var externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);

            return new UserInfoViewModel
            {
                Email = User.Identity.GetUserName(),
                HasRegistered = externalLogin == null
            };
        }

        [Route("Logout")]
        public IHttpActionResult Logout()
        {
            Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType);
            return Ok(new
            {
                Message = "You have been logged out!"
            });
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                UserManager.Dispose();
            }

            base.Dispose(disposing);
        }

        #region Helpers

        private IAuthenticationManager Authentication
        {
            get { return Request.GetOwinContext().Authentication; }
        }

        private class ExternalLoginData
        {
            private string LoginProvider { get; set; }
            private string ProviderKey { get; set; }
            private string UserName { get; set; }

            public static ExternalLoginData FromIdentity(ClaimsIdentity identity)
            {
                if (identity == null)
                {
                    return null;
                }

                var providerKeyClaim = identity.FindFirst(ClaimTypes.NameIdentifier);

                if (providerKeyClaim == null || String.IsNullOrEmpty(providerKeyClaim.Issuer)
                    || String.IsNullOrEmpty(providerKeyClaim.Value))
                {
                    return null;
                }

                if (providerKeyClaim.Issuer == ClaimsIdentity.DefaultIssuer)
                {
                    return null;
                }

                return new ExternalLoginData
                {
                    LoginProvider = providerKeyClaim.Issuer,
                    ProviderKey = providerKeyClaim.Value,
                    UserName = identity.FindFirstValue(ClaimTypes.Name)
                };
            }
        }

        #endregion
    }
}


text:
package com.ivanbratoev.festpal.datamodel.db.external;

/**
 * Holder class for strings used throughout the interface with the external db
 */
class ExternalDatabaseDefinitions {
    public static final String PROTOCOL = "http";
    public static final String ADDRESS = "127.0.0.1";
    public static final String HOST = "8000";

    public static final String REGISTER = "register";
    public static final String LOGIN = "login";
    public static final String LOGOUT = "logout";

    public static final String MULTIPLE = "mult";

    public static final String READ = "r";
    public static final String WRITE = "w";
    public static final String UPDATE = "u";
    public static final String DELETE = "d";
    public static final String VOTE = "v";

    public static final String FESTIVAL = "fest";
    public static final String CONCERT = "conc";

    public static final String PARAMETER_CLIENT = "client";
    public static final String RESPONSE_NO_CLIENT_NAME = "Client name not provided\n";
    public static final String RESPONSE_CLIENT_NO_PERMISSION = "Permission not granted\n";
    public static final String LOG_OUT_RESPONSE_SUCCESS = "Logged out\n";
    public static final String PARAMETER_NUMBER = "num";
    public static final String PARAMETER_ID = "id";
    public static final String PARAMETER_FESTIVAL = "festival";
    public static final String RESPONSE_INVALID_FESTIVAL_ID = "Invalid Festival ID\n";
    public static final String RESPONSE_CONCERT_NOT_FOUND = "Concert Not Found\n";
    public static final String RESPONSE_INCORRECT_INPUT = "Incorrect input\n";
    public static final String RESPONSE_NAME_EXISTS = "Name exists\n";
    public static final String RESPONSE_ARTIST_EXISTS = "Artist exists\n";
    public static final String RESPONSE_PERMISSION_NOT_GRANTED = "Permission not granted\n";
    public static final String RESPONSE_OK = "OK\n";
    public static final String PARAMETER_MIN_PRICE = "min_price";
    public static final String PARAMETER_MAX_PRICE = "max_price";

    public class RegisterContext {
        public static final String PARAMETER_USERNAME = "username";
        public static final String PARAMETER_EMAIL = "e-mail";
        public static final String PARAMETER_PASSWORD = "password";
        public static final String PARAMETER_FIRST_NAME = "first_name";
        public static final String PARAMETER_LAST_NAME = "last_name";
        public static final String PARAMETER_COUNTRY = "country";
        public static final String PARAMETER_CITY = "city";
        public static final String PARAMETER_REPRESENTATIVE = "representative";
        public static final String RESULT_MISSING_NON_OPTIONAL_FIELDS = "Missing Non-Optional Fields\n";
        public static final String RESULT_INVALID_USERNAME = "Invalid Username\n";
        public static final String RESULT_INVALID_EMAIL = "Invalid e-mail\n";
        public static final String RESULT_INVALID_PASSWORD = "Invalid Password\n";
        public static final String RESULT_INVALID_FIRST_NAME = "Invalid First Name\n";
        public static final String RESULT_INVALID_LAST_NAME = "Invalid Last Name\n";
        public static final String RESULT_INVALID_COUNTRY = "Invalid Country\n";
        public static final String RESULT_INVALID_CITY = "Invalid City\n";
        public static final String RESULT_OK = "OK\n";
    }

    public class LogInContext {
        public static final String PARAMETER_USERNAME = "username";
        public static final String PARAMETER_PASSWORD = "password";
        public static final String RESPONSE_OK = "OK\n";
        public static final String RESPONSE_DISABLED = "Disabled account\n";
        public static final String RESPONSE_INVALID = "Invalid login\n";
        public static final String RESPONSE_NO_PASSWORD = "No password\n";
        public static final String RESPONSE_NO_USERNAME = "No username\n";
    }

    public class FestivalsContext {
        public static final String RESULT_PARAMETER_ID = "id";
        public static final String RESULT_PARAMETER_NAME = "name";
        public static final String RESULT_PARAMETER_DESCRIPTION = "description";
        public static final String RESULT_PARAMETER_COUNTRY = "country";
        public static final String RESULT_PARAMETER_CITY = "city";
        public static final String RESULT_PARAMETER_ADDRESS = "address";
        public static final String RESULT_PARAMETER_GENRE = "genre";
        public static final String RESULT_PARAMETER_PRICES = "prices";
        public static final String RESULT_PARAMETER_OWNER = "owner";
        public static final String RESULT_PARAMETER_OFFICIAL = "official";
        public static final String RESULT_PARAMETER_VOTES = "votes";
    }

    public class ConcertContext {
        public static final String RESULT_PARAMETER_EXTERNAL_ID = "external_id";
        public static final String PARAMETER_ID = "id";
        public static final String PARAMETER_FESTIVAL = "festival";
        public static final String PARAMETER_ARTIST = "artist";
        public static final String PARAMETER_SCENE = "scene";
        public static final String PARAMETER_DAY = "day";
        public static final String PARAMETER_START = "start";
        public static final String PARAMETER_END = "end";
        public static final String RESULT_PARAMETER_ARTIST = "artist";
        public static final String RESULT_PARAMETER_SCENE = "scene";
        public static final String RESULT_PARAMETER_DAY = "day";
        public static final String RESULT_PARAMETER_START = "start";
        public static final String RESULT_PARAMETER_END = "end";
    }
}


text:
//
//  ZLPhotoActionSheet.m
//  多选相册照片
//
//  Created by long on 15/11/25.
//  Copyright © 2015年 long. All rights reserved.
//

#import "ZLPhotoActionSheet.h"
#import <Photos/Photos.h>
#import "ZLCollectionCell.h"
#import "ZLShowBigImgViewController.h"
#import "ZLDefine.h"
#import "ZLSelectPhotoModel.h"
#import "ZLPhotoTool.h"
#import "ZLNoAuthorityViewController.h"
#import "ZLPhotoBrowser.h"
#import "ToastUtils.h"

double const ScalePhotoWidth = 1000;

typedef void (^handler)(NSArray<UIImage *> *selectPhotos, NSArray<ZLSelectPhotoModel *> *selectPhotoModels);

@interface ZLPhotoActionSheet () <UICollectionViewDelegateFlowLayout, UIImagePickerControllerDelegate, UINavigationControllerDelegate, PHPhotoLibraryChangeObserver>

@property (nonatomic, assign) BOOL animate;
@property (nonatomic, strong) NSMutableArray<PHAsset *> *arrayDataSources;
@property (nonatomic, strong) NSMutableArray<ZLSelectPhotoModel *> *arraySelectPhotos;
@property (nonatomic, assign) BOOL isSelectOriginalPhoto;
@property (nonatomic, copy)   handler handler;

@end

@implementation ZLPhotoActionSheet

- (void)dealloc
{
    [[PHPhotoLibrary sharedPhotoLibrary] unregisterChangeObserver:self];
}

- (instancetype)init
{
    self = [[kZLPhotoBrowserBundle loadNibNamed:@"ZLPhotoActionSheet" owner:self options:nil] lastObject];
    if (self) {
        NSLog(@"[ZLPhotoTool getViewHeight] -> %ld",(long)[ZLPhotoTool getViewHeight]);
        NSLog(@"[[UIScreen mainScreen] bounds].size.height -> %f",[[UIScreen mainScreen] bounds].size.height);
        NSLog(@"kViewWidth -> %f",kViewWidth);
        if ([ZLPhotoTool getViewHeight] == 0) {
            [ZLPhotoTool saveViewHeight:[NSString stringWithFormat:@"%f",[[UIScreen mainScreen] bounds].size.height]];
        }
        self.frame = CGRectMake(0, 0, kViewWidth, [ZLPhotoTool getViewHeight]);
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.minimumInteritemSpacing = 3;
        layout.sectionInset = UIEdgeInsetsMake(0, 5, 0, 5);

        self.collectionView.collectionViewLayout = layout;
        self.collectionView.backgroundColor = [UIColor whiteColor];
        [self.collectionView registerNib:[UINib nibWithNibName:@"ZLCollectionCell" bundle:kZLPhotoBrowserBundle] forCellWithReuseIdentifier:@"ZLCollectionCell"];

        self.maxSelectCount = 10;
        self.maxPreviewCount = 20;
        self.arrayDataSources  = [NSMutableArray array];
        self.arraySelectPhotos = [NSMutableArray array];

        //注册实施监听相册变化
        [[PHPhotoLibrary sharedPhotoLibrary] registerChangeObserver:self];
    }
    return self;
}

//相册变化回调
- (void)photoLibraryDidChange:(PHChange *)changeInstance
{
    dispatch_sync(dispatch_get_main_queue(), ^{
        [self loadPhotoFromAlbum];
    });
}

- (void)showWithSender:(UIViewController *)sender animate:(BOOL)animate lastSelectPhotoModels:(NSArray<ZLSelectPhotoModel *> *)lastSelectPhotoModels completion:(void (^)(NSArray<UIImage *> * _Nonnull, NSArray<ZLSelectPhotoModel *> * _Nonnull))completion
{
    self.handler = completion;
    self.animate = animate;
    self.sender  = sender;
    [self.arraySelectPhotos removeAllObjects];
    [self.arraySelectPhotos addObjectsFromArray:lastSelectPhotoModels];

    [self loadPhotoFromAlbum];

    [self show];
}

#pragma mark - 判断软件是否有相册、相机访问权限
- (BOOL)judgeIsHavePhotoAblumAuthority
{
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusRestricted ||
        status == PHAuthorizationStatusDenied) {
        return NO;
    }
    return YES;
}

- (BOOL)judgeIsHaveCameraAuthority
{
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (status == AVAuthorizationStatusRestricted ||
        status == AVAuthorizationStatusDenied) {
        return NO;
    }
    return YES;
}

- (void)showAlertWithTitle:(NSString *)title message:(NSString *)message
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:action];
    [self.sender presentViewController:alert animated:YES completion:nil];
}

- (void)loadPhotoFromAlbum
{
    [self.arrayDataSources removeAllObjects];
    [self.arrayDataSources addObjectsFromArray:[[ZLPhotoTool sharePhotoTool] getAllAssetInPhotoAblumWithAscending:NO]];

    [self.collectionView reloadData];
}

#pragma mark - 显示隐藏视图及相关动画
- (void)resetSubViewState
{
    self.hidden = NO;
    self.baseView.hidden = NO;
    if (self.arraySelectPhotos.count == 0) {
        [self.btnCamera setTitle:@"拍照" forState:UIControlStateNormal];
        [self.btnCamera setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    } else {
        [self.btnCamera setTitle:[NSString stringWithFormat:@"确定(%ld)", self.arraySelectPhotos.count] forState:UIControlStateNormal];
        [self.btnCamera setTitleColor:kRGB(19, 153, 231) forState:UIControlStateNormal];
    }
    [self.collectionView setContentOffset:CGPointZero];
}

- (void)show
{
    [self.sender.view addSubview:self];

    [self resetSubViewState];

    if (self.animate) {
        CGPoint fromPoint = CGPointMake(kViewWidth/2, [ZLPhotoTool getViewHeight]+kBaseViewHeight/2);
        CGPoint toPoint   = CGPointMake(kViewWidth/2, [ZLPhotoTool getViewHeight]-kBaseViewHeight/2);
        CABasicAnimation *animation = GetPositionAnimation([NSValue valueWithCGPoint:fromPoint], [NSValue valueWithCGPoint:toPoint], 0.2, @"position");
        [self.baseView.layer addAnimation:animation forKey:nil];
    }
}

- (void)hide
{
    if (self.animate) {
        CGPoint fromPoint = self.baseView.layer.position;
        CGPoint toPoint   = CGPointMake(fromPoint.x, fromPoint.y+kBaseViewHeight);
        CABasicAnimation *animation = GetPositionAnimation([NSValue valueWithCGPoint:fromPoint], [NSValue valueWithCGPoint:toPoint], 0.1, @"position");
        animation.delegate = self;

        [self.baseView.layer addAnimation:animation forKey:nil];
    } else {
        self.hidden = YES;
        [self removeFromSuperview];
    }
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    self.hidden = YES;
    [self removeFromSuperview];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self hide];
}

#pragma mark - UIButton Action
- (IBAction)btnCamera_Click:(id)sender
{
    if (self.arraySelectPhotos.count > 0) {
        [self requestSelPhotos:nil];
    } else {
        [self cameraClickAction:sender];
    }
}

- (void)cameraClickAction:(UIButton *)sender{
    if (![self judgeIsHaveCameraAuthority]) {
        [self showAlertWithTitle:@"无法使用相机" message:@"请在iPhone的\"设置-隐私-相机\"中允许访问相机"];
        [self hide];
        return;
    }
    //拍照
    if ([UIImagePickerController isSourceTypeAvailable:
         UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = NO;
        picker.videoQuality = UIImagePickerControllerQualityTypeLow;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self.sender presentViewController:picker animated:YES completion:nil];
    }
}

- (IBAction)btnPhotoLibrary_Click:(id)sender
{
    [self photoLibraryClickAction:sender];
}

- (void)photoLibraryClickAction:(UIButton *)sender{
    if (![self judgeIsHavePhotoAblumAuthority]) {
        //无相册访问权限
        ZLNoAuthorityViewController *nvc = [[ZLNoAuthorityViewController alloc] initWithNibName:@"ZLNoAuthorityViewController" bundle:kZLPhotoBrowserBundle];
        [self presentVC:nvc];
    } else {
        self.animate = NO;

        ZLPhotoBrowser *photoBrowser = [[ZLPhotoBrowser alloc] initWithStyle:UITableViewStylePlain];
        photoBrowser.maxSelectCount = self.maxSelectCount;
        photoBrowser.arraySelectPhotos = self.arraySelectPhotos.mutableCopy;

        weakify(self);
        __weak typeof(photoBrowser) weakPB = photoBrowser;
        [photoBrowser setDoneBlock:^(NSArray<ZLSelectPhotoModel *> *selPhotoModels, BOOL isSelectOriginalPhoto) {
            strongify(weakSelf);
            __strong typeof(weakPB) strongPB = weakPB;
            strongSelf.isSelectOriginalPhoto = isSelectOriginalPhoto;
            [strongSelf.arraySelectPhotos removeAllObjects];
            [strongSelf.arraySelectPhotos addObjectsFromArray:selPhotoModels];
            [strongSelf requestSelPhotos:strongPB];
        }];

        [photoBrowser setCancelBlock:^{
            strongify(weakSelf);
            [strongSelf hide];
        }];

        [self presentVC:photoBrowser];
    }
}

- (IBAction)btnCancel_Click:(id)sender
{
    [self.arraySelectPhotos removeAllObjects];
    [self hide];
}

- (void)cell_btn_Click:(UIButton *)btn
{
    if (_arraySelectPhotos.count >= self.maxSelectCount
        && btn.selected == NO) {
        ShowToastLong(@"最多只能选择%ld张图片", self.maxSelectCount);
        return;
    }

    PHAsset *asset = self.arrayDataSources[btn.tag];

    if (!btn.selected) {
        [btn.layer addAnimation:GetBtnStatusChangedAnimation() forKey:nil];
        if (![[ZLPhotoTool sharePhotoTool] judgeAssetisInLocalAblum:asset]) {
            ShowToastLong(@"该图片尚未从iCloud下载,请在系统相册中下载到本地后重新尝试,或在预览大图中加载完毕后选择");
            return;
        }
        ZLSelectPhotoModel *model = [[ZLSelectPhotoModel alloc] init];
        model.asset = asset;
        model.localIdentifier = asset.localIdentifier;
        [self.arraySelectPhotos addObject:model];
    } else {
        for (ZLSelectPhotoModel *model in self.arraySelectPhotos) {
            if ([model.localIdentifier isEqualToString:asset.localIdentifier]) {
                [self.arraySelectPhotos removeObject:model];
                break;
            }
        }
    }

    btn.selected = !btn.selected;
    [self changeBtnCameraTitle];
}

- (void)changeBtnCameraTitle
{
    if (self.arraySelectPhotos.count > 0) {
        [self.btnCamera setTitle:[NSString stringWithFormat:@"确定(%ld)", self.arraySelectPhotos.count] forState:UIControlStateNormal];
        [self.btnCamera setTitleColor:kRGB(19, 153, 231) forState:UIControlStateNormal];
    } else {
        [self.btnCamera setTitle:@"拍照" forState:UIControlStateNormal];
        [self.btnCamera setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }
}

#pragma mark - 请求所选择图片、回调
- (void)requestSelPhotos:(UIViewController *)vc
{
    ZLProgressHUD *hud = [[ZLProgressHUD alloc] init];
    [hud show];

    weakify(self);
    NSMutableArray *photos = [NSMutableArray arrayWithCapacity:self.arraySelectPhotos.count];
    for (int i = 0; i < self.arraySelectPhotos.count; i++) {
        [photos addObject:@""];
    }

    CGFloat scale = self.isSelectOriginalPhoto?1:[UIScreen mainScreen].scale;
    for (int i = 0; i < self.arraySelectPhotos.count; i++) {
        ZLSelectPhotoModel *model = self.arraySelectPhotos[i];
        [[ZLPhotoTool sharePhotoTool] requestImageForAsset:model.asset scale:scale resizeMode:PHImageRequestOptionsResizeModeExact completion:^(UIImage *image) {
            strongify(weakSelf);
            if (image) [photos replaceObjectAtIndex:i withObject:[self scaleImage:image]];

            for (id obj in photos) {
                if ([obj isKindOfClass:[NSString class]]) return;
            }

            [hud hide];
            [strongSelf done:photos];
            [strongSelf hide];
            [vc.navigationController dismissViewControllerAnimated:YES completion:nil];
        }];
    }
}

/**
 * @brief 这里对拿到的图片进行缩放,不然原图直接返回的话会造成内存暴涨
 */
- (UIImage *)scaleImage:(UIImage *)image
{
    CGSize size = CGSizeMake(ScalePhotoWidth, ScalePhotoWidth * image.size.height / image.size.width);
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

- (void)done:(NSArray<UIImage *> *)photos
{
    if (self.handler) {
        self.handler(photos, self.arraySelectPhotos.copy);
        self.handler = nil;
    }
}

#pragma mark - UICollectionDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.maxPreviewCount>_arrayDataSources.count?_arrayDataSources.count:self.maxPreviewCount;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ZLCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ZLCollectionCell" forIndexPath:indexPath];

    cell.btnSelect.selected = NO;
    PHAsset *asset = _arrayDataSources[indexPath.row];
    weakify(self);
    [self getImageWithAsset:asset completion:^(UIImage *image, NSDictionary *info) {
        strongify(weakSelf);
        cell.imageView.image = image;
        for (ZLSelectPhotoModel *model in strongSelf.arraySelectPhotos) {
            if ([model.localIdentifier isEqualToString:asset.localIdentifier]) {
                cell.btnSelect.selected = YES;
                break;
            }
        }
    }];

    cell.btnSelect.tag = indexPath.row;
    [cell.btnSelect addTarget:self action:@selector(cell_btn_Click:) forControlEvents:UIControlEventTouchUpInside];

    return cell;
}

#pragma mark - UICollectionViewDelegate
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PHAsset *asset = self.arrayDataSources[indexPath.row];
    return [self getSizeWithAsset:asset];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ZLShowBigImgViewController *svc = [[ZLShowBigImgViewController alloc] init];
    svc.assets         = _arrayDataSources;
    svc.arraySelectPhotos = [NSMutableArray arrayWithArray:_arraySelectPhotos];
    svc.selectIndex    = indexPath.row;
    svc.maxSelectCount = _maxSelectCount;
    svc.isPresent = YES;
    svc.shouldReverseAssets = YES;
    weakify(self);
    __weak typeof(svc) weakSvc  = svc;
    [svc setOnSelectedPhotos:^(NSArray<ZLSelectPhotoModel *> *selectedPhotos, BOOL isSelectOriginalPhoto) {
        strongify(weakSelf);
        strongSelf.isSelectOriginalPhoto = isSelectOriginalPhoto;
        [strongSelf.arraySelectPhotos removeAllObjects];
        [strongSelf.arraySelectPhotos addObjectsFromArray:selectedPhotos];
        [strongSelf changeBtnCameraTitle];
        [strongSelf.collectionView reloadData];
    }];
    [svc setBtnDoneBlock:^(NSArray<ZLSelectPhotoModel *> *selectedPhotos, BOOL isSelectOriginalPhoto) {
        strongify(weakSelf);
        __strong typeof(weakSvc) strongSvc = weakSvc;
        strongSelf.isSelectOriginalPhoto = isSelectOriginalPhoto;
        [strongSelf.arraySelectPhotos removeAllObjects];
        [strongSelf.arraySelectPhotos addObjectsFromArray:selectedPhotos];
        [strongSelf requestSelPhotos:strongSvc];
    }];
    [self presentVC:svc];
}

- (void)presentVC:(UIViewController *)vc
{
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    nav.navigationBar.translucent = YES;

    [nav.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor]}];
    [nav.navigationBar setBackgroundImage:[self imageWithColor:kRGB(255, 212, 79)] forBarMetrics:UIBarMetricsDefault];
    [nav.navigationBar setTintColor:[UIColor whiteColor]];
    [self.sender presentViewController:nav animated:YES completion:nil];
}

- (UIImage *)imageWithColor:(UIColor*)color
{
    CGRect rect=CGRectMake(0,0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    weakify(self);
    [picker dismissViewControllerAnimated:YES completion:^{
        strongify(weakSelf);
        if (strongSelf.handler) {
            UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
            ZLProgressHUD *hud = [[ZLProgressHUD alloc] init];
            [hud show];

            [[ZLPhotoTool sharePhotoTool] saveImageToAblum:image completion:^(BOOL suc, PHAsset *asset) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (suc) {
                        ZLSelectPhotoModel *model = [[ZLSelectPhotoModel alloc] init];
                        model.asset = asset;
                        model.localIdentifier = asset.localIdentifier;
                        strongSelf.handler(@[[strongSelf scaleImage:image]], @[model]);
                    } else {
                        ShowToastLong(@"保存图片到相册失败");
                    }
                    [hud hide];
                    [strongSelf hide];
                });
            }];
        }
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    weakify(self);
    [picker dismissViewControllerAnimated:YES completion:^{
        strongify(weakSelf);
        [strongSelf hide];
    }];
}

#pragma mark - 获取图片及图片尺寸的相关方法
- (CGSize)getSizeWithAsset:(PHAsset *)asset
{
    CGFloat width  = (CGFloat)asset.pixelWidth;
    CGFloat height = (CGFloat)asset.pixelHeight;
    CGFloat scale = width/height;

    return CGSizeMake(self.collectionView.frame.size.height*scale, self.collectionView.frame.size.height);
}

- (void)getImageWithAsset:(PHAsset *)asset completion:(void (^)(UIImage *image, NSDictionary *info))completion
{
    CGSize size = [self getSizeWithAsset:asset];
    size.width  *= 1.5;
    size.height *= 1.5;
    [[ZLPhotoTool sharePhotoTool] requestImageForAsset:asset size:size resizeMode:PHImageRequestOptionsResizeModeFast completion:completion];
}

@end


text:
import React from 'react'
import GameCard from './GameCard'

const GameList = ({ games, selectGame, deleteGame }) => (
  <React.Fragment>
    {
      games ?
      games.map( (game) => <GameCard key={game.id} name={game.name} id={game.id}
        selectGame={selectGame} deleteGame={deleteGame}/>)
        : null
    }
  </React.Fragment>
)

export default GameList


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

using Rant.Compiler;
using Rant.Stringes.Tokens;

namespace Rant
{
    internal class Block
    {
        private readonly Tuple<double, IEnumerable<Token<R>>>[] _items;

        public readonly double WeightTotal;

        private Block(IEnumerable<IEnumerable<Token<R>>> items)
        {
            _items = items.Select(item =>
            {
                double weight = 1;
                if (item.Any())
                {
                    var first = item.First();
                    if (first.ID == R.Weight)
                    {
                        weight = Double.Parse(first.Value);
                        return Tuple.Create(weight, item.Skip(1).SkipWhile(token => token.ID == R.Whitespace));
                    }

                    return Tuple.Create(weight, item.SkipWhile(token => token.ID == R.Whitespace));
                }
                return Tuple.Create(weight, item);
            }).ToArray();

            WeightTotal = _items.Sum(t => t.Item1);
        }

        public static Block Create(IEnumerable<IEnumerable<Token<R>>> items)
        {
            return new Block(items);
        }

        public Tuple<double, IEnumerable<Token<R>>>[] Items => _items;
    }
}


text:
struct _UMURB_HEADER
{
    //
    // Fields filled in by client driver
    //
    IN USHORT Length;
    IN USHORT Function;
    IN WINUSB_INTERFACE_HANDLE InterfaceHandle;

    OUT DWORD Status; //obtained using GetLastError();
};

typedef _UMURB_HEADER* PUMURB_HEADER;

struct _UMURB_PIPE_REQUEST {
    struct _UMURB_HEADER Hdr;                 // function code indicates get or set.
    IN UCHAR PipeID;
    IN ULONG Reserved;
};

struct _UMURB_SELECT_INTERFACE {
    struct _UMURB_HEADER Hdr;                 // function code indicates get or set.
    IN UCHAR AlternateSetting;
};

struct _UMURB_CONTROL_TRANSFER {
    struct _UMURB_HEADER Hdr;                 // function code indicates get or set.
    IN UCHAR Reserved; //maybe use for PipeID
    IN OUT PVOID TransferBuffer;
    IN OUT ULONG TransferBufferLength;
    IN WINUSB_SETUP_PACKET SetupPacket;
};

struct _UMURB_BULK_OR_INTERRUPT_TRANSFER {
    struct _UMURB_HEADER Hdr;                 // function code indicates get or set.
    IN UCHAR PipeID;
    IN BOOL  InPipe;   //in km this is determined based on the pipe,
                       //but WinUsb has two different functions
                       //since host can't store pipe type and it would be expensive to discover it
                       //with every transfer, it is better if direction is sent in as a parameter
    IN OUT ULONG TransferBufferLength;
    IN OUT PVOID TransferBuffer;
};

struct _UMURB_CONTROL_DESCRIPTOR_REQUEST {
    struct _UMURB_HEADER Hdr;                 // function code indicates get or set.
    IN PVOID Reserved;
    IN ULONG Reserved0;
    IN OUT ULONG TransferBufferLength;
    OUT PVOID TransferBuffer;
    IN UCHAR Index;
    IN UCHAR DescriptorType;
    IN USHORT LanguageId;
    IN USHORT Reserved2;
};

struct _UMURB_PIPE_POLICY_REQUEST
{
    struct _UMURB_HEADER Hdr;
    IN UCHAR PipeID;
    IN ULONG PolicyType;
    IN OUT ULONG ValueLength;
    IN OUT PVOID Value;
};

struct _UMURB_INTERFACE_POLICY_REQUEST
{
    struct _UMURB_HEADER Hdr;
    IN ULONG PolicyType;
    IN OUT ULONG ValueLength;
    IN OUT PVOID Value;
};

struct _UMURB_QUERY_PIPE
{
    struct _UMURB_HEADER Hdr;
    IN UCHAR AlternateSetting;
    IN UCHAR PipeID;
    OUT WINUSB_PIPE_INFORMATION PipeInformation;
};

struct _UMURB_CONTROL_GET_INTERFACE_REQUEST {
    struct _UMURB_HEADER Hdr;                 // function code indicates get or set.
    IN UCHAR InterfaceIndex;
};

struct _UMURB_GET_ASSOCIATED_INTERFACE {
    IN struct _UMURB_HEADER Hdr;
    IN UCHAR InterfaceIndex;
    OUT WINUSB_INTERFACE_HANDLE InterfaceHandle;
};

struct _UMURB_INTERFACE_INFORMATION {
    IN struct _UMURB_HEADER Hdr;
    IN UCHAR AlternateSetting;
    OUT USB_INTERFACE_DESCRIPTOR UsbInterfaceDescriptor;
};

struct _UMURB_DEVICE_INFORMATION {
    IN struct _UMURB_HEADER Hdr;
    IN ULONG InformationType;
    IN OUT ULONG BufferLength;
    OUT PVOID Buffer;
};

struct _UMURB_DESCRIPTOR_REQUEST {
    IN struct _UMURB_HEADER Hdr;
    IN  UCHAR DescriptorType;
    IN  UCHAR Index;
    IN  USHORT LanguageID;
    IN OUT ULONG BufferLength;
    OUT PVOID Buffer;
};

typedef struct _UMURB {
    union {
        struct _UMURB_HEADER
            UmUrbHeader;

        struct _UMURB_SELECT_INTERFACE
            UmUrbSelectInterface;

        struct _UMURB_PIPE_REQUEST
            UmUrbPipeRequest;

        struct _UMURB_CONTROL_TRANSFER
            UmUrbControlTransfer;

        struct _UMURB_BULK_OR_INTERRUPT_TRANSFER
            UmUrbBulkOrInterruptTransfer;

        // for standard control transfers on the default pipe
        struct _UMURB_CONTROL_DESCRIPTOR_REQUEST
            UmUrbControlDescriptorRequest;

        struct _UMURB_CONTROL_GET_INTERFACE_REQUEST
            UmUrbControlGetInterfaceRequest;

        struct _UMURB_INTERFACE_POLICY_REQUEST
            UmUrbInterfacePolicyRequest;
        struct _UMURB_PIPE_POLICY_REQUEST
            UmUrbPipePolicyRequest;
        struct _UMURB_QUERY_PIPE
            UmUrbQueryPipe;
        struct _UMURB_GET_ASSOCIATED_INTERFACE
            UmUrbGetAssociatedInterface;
        struct _UMURB_INTERFACE_INFORMATION
            UmUrbInterfaceInformation;
        struct _UMURB_DEVICE_INFORMATION
            UmUrbDeviceInformation;
        struct _UMURB_DESCRIPTOR_REQUEST
            UmUrbDescriptorRequest;
    };
} UMURB, *PUMURB;

//
// Conflicts with ddk\inc\wdf\umdf\2.0\wdfrequest.h
//
typedef enum _WDF_REQUEST_TYPE_PRE20
{
    WdfRequestUndefined_PRE20        = 0,
    WdfRequestCreate_PRE20           = 1,
    WdfRequestCleanup_PRE20          = 2,
    WdfRequestRead_PRE20             = 3,
    WdfRequestWrite_PRE20            = 4,
    WdfRequestDeviceIoControl_PRE20  = 5,
    WdfRequestClose_PRE20            = 6,
    WdfRequestUsb_PRE20              = 7,
    WdfRequestOther_PRE20            = 8,
    WdfRequestInternalIoctl_PRE20    = 9,
    WdfRequestTypeNoFormat_PRE20     = 10,
    WdfRequestMaximum_PRE20

} WDF_REQUEST_TYPE_PRE20, *PWDF_REQUEST_TYPE_PRE20;

#define FILE_DEVICE_UMDF      ((ULONG)(0x8002))

//
// Device IO Control
//
#define UMDF_IOCTL_CODE(id)        \
        CTL_CODE(FILE_DEVICE_UMDF, (id), METHOD_BUFFERED, FILE_READ_ACCESS|FILE_WRITE_ACCESS)

#define IOCTL_INETRNAL_USB_SUBMIT_UMURB              UMDF_IOCTL_CODE(0x100)