text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="Andrew Lord | www.andrew-lord.co.uk">

    <meta http-equiv="cache-control" content="no-cache" />
    <meta http-equiv="expires" content="0" />
    <meta http-equiv="pragma" content="no-cache" />

    <link rel="apple-touch-icon" sizes="57x57" href="/apple-touch-icon-57x57.png?v=2">
    <link rel="apple-touch-icon" sizes="60x60" href="/apple-touch-icon-60x60.png?v=2">
    <link rel="apple-touch-icon" sizes="72x72" href="/apple-touch-icon-72x72.png?v=2">
    <link rel="apple-touch-icon" sizes="76x76" href="/apple-touch-icon-76x76.png?v=2">
    <link rel="apple-touch-icon" sizes="114x114" href="/apple-touch-icon-114x114.png?v=2">
    <link rel="apple-touch-icon" sizes="120x120" href="/apple-touch-icon-120x120.png?v=2">
    <link rel="apple-touch-icon" sizes="144x144" href="/apple-touch-icon-144x144.png?v=2">
    <link rel="apple-touch-icon" sizes="152x152" href="/apple-touch-icon-152x152.png?v=2">
    <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon-180x180.png?v=2">
    <link rel="icon" type="image/png" href="/favicon-32x32.png?v=2" sizes="32x32">
    <link rel="icon" type="image/png" href="/android-chrome-192x192.png?v=2" sizes="192x192">
    <link rel="icon" type="image/png" href="/favicon-96x96.png?v=2" sizes="96x96">
    <link rel="icon" type="image/png" href="/favicon-16x16.png?v=2" sizes="16x16">
    <link rel="manifest" href="/manifest.json?v=2">
    <link rel="shortcut icon" href="/favicon.ico?v=2">
    <meta name="apple-mobile-web-app-title" content="Blast Cap Games">
    <meta name="application-name" content="Blast Cap Games">
    <meta name="msapplication-TileColor" content="#00aba9">
    <meta name="msapplication-TileImage" content="/mstile-144x144.png?v=2">
    <meta name="theme-color" content="#ffffff">

    <title>Blast Cap Games - Games for Android and iOS</title>

    <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

    <link href="css/main.css" rel="stylesheet" type="text/css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#main-navbar-collapse">
                    Toggle navigation

                </button>
                Blast Cap Games

                        Home

                        Games

                        Contact

We LOVE making games YOU love

We create fun, addictive and high quality games for all ages

Our games are simple to play, but difficult to master and impossible to put down

Play our games for free on iOS and Android, for devices of all sizes

Follow us by using the icons below, for gameplay videos, images, reviews and more!

If you have any more questions, feel free to contact us

                            Contact Us

Our Games

Wacky Bat: Swoop Outta Dodge

Wacky Bat has managed to get himself trapped in a dangerous cave, full of obstacles. See how far you can fly, to try and beat your previous best! It gets harder to survive the further you fly, especially when the pillars start to move. Download NOW to experience the addictive game-play!

Contact Us

You can get in touch via Facebook, Twitter or Google+. Or if you would rather email us directly then please use the contact link below.

                Enquiries

Copyright © Blast Cap Games Ltd 2014

Privacy Policy

Return to Top


text:
typedef enum
{
    PACKET_RECEIVED,
    PACKET_SENT,
    PACKET_LOST,
} radio_evt_type_t;

typedef struct __attribute__((packed))
{
    uint8_t len;
    struct __attribute__((packed))
    {
        uint8_t padding : 7;
        uint8_t ack : 1;
    } flags;
    uint8_t data[RADIO_PACKET_MAX_LEN];
} radio_packet_t;

typedef struct
{
   radio_evt_type_t type;
   union
   {
       radio_packet_t packet;
   };
} radio_evt_t;

typedef void (radio_evt_handler_t)(radio_evt_t * evt);

uint32_t radio_init(radio_evt_handler_t * evt_handler);
uint32_t radio_send(radio_packet_t * packet);
uint32_t radio_receive_start(void);

#endif

redpajama_set_name: RedPajamaGithub


text:
package com.ozz.springboot.config.interceptor;

import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 拦截器:由Spring调用 ,能实现Filter的功能,可以IoC注入Spring里的资源,AOP的一种实现策略
 */
@Component
public class MyHandlerInterceptor implements HandlerInterceptor {
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    System.out.println(String.format("%s.preHandle(): contextPath=%s, requestURI=%s", getClass().getSimpleName(), request.getContextPath(), request.getRequestURI()));
    return true;
  }
  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    System.out.println(String.format("%s.afterCompletion(): contextPath=%s, requestURI=%s", getClass().getSimpleName(), request.getContextPath(), request.getRequestURI()));
  }
}


text:
layout:     post
title:      "Mutation testing in Elixir"
subtitle:   "introducing exavier"
date:       2019-07-22 12:19:00
author:     "Daniel Serrano"
header-img: "img/mutation-testing-elixir/cover.jpg"
header-img-author-name: "Adrien Converse"
header-img-author-url: "https://unsplash.com/@lurm"
---

I first heard about mutation testing when attending a Ruby meetup here in Lisbon. At the time [Tadas](https://twitter.com/tadassce) presentation focused on [`mutant`](https://github.com/mbj/mutant), **the** Ruby library for mutation testing by [mbj](https://twitter.com/_m_b_j_).

It sounded fun, but not very practical. I think that was because I didn't understand the full scope, goals and philosophy, so to speak, of mutation testing. This post will help explore mutation testing and why Elixir is a good candidate to give it a shot. I will then introduce a library I've been working on [`exavier`](https://github.com/dnlserrano/exavier) which aims to provide a full-blown mutation testing framework for Elixir.

It's still very early days, it may be haunted by major design flaws, stupid ideas and this blog post also serves a bit as a call for help. If you're out there reading and you think mutation testing might be your thing and you want to help, hit me up [@dnlserrano](https://twitter.com/dnlserrano) or [open a PR](https://github.com/dnlserrano/exavier).

# What is mutation testing?

Let's take a step back and discuss what exactly all of this is. Mutation testing is a software testing technique to ensure quality in your tests whereby one runs the same set of unit tests multiple times, making different small changes (mutations) to the source code under test each time. The intuition behind it is easy: if the same green tests you had continue to be green after you've applied the mutations on the original source code, then something must be off.

Consider the following example of a simple `even?/1` function that checks if a given number is even:

```elixir
defmodule HelloWorld do
  def even?(x), do: rem(x, 2) == 0
end
```

We could think of adding this simple test:

```elixir
defmodule HelloWorldTest do
  use ExUnit.Case, async: true

  @subject HelloWorld

  test "when even" do
    assert @subject.even?(2) == true
  end
end
```

With this, we're testing a basic case of an even number. Good, right?

Imagine we now _mutate_ the original code to the following:

```elixir
defmodule HelloWorld do
  def even?(x), do: rem(x, 2) >= 0 # == replaced by >=
end
```

Our test will still be green given `rem(2, 2)` yields `0`, which is of course still _greater than or equal to_ (`>=`) `0`.

This is what we refer to as a "live mutant". Code is changed, but the test still passes. For each test you run, which will contain a given mutation, you register if it passed (generated a live mutant) or failed (mutant is successfully killed). This will be important for actually using mutation testing in practice, which I will address later on in this post.

So, we changed our source code, and the test still passes. This says something about our tests. In this case in particular, it tells us we're not considering a scenario in which, the remainder of 2 being greater than 0, the return of the function should be `false` rather than `true`. If you think about what it means for a second, turns out we forgot to test the "odd cases":

```elixir
defmodule HelloWorldTest do
  use ExUnit.Case, async: true

  @subject HelloWorld

  test "when even" do
    assert @subject.even?(2) == true
  end

  test "when odd" do
    assert @subject.even?(3) == false
  end
end
```

Now one of the tests would still pass, but we'd have a new one that would fail. Summing it up, we have:

- 1 live mutant
    - test "when even", still passed after mutation
- 1 killed mutant
    - test "when odd", failed after mutation

It means we had a killed mutant rate of 1/2, which translates to 50% "mutation coverage."

### Using mutation testing

Using mutation testing "in the wild" can translate into running it as part of your CI pipeline on every merge to `master`. Each time you do that, your unit tests will run. If they pass, you can run a mutation suite and verify that your mutation coverage is above a specified threshold (e.g., 70%). Other options may ideally be passed to the mutation testing framework you're using so you can further tweak your mutation test suite. Such configurations might involve excluding certain files from mutation testing, only running it for specified folders, modifying the default threshold value, etc.1

# exavier

I've implemented the ideas of mutation testing into an Elixir library I called [`exavier`](https://github.com/dnlserrano/exavier). Its goal is to provide a full-blown mutation testing framework (think `ex_unit` for mutation testing with much worse performance and code quality at this point in time). You can run a set of mutation tests by doing:

`mix exavier.test`

The output would be something like the following:

```
......................

(...)

16) test when infinity (Elixir.HelloWorldTest)
  - if(y == :special) do
  -   :yes
  - else
  -   :no
  - end

  + if(true) do
  +   :yes
  + else
  +   :no
  + end

/Users/dnlserrano/Repos/exavier/test/hello_world_test.exs:10

22 tests, 6 failed (mutants killed), 16 passed (mutants survived)
27.27% mutation coverage
```

It reports each mutant that survived, alongside the mutation(s) made and shows an aggregate result of your mutation coverage.

## Mutators

Mutators specify ways in which we can mutate the code. Currently we have 5 proof-of-concept mutators available in `exavier`. It should be easy to extend the library with other mutators or even have the possibility (soon) to run your own custom mutators that live only inside your specific code-base, if that's more your thing.

Each mutator works by manipulating the [AST](https://en.wikipedia.org/wiki/Abstract_syntax_tree) of Elixir code, and that's part of what makes Elixir such a great fit for trying to develop such a testing framework in this language. Having so many powerful tools around code and the structure of that code in the language, it seemed like an amazing opportunity that shouldn't be missed. That and the fact it was fun, of course.

---

The library still needs a lot of work, particularly around adding more mutators and configurations. The major points I'd like to see tackled in the short-time are available in the ["To be done"](https://github.com/dnlserrano/exavier#to-be-done) section of the project's README.

I'd love to have some feedback about how you're using `exavier` and what we can, hopefully together as a community, do to make it better.

Happy mutations! 🖖

---

1 A very well-known issue in mutation testing is that of [Equivalent Mutations](http://pitest.org/quickstart/basic_concepts/#equivalent-mutations), which is out of the scope of this blog post.


text:
<?php

final class Language_Set extends GWF_Method
{
	public function getHTAccess()
	{
		return 'RewriteRule ^lang-to-([a-z]{2})/?$ index.php?mo=Language&me=Set&iso=$1 [QSA]'.PHP_EOL;
	}

	public function execute()
	{
		if (false !== ($iso = Common::getGet('iso')))
		{
			$this->module->setLanguage($iso);
		}
//		GWF_Session::commit();
		GWF_Website::redirectBack();
		die();
//		header(sprintf('Location: %s', GWF_Website::getRedirectURL()));
	}

}

?>


text:
/* $NetBSD: if_awi_pcmcia.c,v 1.28 2003/10/22 09:13:17 mjl Exp $ */

/*-
 * Copyright (c) 1999 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Bill Sommerfeld
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *        This product includes software developed by the NetBSD
 *        Foundation, Inc. and its contributors.
 * 4. Neither the name of The NetBSD Foundation nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * PCMCIA attachment for BayStack 650 802.11FH PCMCIA card,
 * based on the AMD 79c930 802.11 controller chip.
 *
 * This attachment can probably be trivially adapted for other FH and
 * DS cards based on the same chipset.
 */

#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: if_awi_pcmcia.c,v 1.28 2003/10/22 09:13:17 mjl Exp $");

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/mbuf.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/errno.h>
#include <sys/syslog.h>
#include <sys/select.h>
#include <sys/device.h>

#include <net/if.h>
#include <net/if_dl.h>
#include <net/if_ether.h>
#include <net/if_media.h>

#include <net80211/ieee80211_var.h>
#include <net80211/ieee80211_compat.h>

#include <machine/cpu.h>
#include <machine/bus.h>
#include <machine/intr.h>

#include <dev/ic/am79c930reg.h>
#include <dev/ic/am79c930var.h>
#include <dev/ic/awireg.h>
#include <dev/ic/awivar.h>

#include <dev/pcmcia/pcmciareg.h>
#include <dev/pcmcia/pcmciavar.h>
#include <dev/pcmcia/pcmciadevs.h>

static int awi_pcmcia_match(struct device *, struct cfdata *, void *);
static void awi_pcmcia_attach(struct device *, struct device *, void *);
static int awi_pcmcia_detach(struct device *, int);
static int awi_pcmcia_enable(struct awi_softc *);
static void awi_pcmcia_disable(struct awi_softc *);

struct awi_pcmcia_softc {
	struct awi_softc sc_awi;		/* real "awi" softc */

	/* PCMCIA-specific goo */
	struct pcmcia_io_handle sc_pcioh;	/* PCMCIA i/o space info */
	struct pcmcia_mem_handle sc_memh;	/* PCMCIA memory space info */
	int sc_io_window;			/* our i/o window */
	int sc_mem_window;			/* our memory window */
	struct pcmcia_function *sc_pf;		/* our PCMCIA function */
	void *sc_ih;				/* interrupt handler */
};

static int	awi_pcmcia_find __P((struct awi_pcmcia_softc *,
    struct pcmcia_attach_args *, struct pcmcia_config_entry *));

CFATTACH_DECL(awi_pcmcia, sizeof(struct awi_pcmcia_softc),
    awi_pcmcia_match, awi_pcmcia_attach, awi_pcmcia_detach, awi_activate);

static const struct awi_pcmcia_product {
	u_int32_t	app_vendor;	/* vendor ID */
	u_int32_t	app_product;	/* product ID */
	const char	*app_cisinfo[4]; /* CIS information */
	const char	*app_name;	/* product name */
} awi_pcmcia_products[] = {
	{ PCMCIA_VENDOR_BAY,		PCMCIA_PRODUCT_BAY_STACK_650,
	  PCMCIA_CIS_BAY_STACK_650,	PCMCIA_STR_BAY_STACK_650 },

	{ PCMCIA_VENDOR_BAY,		PCMCIA_PRODUCT_BAY_STACK_660,
	  PCMCIA_CIS_BAY_STACK_660,	PCMCIA_STR_BAY_STACK_660 },

	{ PCMCIA_VENDOR_BAY,		PCMCIA_PRODUCT_BAY_SURFER_PRO,
	  PCMCIA_CIS_BAY_SURFER_PRO,	PCMCIA_STR_BAY_SURFER_PRO },

	{ PCMCIA_VENDOR_AMD,		PCMCIA_PRODUCT_AMD_AM79C930,
	  PCMCIA_CIS_AMD_AM79C930,	PCMCIA_STR_AMD_AM79C930 },

	{ PCMCIA_VENDOR_ICOM,		PCMCIA_PRODUCT_ICOM_SL200,
	  PCMCIA_CIS_ICOM_SL200,	PCMCIA_STR_ICOM_SL200 },

	{ PCMCIA_VENDOR_NOKIA,		PCMCIA_PRODUCT_NOKIA_C020_WLAN,
	  PCMCIA_CIS_NOKIA_C020_WLAN,	PCMCIA_STR_NOKIA_C020_WLAN },

	{ PCMCIA_VENDOR_FARALLON,	PCMCIA_PRODUCT_FARALLON_SKYLINE,
	  PCMCIA_CIS_FARALLON_SKYLINE,	PCMCIA_STR_FARALLON_SKYLINE },

	{ 0,				0,
	  { NULL, NULL, NULL, NULL },	NULL },
};

static const struct awi_pcmcia_product *
	awi_pcmcia_lookup __P((struct pcmcia_attach_args *));

static const struct awi_pcmcia_product *
awi_pcmcia_lookup(pa)
	struct pcmcia_attach_args *pa;
{
	const struct awi_pcmcia_product *app;

	for (app = awi_pcmcia_products; app->app_name != NULL; app++) {
		/* match by vendor/product id */
		if (pa->manufacturer != PCMCIA_VENDOR_INVALID &&
		    pa->manufacturer == app->app_vendor &&
		    pa->product != PCMCIA_PRODUCT_INVALID &&
		    pa->product == app->app_product)
			return (app);

		/* match by CIS information */
		if (pa->card->cis1_info[0] != NULL &&
		    app->app_cisinfo[0] != NULL &&
		    strcmp(pa->card->cis1_info[0], app->app_cisinfo[0]) == 0 &&
		    pa->card->cis1_info[1] != NULL &&
		    app->app_cisinfo[1] != NULL &&
		    strcmp(pa->card->cis1_info[1], app->app_cisinfo[1]) == 0)
			return (app);
	}

	return (NULL);
}

static int
awi_pcmcia_enable(sc)
	struct awi_softc *sc;
{
	struct awi_pcmcia_softc *psc = (struct awi_pcmcia_softc *)sc;
	struct pcmcia_function *pf = psc->sc_pf;

	/* establish the interrupt. */
	psc->sc_ih = pcmcia_intr_establish(pf, IPL_NET, awi_intr, sc);
	if (psc->sc_ih == NULL) {
		printf("%s: couldn't establish interrupt\n",
		    sc->sc_dev.dv_xname);
		return (1);
	}

	if (pcmcia_function_enable(pf)) {
		pcmcia_intr_disestablish(pf, psc->sc_ih);
		return (1);
	}
	DELAY(1000);

	return (0);
}

static void
awi_pcmcia_disable(sc)
	struct awi_softc *sc;
{
	struct awi_pcmcia_softc *psc = (struct awi_pcmcia_softc *)sc;
	struct pcmcia_function *pf = psc->sc_pf;

	pcmcia_function_disable(pf);
	pcmcia_intr_disestablish(pf, psc->sc_ih);
}

static int
awi_pcmcia_match(parent, match, aux)
	struct device *parent;
	struct cfdata *match;
	void *aux;
{
	struct pcmcia_attach_args *pa = aux;

	if (awi_pcmcia_lookup(pa) != NULL)
		return (1);

	return (0);
}

static int
awi_pcmcia_find(psc, pa, cfe)
	struct awi_pcmcia_softc *psc;
	struct pcmcia_attach_args *pa;
	struct pcmcia_config_entry *cfe;
{
	struct awi_softc *sc = &psc->sc_awi;
	int fail = 0;

	/*
	 * see if we can read the firmware version sanely
	 * through the i/o ports.
	 * if not, try a different CIS string..
	 */
	if (pcmcia_io_alloc(psc->sc_pf, cfe->iospace[0].start,
	    cfe->iospace[0].length, AM79C930_IO_ALIGN,
	    &psc->sc_pcioh) != 0)
		goto fail;

	if (pcmcia_io_map(psc->sc_pf, PCMCIA_WIDTH_AUTO, 0, psc->sc_pcioh.size,
	    &psc->sc_pcioh, &psc->sc_io_window))
		goto fail_io_free;

	/* Enable the card. */
	pcmcia_function_init(psc->sc_pf, cfe);
	if (pcmcia_function_enable(psc->sc_pf))
		goto fail_io_unmap;

	sc->sc_chip.sc_bustype = AM79C930_BUS_PCMCIA;
	sc->sc_chip.sc_iot = psc->sc_pcioh.iot;
	sc->sc_chip.sc_ioh = psc->sc_pcioh.ioh;
	am79c930_chip_init(&sc->sc_chip, 0);

	DELAY(1000);

	awi_read_bytes(sc, AWI_BANNER, sc->sc_banner, AWI_BANNER_LEN);

	if (memcmp(sc->sc_banner, "PCnetMobile:", 12) == 0)
		return (0);

	fail++;
	pcmcia_function_disable(psc->sc_pf);

 fail_io_unmap:
	fail++;
	pcmcia_io_unmap(psc->sc_pf, psc->sc_io_window);

 fail_io_free:
	fail++;
	pcmcia_io_free(psc->sc_pf, &psc->sc_pcioh);
 fail:
	fail++;
	psc->sc_io_window = -1;
	return (fail);
}

static void
awi_pcmcia_attach(parent, self, aux)
	struct device  *parent, *self;
	void           *aux;
{
	struct awi_pcmcia_softc *psc = (void *)self;
	struct awi_softc *sc = &psc->sc_awi;
	const struct awi_pcmcia_product *app;
	struct pcmcia_attach_args *pa = aux;
	struct pcmcia_config_entry *cfe;
	bus_size_t memoff;

	app = awi_pcmcia_lookup(pa);
	if (app == NULL)
		panic("awi_pcmcia_attach: impossible");

	psc->sc_pf = pa->pf;

	SIMPLEQ_FOREACH(cfe, &pa->pf->cfe_head, cfe_list) {
		if (cfe->iftype != PCMCIA_IFTYPE_IO)
			continue;
		if (cfe->num_iospace < 1)
			continue;
		if (cfe->iospace[0].length < AM79C930_IO_SIZE)
			continue;

		if (awi_pcmcia_find(psc, pa, cfe) == 0)
			break;
	}
	if (cfe == NULL) {
		printf(": no suitable CIS info found\n");
		goto no_config_entry;
	}

	sc->sc_enabled = 1;
	printf(": %s\n", app->app_name);

	psc->sc_mem_window = -1;
	if (pcmcia_mem_alloc(psc->sc_pf, AM79C930_MEM_SIZE,
	    &psc->sc_memh) != 0) {
		printf("%s: unable to allocate memory space; using i/o only\n",
		    sc->sc_dev.dv_xname);
	} else if (pcmcia_mem_map(psc->sc_pf,
	    PCMCIA_WIDTH_MEM8|PCMCIA_MEM_COMMON, AM79C930_MEM_BASE,
	    AM79C930_MEM_SIZE, &psc->sc_memh, &memoff, &psc->sc_mem_window)) {
		printf("%s: unable to map memory space; using i/o only\n",
		    sc->sc_dev.dv_xname);
		pcmcia_mem_free(psc->sc_pf, &psc->sc_memh);
	} else {
		sc->sc_chip.sc_memt = psc->sc_memh.memt;
		sc->sc_chip.sc_memh = psc->sc_memh.memh;
		am79c930_chip_init(&sc->sc_chip, 1);
	}

	sc->sc_enable = awi_pcmcia_enable;
	sc->sc_disable = awi_pcmcia_disable;

	/* establish the interrupt. */
	psc->sc_ih = pcmcia_intr_establish(psc->sc_pf, IPL_NET, awi_intr, sc);
	if (psc->sc_ih == NULL) {
		printf("%s: couldn't establish interrupt\n",
		    sc->sc_dev.dv_xname);
		goto no_interrupt;
	}
	sc->sc_cansleep = 1;

	if (awi_attach(sc) != 0) {
		printf("%s: failed to attach controller\n",
		    sc->sc_dev.dv_xname);
		goto attach_failed;
	}

	sc->sc_enabled = 0;
	/* disable device and disestablish the interrupt */
	awi_pcmcia_disable(sc);
	return;

 attach_failed:
	pcmcia_intr_disestablish(psc->sc_pf, psc->sc_ih);

 no_interrupt:
	/* Unmap our memory window and space */
	if (psc->sc_mem_window != -1) {
		pcmcia_mem_unmap(psc->sc_pf, psc->sc_mem_window);
		pcmcia_mem_free(psc->sc_pf, &psc->sc_memh);
	}

	/* Unmap our i/o window and space */
	pcmcia_io_unmap(psc->sc_pf, psc->sc_io_window);
	pcmcia_io_free(psc->sc_pf, &psc->sc_pcioh);

	/* Disable the function */
	pcmcia_function_disable(psc->sc_pf);

 no_config_entry:
	psc->sc_io_window = -1;
}

static int
awi_pcmcia_detach(self, flags)
	struct device *self;
	int flags;
{
	struct awi_pcmcia_softc *psc = (struct awi_pcmcia_softc *)self;
	int error;

	if (psc->sc_io_window == -1)
		/* Nothing to detach. */
		return (0);

	error = awi_detach(&psc->sc_awi);
	if (error != 0)
		return (error);

	/* Unmap our memory window and free memory space */
	if (psc->sc_mem_window != -1) {
		pcmcia_mem_unmap(psc->sc_pf, psc->sc_mem_window);
		pcmcia_mem_free(psc->sc_pf, &psc->sc_memh);
	}

	/* Unmap our i/o window. */
	pcmcia_io_unmap(psc->sc_pf, psc->sc_io_window);

	/* Free our i/o space. */
	pcmcia_io_free(psc->sc_pf, &psc->sc_pcioh);
	return (0);
}


text:
//
//  NSData+DTCrypto.h
//  DTFoundation
//
//  Created by Stefan Gugarel on 10/3/12.
//  Copyright (c) 2012 Cocoanetics. All rights reserved.
//

/**
 Useful cryptography methods
 */

@interface NSData (DTCrypto)

/**-------------------------------------------------------------------------------------
 @name Generating HMAC Hashes
 ---------------------------------------------------------------------------------------
 */

/**
 Generates a HMAC from the receiver using the SHA1 algorithm
 @param key The encryption key
 @returns The encrypted hash
 */
- (NSData *)encryptedDataUsingSHA1WithKey:(NSData *)key;

@end


text:
using System;

using CatFight.Data;
using CatFight.Fighters;
using CatFight.Stages.Arena;
using CatFight.Util.ObjectPool;

using UnityEngine;

namespace CatFight.Items.Specials
{
    [RequireComponent(typeof(PooledObject))]
    public sealed class Chaff : SpecialAmmo
    {
        [SerializeField]
        private GameObject _missileTargetObject;

        private PooledObject _pooledObject;

        private IChaffTarget _target;

#region Unity Lifecycle
        private void Awake()
        {
            _pooledObject = GetComponent<PooledObject>();
            _pooledObject.RecycleEvent += RecycleEventHandler;
        }
#endregion

        public override void Initialize(Fighter fighter, SpecialData.SpecialType specialType, int damage)
        {
            base.Initialize(fighter, specialType, damage);

            fighter.Stats.AddChaff(this);

// TODO: chaff should fly up and then fall down
        }

        protected override void Destroy()
        {
            _target?.OnChaffDied();

            Fighter.Stats.RemoveChaff(this);

            //_missileTargetObject.SetActive(false);

            base.Destroy();
        }

        public void Use(IChaffTarget target)
        {
            Fighter.Stats.RemoveChaff(this);
            //_missileTargetObject.SetActive(true);

            _target = target;
        }

        public void Release()
        {
            //_missileTargetObject.SetActive(false);
            Fighter.Stats.AddChaff(this);

            _target = null;
        }

        protected override void OnArenaCollision(ArenaEdge edge)
        {
            base.OnArenaCollision(edge);

            if(edge.IsGround) {
                _pooledObject.Recycle();
            }
        }

#region Event Handlers
        private void RecycleEventHandler(object sender, EventArgs evt)
        {
            Destroy();
        }
#endregion
    }
}


text:
SingulariD
==========

IDE for the D programming language with web-based UI

## Status

SingulariD is currently in it's planning stage, see the docs folder.


text:
import cookie from 'react-cookie'
import { extend } from 'lodash'
import fetchJSON from '../../redux/utils/fetchJSON'
import { reset, getValues } from 'redux-form'
import constants from '../../constants/questions/constants.js'

// ------------------------------------
// Actions: Sync
// ------------------------------------
export const createStart = (question): Action => ({
  type: constants.QUESTION_CREATE_START,
  question: question
})
export const createSuccess = (question): Action => ({
  type: constants.QUESTION_CREATE_SUCCESS,
  question: question
})
export const createError = (error, question): Action => ({
  type: constants.QUESTION_CREATE_ERROR,
  error: error,
  question: question
})

// ------------------------------------
// Actions: Async
// ------------------------------------
export const createQuestion = (successCallback = () => {}) => {
  return (dispatch, getState) => {
    let data = getValues(getState().form.question)
    let currentUser = getState().currentUser
    if (currentUser.loggedIn) {
      data = extend({}, data, {owner_id: currentUser.id})
    }
    dispatch(createStart(data))
    return fetchJSON(constants.INDEX_URL, { post: data, token: cookie.load('token') })
      .then(json => dispatch(createSuccess(json))).then(successCallback)
      // .catch(json => dispatch(createError(json))) // TODO: catch does't work here for some reason
  }
}
export const resetForm = () => {
  return (dispatch, getState) => {
    dispatch(reset('question'))
  }
}

// Actions List
export const actions = {
  createQuestion,
  resetForm
}

// ------------------------------------
// Reducer
// ------------------------------------
const initialState = {}
export default function questionReducer (state: initialState, action: Action): Object {
  switch (action.type) {
    case constants.QUESTION_CREATE_START:
      return {
        id: action.id,
        category: action.category,
        title: action.title,
        answer: action.answer,
        importance: action.importance,
        difficult: action.difficult,
        tags: action.tags
      }
    case constants.QUESTION_CREATE_SUCCESS:
      return {
        id: action.id,
        category: action.category,
        title: action.title,
        answer: action.answer,
        importance: action.importance,
        difficult: action.difficult,
        tags: action.tags
      }
    case constants.QUESTION_CREATE_ERROR:
      return {
        id: action.id,
        category: action.category,
        title: action.title,
        answer: action.answer,
        importance: action.importance,
        difficult: action.difficult,
        tags: action.tags
      }
    default:
      return state
  }
}


text:
page_type: sample
languages:
- csharp
products:
- azure
- azure-maps
name: Azure.Maps.Search samples for .NET
description: Samples for the Azure.Maps.Search client library.
---

# Azure.Maps.Search Samples

For different APIs, please refer the following samples:

* [Search Addresses](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/maps/Azure.Maps.Search/samples/SearchAddressSamples.md)
* [Reverse Search Addresses](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/maps/Azure.Maps.Search/samples/ReverseSearchAddressSamples.md)
* [Fuzzy Search](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/maps/Azure.Maps.Search/samples/FuzzySearchSamples.md)
* [GeoJson Search](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/maps/Azure.Maps.Search/samples/GeoJsonSearchSamples.md) (Including `search inside geometry`, `search point of interests`, `get polygons`)


text:
namespace RBAC {

  export class RBACTasksFactory {
    static create(postLoginTasks: Core.Tasks, jolokia: Jolokia.IJolokia, $q: ng.IQService): RBACTasks {
      'ngInject';
      let rbacTasks = new RBACTasksImpl($q.defer());
      postLoginTasks.addTask("FetchJMXSecurityMBeans", () => rbacTasks.fetchJMXSecurityMBeans(jolokia));
      return rbacTasks;
    }
  }

  export class RBACACLMBeanFactory {
    static create(rbacTasks: RBACTasks): ng.IPromise<string> {
      'ngInject';
      return rbacTasks.getACLMBean();
    }
  }

  class RBACTasksImpl extends Core.Tasks implements RBACTasks {

    private ACLMBean: string = null;

    constructor(private deferred: ng.IDeferred<string>) {
      super("RBAC");
    }

    fetchJMXSecurityMBeans(jolokia: Jolokia.IJolokia): void {
      jolokia.request(
        { type: 'search', mbean: '*:type=security,area=jmx,*' },
        Core.onSuccess((response) => {
          log.debug("Fetching JMXSecurity MBeans...", response);
          let mbeans = response.value as string[];
          let chosen = "";
          if (mbeans.length === 0) {
            log.info("Didn't discover any JMXSecurity mbeans, client-side role based access control is disabled");
          } else if (mbeans.length === 1) {
            chosen = mbeans[0];
          } else if (mbeans.length > 1) {
            let picked = false;
            mbeans.forEach((mbean) => {
              if (picked) {
                return;
              }
              if (_.includes(mbean, "HawtioDummy")) {
                return;
              }
              if (!_.includes(mbean, "rank=")) {
                chosen = mbean;
                picked = true;
              }
            });
          }
          if (chosen != null && chosen != "") {
            log.info("Using mbean", chosen, "for client-side role based access control");
          } else {
            log.info("Didn't discover any effective JMXSecurity mbeans, client-side role based access control is disabled");
          }
          this.initialize(chosen);
        }));
    }

    initialize(mbean: string): void {
      this.ACLMBean = mbean;
      this.deferred.resolve(this.ACLMBean);
      super.execute();
    }

    getACLMBean(): ng.IPromise<string> {
      return this.deferred.promise;
    }
  }

}


text:
package org.elasticsearch.xpack.graph.rest.action;

import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.core.RestApiVersion;
import org.elasticsearch.core.Tuple;
import org.elasticsearch.protocol.xpack.graph.GraphExploreRequest;
import org.elasticsearch.protocol.xpack.graph.GraphExploreResponse;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.test.rest.FakeRestRequest;
import org.elasticsearch.test.rest.RestActionTestCase;
import org.elasticsearch.xcontent.XContentType;
import org.junit.Before;
import org.mockito.Mockito;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import static org.hamcrest.Matchers.instanceOf;

public class RestGraphActionTests extends RestActionTestCase {
    private final List<String> compatibleMediaType = Collections.singletonList(randomCompatibleMediaType(RestApiVersion.V_7));

    @Before
    public void setUpAction() {
        controller().registerHandler(new RestGraphAction());
        verifyingClient.setExecuteVerifier((actionType, request) -> {
            assertThat(request, instanceOf(GraphExploreRequest.class));
            return Mockito.mock(GraphExploreResponse.class);
        });
    }

    public void testTypeInPath() {
        for (Tuple<RestRequest.Method, String> methodAndPath : List.of(
            Tuple.tuple(RestRequest.Method.GET, "/some_index/some_type/_graph/explore"),
            Tuple.tuple(RestRequest.Method.POST, "/some_index/some_type/_graph/explore"),
            Tuple.tuple(RestRequest.Method.GET, "/some_index/some_type/_xpack/graph/_explore"),
            Tuple.tuple(RestRequest.Method.POST, "/some_index/some_type/_xpack/graph/_explore")
        )) {

            RestRequest request = new FakeRestRequest.Builder(xContentRegistry()).withHeaders(
                Map.of(
                    "Accept",
                    compatibleMediaType,
                    "Content-Type",
                    Collections.singletonList(compatibleMediaType(XContentType.VND_JSON, RestApiVersion.V_7))
                )
            ).withMethod(methodAndPath.v1()).withPath(methodAndPath.v2()).withContent(new BytesArray("{}"), null).build();

            dispatchRequest(request);
            assertCriticalWarnings(RestGraphAction.TYPES_DEPRECATION_MESSAGE);
        }
    }
}


text:
package com.amazonaws.services.s3.model;

import java.io.Serializable;

import com.amazonaws.AmazonWebServiceRequest;
import com.amazonaws.services.s3.AmazonS3Client;

/**
 *

 * Provides options for obtaining the metadata for the specified Amazon S3
 * object without actually fetching the object contents. This is useful if
 * obtaining only object metadata, and avoids wasting bandwidth from retrieving
 * the object data.
 *

 *

 * The object metadata contains information such as content type, content
 * disposition, etc., as well as custom user metadata that can be associated
 * with an object in Amazon S3.
 *

 *

 * For more information about enabling versioning for a bucket, see
 * {@link AmazonS3Client#setBucketVersioningConfiguration(SetBucketVersioningConfigurationRequest)}
 * .
 *

 *
 * @see GetObjectMetadataRequest#GetObjectMetadataRequest(String, String)
 * @see GetObjectMetadataRequest#GetObjectMetadataRequest(String, String, String)
 * @see GetObjectRequest
 */
public class GetObjectMetadataRequest extends AmazonWebServiceRequest implements
        SSECustomerKeyProvider, Serializable {
    /**
     * The name of the bucket containing the object's whose metadata is being
     * retrieved.
     */
    private String bucketName;

    /**
     * The key of the object whose metadata is being retrieved.
     */
    private String key;

    /**
     * The optional version ID of the object version whose metadata is being
     * retrieved. If not specified, the latest version will be used.
     */
    private String versionId;

    /**
     * If enabled, the requester is charged for downloading the metadata from
     * Requester Pays Buckets.
     */
    private boolean isRequesterPays;

    /**
     * The optional customer-provided server-side encryption key to use when
     * retrieving the metadata of a server-side encrypted object.
     */
    private SSECustomerKey sseCustomerKey;

    /**
     * The optional part number to find the number of parts of an object.
     */
    private Integer partNumber;

    /**
     * Constructs a new
     * {@link GetObjectMetadataRequest}
     * used to retrieve a specified
     * object's metadata.
     *
     * @param bucketName
     *            The name of the bucket containing the object whose metadata
     *            is being retrieved.
     * @param key
     *            The key of the object whose metadata is being retrieved.
     *
     * @see GetObjectMetadataRequest#GetObjectMetadataRequest(String bucketName, String key, String versionId)
     */
    public GetObjectMetadataRequest(String bucketName, String key) {
        setBucketName(bucketName);
        setKey(key);
    }

    /**
     * Constructs a new
     * {@link GetObjectMetadataRequest}
     * with basic options.
     *
     * @param bucketName
     *            The name of the bucket containing the object whose metadata
     *            is being retrieved.
     * @param key
     *            The key of the object whose metadata is being retrieved.
     * @param versionId
     *            The version ID of the object version whose metadata is being
     *            retrieved.
     *
     * @see GetObjectMetadataRequest#GetObjectMetadataRequest(String bucketName, String key)
     */
    public GetObjectMetadataRequest(String bucketName, String key, String versionId) {
        this(bucketName, key);
        setVersionId(versionId);
    }

    /**
     * Gets the name of the bucket containing the object whose metadata is
     * being retrieved.
     *
     * @return The name of the bucket containing the object whose metadata is
     *         being retrieved.
     *
     * @see GetObjectMetadataRequest#setBucketName(String bucketName)
     * @see GetObjectMetadataRequest#withBucketName(String)
     */
    public String getBucketName() {
        return bucketName;
    }

    /**
     * Sets the name of the bucket containing the object whose metadata is
     * being retrieved.
     *
     * @param bucketName
     *            The name of the bucket containing the object's whose metadata
     *            is being retrieved.
     *
     * @see GetObjectMetadataRequest#getBucketName()
     * @see GetObjectMetadataRequest#withBucketName(String)
     */
    public void setBucketName(String bucketName) {
        this.bucketName = bucketName;
    }

    /**
     * Sets the name of the bucket containing the object whose metadata is
     * being retrieved.
     * Returns this {@link GetObjectMetadataRequest}, enabling additional method
     * calls to be chained together.
     *
     * @param bucketName
     *            The name of the bucket containing the object's whose metadata
     *            is being retrieved.
     *
     * @return This {@link GetObjectMetadataRequest}, enabling additional method
     *         calls to be chained together.
     *
     * @see GetObjectMetadataRequest#getBucketName()
     * @see GetObjectMetadataRequest#setBucketName(String bucketName)
     */
    public GetObjectMetadataRequest withBucketName(String bucketName) {
        setBucketName(bucketName);
        return this;
    }

    /**
     * Gets the key of the object whose metadata is being retrieved.
     *
     * @return The key of the object whose metadata is being retrieved.
     *
     * @see GetObjectMetadataRequest#setKey(String)
     * @see GetObjectMetadataRequest#withKey(String)
     */
    public String getKey() {
        return key;
    }

    /**
     * Sets the key of the object whose metadata is being retrieved.
     *
     * @param key
     *            The key of the object whose metadata is being retrieved.
     *
     * @see GetObjectMetadataRequest#getKey()
     * @see GetObjectMetadataRequest#withKey(String)
     */
    public void setKey(String key) {
        this.key = key;
    }

    /**
     * Sets the key of the object whose metadata is being retrieved.
     * Returns this {@link GetObjectMetadataRequest}, enabling additional method
     * calls to be chained together.
     *
     * @param key
     *            The key of the object whose metadata is being retrieved.
     *
     * @return This {@link GetObjectMetadataRequest}, enabling additional method
     *         calls to be chained together.
     *
     * @see GetObjectMetadataRequest#getKey()
     * @see GetObjectMetadataRequest#setKey(String)
     */
    public GetObjectMetadataRequest withKey(String key) {
        setKey(key);
        return this;
    }

    /**
     * Gets the optional version ID of the object version whose metadata is
     * being retrieved. If not specified, the latest version will be used.
     *
     * @return The optional version ID of the object version whose metadata is
     *         being retrieved. If not specified, the latest version will be
     *         used.
     *
     * @see GetObjectMetadataRequest#setVersionId(String)
     * @see GetObjectMetadataRequest#withVersionId(String)
     */
    public String getVersionId() {
        return versionId;
    }

    /**
     * Sets the optional version ID of the object version whose metadata is
     * being retrieved. If not specified, the latest version will be used.
     *
     * @param versionId
     *            The optional version ID of the object version whose metadata
     *            is being retrieved. If not specified, the latest version will
     *            be used.
     *
     * @see GetObjectMetadataRequest#getVersionId()
     * @see GetObjectMetadataRequest#withVersionId(String)
     */
    public void setVersionId(String versionId) {
        this.versionId = versionId;
    }

    /**
     * Sets the optional version ID of the object version whose metadata is
     * being retrieved.
     * Returns this {@link GetObjectMetadataRequest}, enabling additional method
     * calls to be chained together.
     * If not specified, the latest version will be used.
     *
     * @param versionId
     *            The optional version ID of the object version whose metadata
     *            is being retrieved.
     *
     * @return This {@link GetObjectMetadataRequest}, enabling additional method
     *         calls to be chained together.
     *
     * @see GetObjectMetadataRequest#getVersionId()
     * @see GetObjectMetadataRequest#setVersionId(String)
     */
    public GetObjectMetadataRequest withVersionId(String versionId) {
        setVersionId(versionId);
        return this;
    }

    /**
     * Returns true if the user has enabled Requester Pays option when
     * downloading the object metadata from Requester Pays Bucket; else false.
     *
     *

     * If a bucket is enabled for Requester Pays, then any attempt to read an
     * object from it without Requester Pays enabled will result in a 403 error
     * and the bucket owner will be charged for the request.
     *
     *

     * Enabling Requester Pays disables the ability to have anonymous access to
     * this bucket
     *
     * @return true if the user has enabled Requester Pays option for
     *         downloading the object metadata from Requester Pays Bucket.
     */
    public boolean isRequesterPays() {
        return isRequesterPays;
    }

    /**
     * Used for downloading an Amazon S3 Object metadata from a Requester Pays Bucket. If
     * set the requester is charged for downloading the data from the bucket.
     *
     *

     * If a bucket is enabled for Requester Pays, then any attempt to read an
     * object metadata from it without Requester Pays enabled will result in a 403 error
     * and the bucket owner will be charged for the request.
     *
     *

     * Enabling Requester Pays disables the ability to have anonymous access to
     * this bucket
     *
     * @param isRequesterPays
     *            Enable Requester Pays option for the operation.
     */
    public void setRequesterPays(boolean isRequesterPays) {
        this.isRequesterPays = isRequesterPays;
    }

    /**
     * Used for conducting this operation from a Requester Pays Bucket. If
     * set the requester is charged for requests from the bucket. It returns this
     * updated GetObjectMetadataRequest object so that additional method calls can be
     * chained together.
     *
     *

     * If a bucket is enabled for Requester Pays, then any attempt to upload or
     * download an object from it without Requester Pays enabled will result in
     * a 403 error and the bucket owner will be charged for the request.
     *
     *

     * Enabling Requester Pays disables the ability to have anonymous access to
     * this bucket.
     *
     * @param isRequesterPays
     *            Enable Requester Pays option for the operation.
     *
     * @return The updated GetObjectMetadataRequest object.
     */
    public GetObjectMetadataRequest withRequesterPays(boolean isRequesterPays) {
        setRequesterPays(isRequesterPays);
        return this;
    }

    @Override
    public SSECustomerKey getSSECustomerKey() {
        return sseCustomerKey;
    }

    /**
     * Sets the optional customer-provided server-side encryption key to use
     * when retrieving the metadata of a server-side encrypted object.
     *
     * @param sseKey
     *            The optional customer-provided server-side encryption key to
     *            use when retrieving the metadata of a server-side encrypted
     *            object.
     */
    public void setSSECustomerKey(SSECustomerKey sseKey) {
        this.sseCustomerKey = sseKey;
    }

    /**
     * Sets the optional customer-provided server-side encryption key to use
     * when retrieving the metadata of a server-side encrypted object, and
     * retuns the updated request object so that additional method calls can be
     * chained together.
     *
     * @param sseKey
     *            The optional customer-provided server-side encryption key to
     *            use when retrieving the metadata of a server-side encrypted
     *            object.
     *
     * @return This updated request object so that additional method calls can
     *         be chained together.
     */
    public GetObjectMetadataRequest withSSECustomerKey(SSECustomerKey sseKey) {
        setSSECustomerKey(sseKey);
        return this;
    }

    /**
     *

     * Returns the optional part number that indicates a part in multipart object.
     *

     *
     * @return The part number representing a part in a multipart object.
     *
     * @see GetObjectMetadataRequest#setPartNumber(Integer)
     * @see GetObjectMetadataRequest#withPartNumber(Integer)
     */
    public Integer getPartNumber() {
        return partNumber;
    }

    /**
     *

     * Sets the optional part number to find the number of parts of an object.
     *

     *

     * To find the number of parts of an object, set partNumber to 1 and observe the x-amz-mp-parts-count response.
     * If the object exists and x-amz-mp-parts-count is missing it's implicitly 1.
     * Otherwise number of parts is equal to the value returned by x-amz-mp-parts-count.
     *

     *

     * The valid range for part number is 1 - 10000 inclusive.
     * For partNumber < 1, an AmazonS3Exception is thrown with response code 400 bad request
     * For partNumber larger than actual part count,  an AmazonS3Exception is thrown with response code 416 Request Range Not Satisfiable
     *

     *
     * @param partNumber
     *            The part number representing a part in a multipart object.
     *
     * @see GetObjectMetadataRequest#getPartNumber()
     * @see GetObjectMetadataRequest#withPartNumber(Integer)
     */
    public void setPartNumber(Integer partNumber) {
        this.partNumber = partNumber;
    }

    /**
     *

     * Sets the optional part number to find the number of parts of an object.
     *

     *

     * To find the number of parts of an object, set partNumber to 1 and observe the x-amz-mp-parts-count response.
     * If the object exists and x-amz-mp-parts-count is missing it's implicitly 1.
     * Otherwise number of parts is equal to the value returned by x-amz-mp-parts-count.
     *

     *

     * The valid range for part number is 1 - 10000 inclusive.
     * For partNumber < 1, an AmazonS3Exception is thrown with response code 400 bad request
     * For partNumber larger than actual part count,  an AmazonS3Exception is thrown with response code 416 Request Range Not Satisfiable
     *

     *
     * @param partNumber
     *            The part number representing a part in a multipart object.
     *
     * @return This {@link GetObjectRequest}, enabling additional method
     *         calls to be chained together.
     *
     * @see GetObjectMetadataRequest#getPartNumber()
     * @see GetObjectMetadataRequest#setPartNumber(Integer)
     */
    public GetObjectMetadataRequest withPartNumber(Integer partNumber) {
        setPartNumber(partNumber);
        return this;
    }

}


text:
import numpy as np
import json
import os
import sys
import time
import argparse

import ray
from ray.data import DatasetPipeline

import pandas as pd

GiB = 1024 * 1024 * 1024

@ray.remote(num_cpus=0.5)
class ConsumingActor:
    def __init__(self, rank):
        self._rank = rank

    def consume(self, split):
        DoConsume(split, self._rank)

def DoConsume(split, rank):
    prefetch_blocks = 1
    batch_size = 4096
    num_epochs = 2

    start = time.perf_counter()
    epochs_read, batches_read, bytes_read = 0, 0, 0
    batch_delays = []

    def generate_epochs(data, epochs: int):
        if isinstance(data, DatasetPipeline):
            for epoch in data.iter_epochs(epochs):
                yield epoch
        else:
            # Dataset
            for _ in range(epochs):
                yield data

    for epoch_data in generate_epochs(split, num_epochs):
        epochs_read += 1
        batch_start = time.perf_counter()
        for batch in epoch_data.iter_batches(
            prefetch_blocks=prefetch_blocks, batch_size=batch_size
        ):
            batch_delay = time.perf_counter() - batch_start
            batch_delays.append(batch_delay)
            batches_read += 1
            if isinstance(batch, pd.DataFrame):
                bytes_read += int(batch.memory_usage(index=True, deep=True).sum())
            elif isinstance(batch, np.ndarray):
                bytes_read += batch.nbytes
            else:
                # NOTE: This isn't recursive and will just return the size of
                # the object pointers if list of non-primitive types.
                bytes_read += sys.getsizeof(batch)
            batch_start = time.perf_counter()
    delta = time.perf_counter() - start

    print("Time to read all data", delta, "seconds")
    print(
        "P50/P95/Max batch delay (s)",
        np.quantile(batch_delays, 0.5),
        np.quantile(batch_delays, 0.95),
        np.max(batch_delays),
    )
    print("Num epochs read", epochs_read)
    print("Num batches read", batches_read)
    print("Num bytes read", round(bytes_read / (1024 * 1024), 2), "MiB")
    print("Mean throughput", round(bytes_read / (1024 * 1024) / delta, 2), "MiB/s")

    if rank == 0:
        print("Ingest stats from rank=0:\n\n{}".format(split.stats()))

def make_ds(size_gb: int):
    # Dataset of 10KiB tensor records.
    total_size = 1024 * 1024 * 1024 * size_gb
    record_dim = 1280
    record_size = record_dim * 8
    num_records = int(total_size / record_size)
    dataset = ray.data.range_tensor(num_records, shape=(record_dim,), parallelism=200)
    print("Created dataset", dataset, "of size", dataset.size_bytes())
    return dataset

def run_ingest_bulk(dataset, num_workers):
    consumers = [
        ConsumingActor.options(scheduling_strategy="SPREAD").remote(i)
        for i in range(num_workers)
    ]
    ds = dataset.map_batches(lambda df: df * 2)
    splits = ds.split(num_workers, equal=True, locality_hints=consumers)
    future = [consumers[i].consume.remote(s) for i, s in enumerate(splits)]
    ray.get(future)

    # Example ballpark number for transformation (5s):
    # Read->Map_Batches: 201/201 Time to read all data 5.001230175999922 seconds

    # Example ballpark number for consumption i.e. at an actor (consumer):
    # Time to read all data 5.275932452000006 seconds
    # P50/P95/Max batch delay (s) 0.010558151499992618 0.010944704699983276 0.04179979600007755  # noqa: E501
    # Num epochs read 2
    # Num batches read 512
    # Num bytes read 20480.0 MiB
    # Mean throughput 3881.78 MiB/s

    # Example total time:
    # success! total time 13.813468217849731

def run_ingest_streaming(dataset, num_workers):
    consumers = [
        ConsumingActor.options(scheduling_strategy="SPREAD").remote(i)
        for i in range(num_workers)
    ]
    p = (
        dataset.window(bytes_per_window=40 * GiB)
        .repeat()
        .map_batches(lambda df: df * 2)
    )
    splits = p.split(num_workers, equal=True, locality_hints=consumers)
    future = [consumers[i].consume.remote(s) for i, s in enumerate(splits)]
    ray.get(future)

    # Example ballpark numbers:
    # == Pipeline Window 10 ==
    # Stage 1 read->map_batches: 40/40 blocks executed in 1.98s
    # * Remote wall time: 1.38s min, 1.66s max, 1.46s mean, 58.26s total
    # * Remote cpu time: 1.38s min, 1.7s max, 1.46s mean, 58.33s total
    # * Peak heap memory usage (MiB): 6533908000.0 min, 10731508000.0 max, 9710443300 mean  # noqa: E501
    # * Output num rows: 104857 min, 104857 max, 104857 mean, 4194280 total
    # * Output size bytes: 1074155212 min, 1074155212 max, 1074155212 mean, 42966208480 total  # noqa: E501
    # * Tasks per node: 2 min, 2 max, 2 mean; 20 nodes used

    # Example actor (consumer):
    # Time to read all data 25.58030511100003 seconds
    # P50/P95/Max batch delay (s) 0.010486626999977489 0.012674414999997904 2.0688196870000866  # noqa: E501
    # Num epochs read 2
    # Num batches read 512
    # Num bytes read 20480.0 MiB
    # Mean throughput 800.62 MiB/s

    # Example total time:
    # success! total time 27.822711944580078

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--num-workers", type=int, default=4)
    parser.add_argument("--dataset-size-gb", type=int, default=200)
    parser.add_argument("--streaming", action="store_true", default=False)
    args = parser.parse_args()

    start = time.time()
    ds = make_ds(args.dataset_size_gb)
    if args.streaming:
        run_ingest_streaming(ds, args.num_workers)
    else:
        run_ingest_bulk(ds, args.num_workers)

    delta = time.time() - start
    print(f"success! total time {delta}")
    test_output_json = os.environ.get("TEST_OUTPUT_JSON", "/tmp/result.json")
    with open(test_output_json, "w") as f:
        f.write(json.dumps({"ingest_time": delta, "success": 1}))


text:
// MIT License. Copyright (c) 2016 Maxim Kuzmin. Contacts: https://github.com/maxim-kuzmin

// Author: Maxim Kuzmin

using Makc2016.Core.Execution.Operations.Async;
using Makc2016.Modules.DummyManyToManyLink.Filters;
using Makc2016.Modules.DummyManyToManyLink.Models;
using System;
using System.Threading.Tasks;

namespace Makc2016.Modules.DummyManyToManyLink.Operations.List
{
    /// <summary>
    /// Модули. Модуль "DummyManyToManyLink". Операции. Операция, выполняющая функцию получения списка.
    /// </summary>
    public class ModuleDummyManyToManyLinkOperationListGet : CoreExecutionOperationAsyncWithInputAndOutputData
        <
            ModuleDummyManyToManyLinkFilterList,
            ModuleDummyManyToManyLinkModelList
        >
    {
        #region Constructors

        /// <summary>
        /// Конструктор.
        /// </summary>
        /// <param name="executableFunction">Выполняемая функция.</param>
        public ModuleDummyManyToManyLinkOperationListGet(
            Func<ModuleDummyManyToManyLinkFilterList, Task<ModuleDummyManyToManyLinkModelList>> executableFunction
            ) : base(
                executableFunction,
                null,
                TransformInputData,
                null,
                null
                )
        {
        }

        #endregion Constructors

        #region Internal methods

        internal static ModuleDummyManyToManyLinkFilterList TransformInputData(ModuleDummyManyToManyLinkFilterList inputData)
        {
            if (inputData == null)
            {
                inputData = new ModuleDummyManyToManyLinkFilterList();
            }

            inputData.Normalize();

            return inputData;
        }

        #endregion Internal methods
    }
}


text:
//
//  ViewController.m
//  localpost
//
//  Created by Roger on 4/11/15.
//  Copyright (c) 2015 Roger Zou and Charles Zhang. All rights reserved.
//

//current issue: Core Data syncing over web (ideally via Parse, though that 1000 object limit is annoying...). Want to have easiest, most lightweight framework. Have considered NSIncrementalStore, Dropbox Datastore, among others. Ultimately Parse's object API is easiest and seems like it would be globally accessible across all copies of the app. Going to completely synchronize them such that practically one-to-one.
//http://stackoverflow.com/questions/5035132/how-to-sync-iphone-core-data-with-web-server-and-then-push-to-other-devices?rq=1
//http://www.raywenderlich.com/17927/how-to-synchronize-core-data-with-a-web-service-part-2

#import <CoreData/CoreData.h>
#import "ViewController.h"
#import "City.h"
#import "Post.h"
#import "AppDelegate.h"
#import "MyCustomAnnotation.h"

@import AddressBookUI;

@interface ViewController () <CLLocationManagerDelegate,MKMapViewDelegate>

@property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;
//@property (nonatomic, strong) NSFetchedResultsController *fetchedResultsController; //fuck it
@property (weak, nonatomic) IBOutlet UITextField *messageTextField;
@property (weak, nonatomic) IBOutlet UIDatePicker *expireDatePicker;
@property (nonatomic, strong) City *currCity;
@property (nonatomic, strong) UIToolbar *blurToolbar;

@end

@implementation ViewController
int startCount = 1;
- (IBAction)unhideCover:(id)sender {
    if (self.coverView.hidden == true) {
        self.coverView.hidden = false;
        self.expireDatePicker.date = [NSDate date];
    }
    else {
        self.coverView.hidden = true;
    }
}

- (IBAction)addEvent:(id)sender {
    //add to core data thing
    Post *currpost = [NSEntityDescription insertNewObjectForEntityForName:@"Post" inManagedObjectContext:self.managedObjectContext];
    if (self.messageTextField.text.length <= 40) {
        currpost.message = self.messageTextField.text;
        // ASSUMES IT'S 24 HOUR DEPENDENT ON THE SLIDER/DISPLAY. 1.0 to 24 hours
        currpost.expireTime = [NSDate dateWithTimeIntervalSinceNow:self.slider.value * 360]; //60 * 60 = 360. slider is 1-24

        currpost.latitude = [NSDecimalNumber decimalNumberWithDecimal: [@(mapview.userLocation.location.coordinate.latitude) decimalValue]];
        currpost.longitude = [NSDecimalNumber decimalNumberWithDecimal:[@(mapview.userLocation.location.coordinate.longitude)decimalValue]];
        currpost.city = self.currCity;
        [self.currCity addPostsObject:currpost];
        NSError *error;
        if (![self.managedObjectContext save:&error])
        NSLog(@"fail sav, %@", [error localizedDescription]);
        //put down a pin
        MKPointAnnotation *annot = [[MKPointAnnotation alloc]init];
        [annot setCoordinate:CLLocationCoordinate2DMake(mapview.userLocation.location.coordinate.latitude, mapview.userLocation.location.coordinate.longitude)];
        [annot setTitle:self.messageTextField.text];
        [mapview addAnnotation:annot];

        //hide
        self.coverView.hidden = true;
        [self.blurToolbar removeFromSuperview];
        self.messageTextField.text = @"";
    }
    else {
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Failed to Post"
                                                                       message:@"Message needs to be 40 characters or less."
                                                                preferredStyle:UIAlertControllerStyleAlert];

        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                              handler:^(UIAlertAction * action) {}];

        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
        self.messageTextField.text = @"";

    }
}

- (IBAction)onSlide:(id)sender {
    self.sliderLabel.text = [NSString stringWithFormat:@"Display message for %0.1f hours", self.slider.value];
}

@synthesize mapview;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    //test Parse code
    //PFObject *testobj = [PFObject objectWithClassName:@"TestObject"];
    //testobj[@"foo"] = @"bar";
    //[testobj saveInBackground];

    //test, my code for core data
    //NSManagedObjectContext *context = self.managedObjectContext;

    //default start as hidden
    self.coverView.hidden = true;

    // default slider
    self.slider.minimumValue = 1;
    self.slider.maximumValue = 24;

        //charles' mapview code
    mapview.showsUserLocation = YES;
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    // TODO: Add NSLocationWhenInUseUsageDescription in MyApp-Info.plist and give it a string

    // Check for iOS 8
    if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
        [self.locationManager requestWhenInUseAuthorization];
    }

    //MKMapViewDelegate * mapDelegate = [[MKMapViewDelegate alloc]init];
    mapview.delegate = self;

    [[self locationManager] startUpdatingLocation];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidDisappear:(BOOL)animated {
    //self.fetchedResultsController = nil;
    [super viewDidDisappear:animated];
}

- (NSManagedObjectContext *)managedObjectContext
{
    if (_managedObjectContext)
        return _managedObjectContext;

    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    _managedObjectContext = [appDelegate managedObjectContext];
    return _managedObjectContext;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    CLLocation *location = locations.lastObject;

    if (startCount != 0) {
        self.location = location;
        MKCoordinateRegion region=MKCoordinateRegionMakeWithDistance(location.coordinate, 200, 200);
        [self.mapview setRegion:region animated: YES];
    /*

    MKCoordinateRegion region=MKCoordinateRegionMakeWithDistance(location.coordinate, 200, 200);
    [self.mapview setRegion:region animated: NO];

    [[self labelLatitude] setText:[NSString stringWithFormat:@"%.6f", location.coordinate.latitude]];
    [[self labelLongitude] setText:[NSString stringWithFormat:@"%.6f", location.coordinate.longitude]];
    [[self labelAltitude] setText:[NSString stringWithFormat:@"%.2f feet", location.altitude]];
    */
    }
    startCount = 0;

    //update current city and get local posts
    if (!self.currCity) {
        CLGeocoder *geocoder = [[CLGeocoder alloc]init];
        [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
            if (error)
                NSLog(@"reverse geolocate error, %@", [error localizedDescription]);
            else {
                CLPlacemark *placemark = [placemarks lastObject];
                //use locality concat w/ zipcode
                //get city and display posts here
                NSString *cityID;
                if (placemark.locality)
                    if (placemark.postalCode)
                        cityID = [placemark.locality stringByAppendingString:placemark.postalCode];
                    else
                        cityID = placemark.locality;
                else if (placemark.postalCode)
                    cityID = placemark.postalCode;
                else
                    return; //can't update city, can't post anything. sorry.

                //get stuff
                NSFetchRequest *fetchreq = [[NSFetchRequest alloc]init];
                NSEntityDescription *entity = [NSEntityDescription entityForName:@"City" inManagedObjectContext:self.managedObjectContext];
                [fetchreq setEntity:entity]; //prob

                NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name==%@",
                                          cityID];
                [fetchreq setPredicate:predicate];

                NSError *error;
                NSArray *cities = [self.managedObjectContext executeFetchRequest:fetchreq error:&error];
                if (error)
                    NSLog(@"%@", [error localizedDescription]);
                if ([cities count] == 0) {
                    //no posts for that city
                    //create a City and insert into context for later, then set as currentCity.
                    City *c = [NSEntityDescription insertNewObjectForEntityForName:@"City" inManagedObjectContext:self.managedObjectContext];
                    c.name = cityID;
                    c.posts = [[NSSet alloc]init]; //empty set
                    if(![self.managedObjectContext save:&error])
                        NSLog(@"err inserting city %@, %@", cityID, [error localizedDescription]);
                    else
                        self.currCity = c;
                    return;
                } else if ([cities count] > 3) {
                    NSLog(@"warningsssss this really shouldn't happen!");
                }
                //query should be unique, so just get this. if not unique...uh oh.
                self.currCity = [cities lastObject];
                for (Post *poster in self.currCity.posts) {
                    //add points to the map
                    MKPointAnnotation *annot = [[MKPointAnnotation alloc]init];
                    [annot setCoordinate:CLLocationCoordinate2DMake([poster.latitude doubleValue], [poster.longitude doubleValue])];
                    // doesn't work....
                    MKPinAnnotationView *pinView = [[MKPinAnnotationView alloc]initWithAnnotation:annot reuseIdentifier:@"stuff"];
                    pinView.pinColor = MKPinAnnotationColorPurple;
                    [annot setTitle:poster.message];
                    [mapview addAnnotation:annot];
                }
                if (![self.managedObjectContext save:&error]) {
                    NSLog(@"fail save, %@", [error localizedDescription]);
                }
            }
        }];
    }
}
- (void)searchBar: (UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    NSString * text = searchText;
    NSLog(@"%@", text);
    for (Post *poster in self.currCity.posts) {
        MKPointAnnotation *annot = [[MKPointAnnotation alloc]init];
        [annot setCoordinate:CLLocationCoordinate2DMake([poster.latitude doubleValue], [poster.longitude doubleValue])];
        // doesn't work....
        MKPinAnnotationView *pinView = [[MKPinAnnotationView alloc]initWithAnnotation:annot reuseIdentifier:@"stuff"];
        pinView.pinColor = MKPinAnnotationColorPurple;
        [annot setTitle:poster.message];
        [mapview addAnnotation:annot];

        if ([poster.message rangeOfString:text].location == NSNotFound && ![text isEqualToString:@""]) {
            for (MKPointAnnotation * annot in mapview.annotations) {
                if (annot.title == poster.message) {
                    [mapview removeAnnotation: annot];
                }
            }
        }

    }

}

/*
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIViewController *)control {
    NSLog(@"reached");
    [self performSegueWithIdentifier:@"DetailsIphone" sender:view];

}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MKUserLocation class]])
    {
        return nil;
    }
    else if ([annotation isKindOfClass:[MyCustomAnnotation class]])
    {
        static NSString * const identifier = @"MyCustomAnnotation";

        MKAnnotationView* annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:identifier];

        if (annotationView)
        {
            annotationView.annotation = annotation;
        }
        else
        {
            annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation
                                                          reuseIdentifier:identifier];
        }

        // set your annotationView properties

        annotationView.image = [UIImage imageNamed:@"circle.png"];
        annotationView.canShowCallout = YES;

        // if you add QuartzCore to your project, you can set shadows for your image, too
        //
        // [annotationView.layer setShadowColor:[UIColor blackColor].CGColor];
        // [annotationView.layer setShadowOpacity:1.0f];
        // [annotationView.layer setShadowRadius:5.0f];
        // [annotationView.layer setShadowOffset:CGSizeMake(0, 0)];
        // [annotationView setBackgroundColor:[UIColor whiteColor]];

        return annotationView;
    }

    return nil;

}
*/
@end


text:
static int test = 0;
static bool btest = 0;
static unsigned int latest_num = 0;
static long latest[10] = {0};
static char strtest[20] = "\0";

void usage()
{
    char *msg = "usage: moduleparam_test [test=int] [btest[=bool]] [latest=int array] [strtest=string]\n";
    printf(msg);
}

int unknown_handler(char *param, char *val)
{
    printf("find unknown param: %s\n", param);
    return 0;
}

int main (int argc, char **argv)
{
    init_module_param(4);
    module_param(test, int);
    module_param_bool(btest);
    module_param_array(latest, long, &latest_num);
    module_param_string(strtest, strtest, sizeof(strtest));

    int ret = parse_params(argc, argv, unknown_handler);

    if(ret != 0)
    {
        usage();
        return 0;
    }

    char buf[1024];
    for(int i=0; i < MODULE_INIT_VARIABLE_NUM; ++i)
    {
        MODULE_INIT_VARIABLE[i].get(buf, &MODULE_INIT_VARIABLE[i]);
        printf("%s = %s\n", MODULE_INIT_VARIABLE[i].name, buf);
    }
    return 0;
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<rss version="2.0">
    <channel>
        <title>VPAA Calendar of Events</title>
        <link>http://illinois.edu/calendar/list/3183</link>
        <description>VPAA Event Calendar</description>
    </channel>
</rss>


text:
'use strict';

module.exports = function (N) {
  N.runtime = N.runtime || {};

  N.wire    = require('event-wire')();
  N.router  = require('pointer')('$$ N.router.stringify() $$');
  N.environment  = '$$ JSON.stringify(N.environment) $$';
  N.version_hash = '$$ JSON.stringify(N.version_hash) $$';
  // No need to set default locale in constructor, since we use 1
  // language on client.
  N.i18n    = require('babelfish')('en-US');

  // translation helper with active locale
  N.runtime.t = (phrase, params) => N.i18n.t(N.runtime.locale, phrase, params);

  N.runtime.t.exists = phrase => N.i18n.hasPhrase(N.runtime.locale, phrase);

  N.logger         = require('./kernel/logger');
  N.io             = require('./kernel/io')(N);
  N.runtime.render = require('./kernel/render')(N);

  //
  // Emit io.* events like rpc does to signal user about executing
  // network requests.
  //
  let defaultLoadAssets = N.loader.loadAssets;

  N.loader.loadAssets = function () {
    let args = Array.prototype.slice.call(arguments),
        callback = args[args.length - 1];

    N.wire.emit('io.request');

    args[args.length - 1] = function () {
      N.wire.emit('io.complete', {});
      return callback.apply(this, arguments);
    };

    return defaultLoadAssets.apply(this, args);
  };
};


text:
import { Directive, ElementRef, Input, Output, EventEmitter} from '@angular/core';
import { NgModel} from '@angular/common';

declare var google: any;

@Directive({
    selector: '[google-place-autocomplete]' ,
    providers: [NgModel]
})
export class GooglePlaceAutocompleteDirective {
    @Output() setAddress: EventEmitter<any> = new EventEmitter();

    constructor(private el: ElementRef, private model: NgModel) {
    }

    ngAfterViewInit() {
        var autocomplete = new google.maps.places.Autocomplete(this.el.nativeElement.querySelector('input'), {});

        google.maps.event.addListener(autocomplete, 'place_changed', () => {
            var place = autocomplete.getPlace();
            this.setAddress.emit(place);
        });
    }

}


text:
const { Command, util } = require('klasa');

module.exports = class extends Command {

    constructor(...args) {
        super(...args, {
            name: 'history',
            permLevel: 2,
            runIn: ['text'],

            description: 'Check the history for the mentioned member.',
            usage: '<user:user>'
        });

        this.provider = null;
    }

    async run(msg, [user]) {
        const modlogs = await this.provider.get('modlogs', msg.guild.id).then(data => data || []);
        const userlogs = modlogs.filter(log => log.user.id === user.id);
        if (userlogs.length === 0) return msg.send(`There is no log under the ${user.tag} (${user.id}) account.`);
        const actions = {
            ban: 0,
            unban: 0,
            softban: 0,
            kick: 0,
            warn: 0
        };
        for (const log of userlogs) {
            actions[log.type]++;
        }
        return msg.send([
            `${msg.author}, the user ${user.tag} (${user.id}) has the following logs:`,
            util.codeBlock('http', Object.entries(actions).map(([action, value]) => `${util.toTitleCase(`${action}s`).padEnd(9)}: ${value}`).join('\n'))
        ]);
    }

    init() {
        this.provider = this.client.providers.get('json');
    }

};


text:
WeChat SDK for yii2 , based on [overtrue/wechat](https://github.com/overtrue/wechat).
This extension helps you access `overtrue/wechat` application in a simple & familiar way:   `Yii::$app->wechat`.

## Installation
```
composer require maxwen/yii2-easy-wechat
```

## Configuration

Add the SDK as a yii2 application `component` in the `config/main.php`:

```php

'components' => [
	// ...
	'wechat' => [
		'class' => 'maxwen\easywechat\Wechat',
		// 'userOptions' => []  # user identity class params
		// 'sessionParam' => '' # wechat user info will be stored in session under this key
		// 'returnUrlParam' => '' # returnUrl param stored in session
	],
	// ...
]
```

## Usage
```php

// here are two representative examples that will help you:

// 微信网页授权:
if(Yii::$app->wechat->isWechat && !Yii::$app->wechat->isAuthorized()) {
	return Yii::$app->wechat->authorizeRequired()->send();
}

// 微信支付(JsApi):
$orderData = [
	'openid' => '.. '
	// ... etc.
];
$order = new WechatOrder($orderData);
$payment = Yii::$app->wechat->payment;
$prepayRequest = $payment->prepare($order);
if($prepayRequest->return_code = 'SUCCESS' && $prepayRequest->result_code == 'SUCCESS') {
	$prepayId = $prepayRequest->prepay_id;
}else{
	throw new yii\base\ErrorException('微信支付异常, 请稍后再试');
}

$jsApiConfig = $payment->configForPayment($prepayId);

return $this->render('wxpay', [
	'jsApiConfig' => $jsApiConfig,
	'orderData'   => $orderData
]);

```

### How to load Wechat configures?
the `overtrue/wechat` application always constructs with a `$options` parameter.
I made the options as a yii2 param in the `params.php`:

recomended way:
```php
// in this way you need to create a wechat.php in the same directory of params.php
// put contents in the wechat.php like:
// return [
// 		// wechat options here
// ];
'WECHAT' => require(__DIR__.'/wechat.php'),
```
OR
```php
'WECHAT' => [ // wechat options here ]
```

[Wechat options configure help docs.](https://easywechat.org/zh-cn/docs/configuration.html)

### More documentation
see [EasyWeChat Docs](https://easywechat.org/zh-cn/docs/index.html).

Thanks to `overtrue/wechat` , realy a easy way to play with wechat SDK 😁.

## More repos for Yii2:
[yii2-ckeditor-widget](https://github.com/max-wen/yii2-ckeditor-widget)
[yii2-adminlte-gii](https://github.com/max-wen/yii2-adminlte-gii)
[yii2-curl](https://github.com/max-wen/yii2-curl)


text:
<?php

	$va_errors = $this->getVar('errors');

	if (sizeof($va_errors)) {
		print json_encode(array('status' => 'error', 'errors' => $va_errors, 'set_id' => $this->getVar('set_id'), 'item_id' => $this->getVar('item_id')));
	} else {
		print json_encode(array('status' => 'ok', 'set_id' => $this->getVar('set_id'), 'item_id' => $this->getVar('item_id'), 'idno' => $this->getVar('idno'),  'idno_sort' => $this->getVar('idno_sort'), 'representation_tag' => $this->getVar('representation_tag'), 'representation_url' => $this->getVar('representation_url'),  'representation_width' => $this->getVar('representation_width'),  'representation_height' => $this->getVar('representation_height'), 'set_item_label' => $this->getVar('set_item_label')));
	}
?>


text:
namespace Gu.Units.Wpf
{
    using System;
    using System.Windows.Markup;

    /// <summary>
    /// An <see cref="MarkupExtension"/> for quantities of type <see cref="Speed"/> in XAML.
    /// </summary>
    [MarkupExtensionReturnType(typeof(Speed))]
    public class SpeedExtension : MarkupExtension
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Gu.Units.Wpf.SpeedExtension"/> class.
        /// </summary>
        /// <param name="value"><see cref="Gu.Units.Speed"/>.</param>
        public SpeedExtension(Speed value)
        {
            this.Value = value;
        }

        /// <summary>
        /// Gets the <see cref="Speed"/> value
        /// </summary>
        public Speed Value { get; private set; }

        /// <inheritdoc />
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return this.Value;
        }
    }
}


text:
package main

type item struct {
}


text:
package org.springframework.boot.gradle.testkit;

/**
 * The DSLs supported by Gradle and demonstrated in the documentation samples
 */
public enum Dsl {

	GROOVY("Groovy", ".gradle"), KOTLIN("Kotlin", ".gradle.kts");

	private final String name;

	private final String extension;

	Dsl(String name, String extension) {
		this.name = name;
		this.extension = extension;
	}

	/**
	 * Gets the user-friendly name of the DSL
	 */
	public String getName() {
		return this.name;
	}

	/**
	 * Gets the file extension of build scripts (starting with a dot)
	 */
	String getExtension() {
		return this.extension;
	}

}