text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>FingerList — Leap Motion C++ SDK v2.3 documentation</title>

    <link rel="stylesheet" href="../../cpp/_static/bootstrap-3.0.0/css/documentation-bundle.1439949735.css" type="text/css" />

    <link rel="top" title="Leap Motion C++ SDK v2.3 documentation" href="../index.html" />
    <link rel="up" title="API Reference" href="Leap_Classes.html" />
    <link rel="next" title="Frame" href="Leap.Frame.html" />
    <link rel="prev" title="Finger" href="Leap.Finger.html" />

<link rel="stylesheet" href="/assets/standalone-header.css?r9" type="text/css" />

<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1'>
<meta name="apple-mobile-web-app-capable" content="yes">

            Developer Portal

      <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">

      </button>

What's new

Getting Started

Documentation

 Examples

 Blog

 Community

      JavaScript

      Unity

      C#

      C++

      Java

      Python

      Objective-C

      Unreal

<form class="navbar-form" action="../search.html" method="get" onsubmit="storeThisPage()">

  <input type="search" results="5" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

FingerList¶

Methods:

FingerList()

append(const FingerList &other)

begin() const

count() const

end() const

extended() const

fingerType(Finger::Type type) const

frontmost() const

isEmpty() const

leftmost() const

operator[](int index) const

rightmost() const

class Leap::FingerList

The FingerList class represents a list of Finger objects.

Get a FingerList object by calling Frame::fingers().

Leap::FingerList allFingers = frame.fingers();

Since

1.0

Public Functions

FingerList  & append(const  FingerList  & other)

Appends the members of the specified FingerList to this FingerList.

Since

1.0

Parameters

<tt class="first docutils literal">other</tt> -
A FingerList object containing Finger objects to append to the end of this FingerList.

const_iterator begin()

The C++ iterator set to the beginning of this FingerList.

Leap::FingerList allTheFingers = frame.fingers();
for(Leap::FingerList::const_iterator fl = allTheFingers.begin(); fl != allTheFingers.end(); fl++)
    std::cout << "Finger ID: " << (*fl).id() << std::endl;

Since

1.0

int count()

Returns the number of fingers in this list.

for (int f = 0; f < frame.fingers().count(); f++) {
    std::cout << frame.fingers()[f] << std::endl;
}

Return

The number of fingers in this list.

Since

1.0

const_iterator end()

The C++ iterator set to the end of this FingerList.

Leap::FingerList fingersInFrame = frame.fingers();
for(Leap::FingerList::const_iterator fl = fingersInFrame.begin(); fl != fingersInFrame.end(); fl++)
    std::cout << *fl << std::endl;

Since

1.0

FingerList extended()

Returns a new list containing those fingers in the current list that are extended.

Leap::FingerList extendedFingerList = hand.fingers().extended();

Return

The list of extended fingers from the current list.

Since

2.0

 FingerList()

Constructs an empty list of fingers.

Since

1.0

FingerList fingerType(Finger::Type type)

Returns a list containing fingers from the current list of a given finger type by modifying the existing list.

Leap::FingerList indexFingerList = hand.fingers().fingerType(Leap::Finger::TYPE_INDEX);
Leap::Finger indexFinger = indexFingerList[0]; //since there is only one per hand

Return

The list of matching fingers from the current list.

Since

2.0

Finger frontmost()

The member of the list that is farthest to the front within the standard Leap Motion frame of reference (i.e has the smallest Z coordinate).

Leap::Finger mostForwardFinger = frame.fingers().frontmost();

Return

The frontmost finger, or invalid if list is empty.

Since

1.0

bool isEmpty()

Reports whether the list is empty.

if (!frame.fingers().isEmpty()) {
    //Use the fingers
}

Return

True, if the list has no members.

Since

1.0

Finger leftmost()

The member of the list that is farthest to the left within the standard Leap Motion frame of reference (i.e has the smallest X coordinate).

Leap::Finger fingerWithSmallestX = frame.fingers().leftmost();

Return

The leftmost finger, or invalid if list is empty.

Since

1.0

Finger operator[](int index)

Access a list member by its position in the list.

Leap::Finger firstFingerInList = frame.fingers()[0];

Return

The Finger object at the specified index.

Since

1.0

Parameters

<tt class="first docutils literal">index</tt> -
The zero-based list position index.

Finger rightmost()

The member of the list that is farthest to the right within the standard Leap Motion frame of reference (i.e has the largest X coordinate).

Leap::Finger fingerWithLargestX = frame.fingers().rightmost();

Return

The rightmost finger, or invalid if list is empty.

Since

1.0

C++ Docs (v2.3)

Introducing the Skeletal Tracking Model

API Overview

Guidelines

Application Development

Using the Tracking API

API Reference

Arm

Bone

CircleGesture

Config

Controller

Device

DeviceList

Finger

FingerList

Frame

Gesture

GestureList

Hand

HandList

Image

ImageList

InteractionBox

KeyTapGesture

Listener

Mask

MaskList

Matrix

Pointable

PointableList

ScreenTapGesture

SwipeGesture

Tool

ToolList

TrackedQuad

Vector

Appendices


text:
<!---
Copyright 2015 The AMP HTML Authors. All Rights Reserved.

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

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

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

# AdButler

Serves ads from [AdButler](https://www.adbutler.com/).

## Example

```html
<amp-ad
  width="300"
  height="250"
  type="adbutler"
  data-account="167283"
  data-zone="212491"
>
</amp-ad>
```

## Configuration

For details on the configuration semantics, please see [AdButler's documentation](http://www.adbutlerhelp.com/amp-configuration).

### Required parameters

-   `width`
-   `height`
-   `data-account`
-   `data-zone`

### Optional parameters

-   `data-place`
-   `data-keyword`

redpajama_set_name: RedPajamaGithub


text:
package com.kenos.kenos.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.kenos.kenos.R;

/**
 * 个人中心界面
 *
 * @author allenjuns@yahoo.com
 *
 */
public class Fragment_Profile extends Fragment {
	private Activity ctx;
	private View layout;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
							 Bundle savedInstanceState) {
		if (layout == null) {
			ctx = this.getActivity();
			layout = ctx.getLayoutInflater().inflate(R.layout.fragment_profile,
					null);
			initView();
		} else {
			ViewGroup parent = (ViewGroup) layout.getParent();
			if (parent != null) {
				parent.removeView(layout);
			}
		}
		return layout;
	}

	private void initView() {
	}
}


text: import 'core-js/fn/promise';


text:
<?php

namespace Ivory\GoogleMap\Assets;

use Ivory\GoogleMap\Exception\AssetException;

/**
 * Allow easy add of options for any class model that requires it.
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
abstract class AbstractOptionsAsset extends AbstractJavascriptVariableAsset
{
    /** @var array */
    protected $options;

    /**
     * Creates an options asset.
     *
     * @param string $javascriptVariable The javascript variable.
     * @param array  $options            The options.
     */
    public function __construct($javascriptVariable = null, array $options = array())
    {
        parent::__construct($javascriptVariable);

        $this->setOptions($options);
    }

    /**
     * Checks if there is option.
     *
     * @return boolean TRUE if there is option else FALSE.
     */
    public function hasOptions()
    {
        return !empty($this->options);
    }

    /**
     * Checks if the option exists.
     *
     * @param string $option The option.
     *
     * @throws \Ivory\GoogleMap\Exception\AssetException If the option is not valid.
     *
     * @return boolean TRUE if the option exists else FALSE.
     */
    public function hasOption($option)
    {
        if (!is_string($option)) {
            throw AssetException::invalidOption();
        }

        return isset($this->options[$option]);
    }

    /**
     * Gets the options.
     *
     * @return array The options.
     */
    public function getOptions()
    {
        return $this->options;
    }

    /**
     * Sets the options.
     *
     * @param array $options The options.
     */
    public function setOptions(array $options)
    {
        $this->options = array();

        foreach ($options as $option => $value) {
            $this->setOption($option, $value);
        }
    }

    /**
     * Gets a specific option.
     *
     * @param string $option The option.
     *
     * @throws \Ivory\GoogleMap\Exception\AssetException If the option does not exist.
     *
     * @return mixed The option value.
     */
    public function getOption($option)
    {
        if (!$this->hasOption($option)) {
            throw AssetException::optionDoesNotExist($option);
        }

        return $this->options[$option];
    }

    /**
     * Sets a specific option.
     *
     * @param string $option The option
     * @param mixed  $value  The option value.
     *
     * @throws \Ivory\GoogleMap\Exception\AssetException If the option is not valid.
     */
    public function setOption($option, $value)
    {
        if (!is_string($option)) {
            throw AssetException::invalidOption();
        }

        $this->options[$option] = $value;
    }

    /**
     * Removes an option.
     *
     * @param string $option The option.
     *
     * @throws \Ivory\GoogleMap\Exception\AssetException If the option does not exist.
     */
    public function removeOption($option)
    {
        if (!$this->hasOption($option)) {
            throw AssetException::optionDoesNotExist($option);
        }

        unset($this->options[$option]);
    }
}


text:
using System;
using System.Diagnostics;

namespace StackingEntities.Properties.Annotations
{
	[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
	[Conditional("JETBRAINS_ANNOTATIONS")]
	public class AspChildControlTypeAttribute : Attribute
	{
		public AspChildControlTypeAttribute(string tagName, Type controlType)
		{
			TagName = tagName;
			ControlType = controlType;
		}

		public string TagName { get; private set; }
		public Type ControlType { get; private set; }
	}
}


text: body{behavior:url("csshover.htc");}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Login extends CI_Controller {

	function __construct()
	{
		parent::__construct();
	}

	public function index()
	{
		$this->load->view('login');
	}

	public function enter()
	{
		$this->load->model('login_model');

		$user = strtolower(trim($_POST["txtEmail"]));
		$pass = $_POST["txtPassword"];

		$response = array();
		if($this->login_model->login($user,$pass))
		{
			$response["success"] = true;
		}
		else
		{
			$response["error"] = "Invalid credentials, email or password unknown or incorrect";
		}

		echo json_encode($response);
	}

	public function logout()
	{
		unset($_SESSION["auth"]);
		$this->load->view('login');
	}
}


text:
description: Export your Next.js app to static HTML, and run it standalone without the need of a Node.js server.
---

# Static HTML Export

  Examples

Static Export

`next export` allows you to export your Next.js application to static HTML, which can be run standalone without the need of a Node.js server. It is recommended to only use `next export` if you don't need any of the [unsupported features](#unsupported-features) requiring a server.

If you're looking to build a hybrid site where only _some_ pages are prerendered to static HTML, Next.js already does that automatically. Learn more about [Automatic Static Optimization](/docs/advanced-features/automatic-static-optimization.md) and [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md).

## `next export`

Update your build script in `package.json` to use `next export`:

```json
"scripts": {
  "build": "next build && next export"
}
```

Running `npm run build` will generate an `out` directory.

`next export` builds an HTML version of your app. During `next build`, [`getStaticProps`](/docs/basic-features/data-fetching/get-static-props.md) and [`getStaticPaths`](/docs/basic-features/data-fetching/get-static-paths.md) will generate an HTML file for each page in your `pages` directory (or more for [dynamic routes](/docs/routing/dynamic-routes.md). Then, `next export` will copy the already exported files into the correct directory. `getInitialProps` will generate the HTML files during `next export` instead of `next build`.

For more advanced scenarios, you can define a parameter called [`exportPathMap`](/docs/api-reference/next.config.js/exportPathMap.md) in your [`next.config.js`](/docs/api-reference/next.config.js/introduction.md) file to configure exactly which pages will be generated.

## Supported Features

The majority of core Next.js features needed to build a static site are supported, including:

- [Dynamic Routes when using `getStaticPaths`](/docs/routing/dynamic-routes.md)
- Prefetching with `next/link`
- Preloading JavaScript
- [Dynamic Imports](/docs/advanced-features/dynamic-import.md)
- Any styling options (e.g. CSS Modules, styled-jsx)
- [Client-side data fetching](/docs/basic-features/data-fetching/client-side.md)
- [`getStaticProps`](/docs/basic-features/data-fetching/get-static-props.md)
- [`getStaticPaths`](/docs/basic-features/data-fetching/get-static-paths.md)
- [Image Optimization](/docs/basic-features/image-optimization.md) using a [custom loader](/docs/basic-features/image-optimization.md#loader)

## Unsupported Features

Features that require a Node.js server, or dynamic logic that cannot be computed during the build process, are not supported:

- [Image Optimization](/docs/basic-features/image-optimization.md) (default loader)
- [Internationalized Routing](/docs/advanced-features/i18n-routing.md)
- [API Routes](/docs/api-routes/introduction.md)
- [Rewrites](/docs/api-reference/next.config.js/rewrites.md)
- [Redirects](/docs/api-reference/next.config.js/redirects.md)
- [Headers](/docs/api-reference/next.config.js/headers.md)
- [Middleware](/docs/middleware.md)
- [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md)
- [`fallback: true`](/docs/api-reference/data-fetching/get-static-paths.md#fallback-true)
- [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md)

### `getInitialProps`

It's possible to use the [`getInitialProps`](/docs/api-reference/data-fetching/get-initial-props.md) API instead of `getStaticProps`, but it comes with a few caveats:

- `getInitialProps` cannot be used alongside `getStaticProps` or `getStaticPaths` on any given page. If you have dynamic routes, instead of using `getStaticPaths` you'll need to configure the [`exportPathMap`](/docs/api-reference/next.config.js/exportPathMap.md) parameter in your [`next.config.js`](/docs/api-reference/next.config.js/introduction.md) file to let the exporter know which HTML files it should output.
- When `getInitialProps` is called during export, the `req` and `res` fields of its [`context`](/docs/api-reference/data-fetching/get-initial-props.md#context-object) parameter will be empty objects, since during export there is no server running.
- `getInitialProps` **will be called on every client-side navigation**, if you'd like to only fetch data at build-time, switch to `getStaticProps`.
- `getInitialProps` should fetch from an API and cannot use Node.js-specific libraries or the file system like `getStaticProps` can.

We recommend migrating towards `getStaticProps` over `getInitialProps` whenever possible.


text:
{{asset.name}}
				<archived the-style="archived-asset" deleted="asset.deleted" ></archived>

Created: {{asset.date_create | date:'EEE: yyyy-MM-dd'}}

Path: {{asset.path}}

Main product/cat: {{products.$getRecord(asset.product_category).name}} {{products.$getRecord(asset.product_category).deleted ? '- Archived' :''}}

Assoc artwork:{{artwork.name}} {{artwork.deleted ? '- Archived' :''}}

Notes:

				View
				Edit


text:
namespace mojo {

// static
bool StructTraits<sandbox::mac::mojom::SeatbeltExtensionTokenDataView,
                  sandbox::SeatbeltExtensionToken>::
    Read(sandbox::mac::mojom::SeatbeltExtensionTokenDataView data,
         sandbox::SeatbeltExtensionToken* out) {
  std::string token;
  if (!data.ReadToken(&token))
    return false;

  out->set_token(token);
  return true;
}

}  // namespace mojo


text:
<!DOCTYPE html>

  <meta charset='UTF-8'/>
  <link rel="stylesheet" href="../../dist/mapbox.css"/>
  <meta name='viewport' content='initial-scale=1.0 maximum-scale=1.0'>
  <link rel="stylesheet" href="embed.css"/>


text:
import java.util.*;

public class Solution {
  public String reverseWords(String text) {
    StringBuilder builder = new StringBuilder(text.length());
    StringBuilder wordBuilder = new StringBuilder();

    for (int i = 0; i < text.length(); i++) {
      char c = text.charAt(i);
      if (Character.isWhitespace(c)) {
        if (wordBuilder.length() > 0) {
          // We have a word
          if (builder.length() > 0) {
            // We have some other words in the buffer, insert a space
            wordBuilder.append(' ');
          }
          builder.insert(0, wordBuilder.toString());
          wordBuilder.setLength(0);
        }
      } else {
        wordBuilder.append(c);
      }
    }

    if (wordBuilder.length() > 0) {
      if (builder.length() > 0) {
        wordBuilder.append(' ');
      }
      builder.insert(0, wordBuilder.toString());
    }

    return builder.toString();
  }
}


text:
<?php if (!defined('W3TC')) die(); ?>

    <?php _e('Username:', 'w3-total-cache'); ?>

        <input id="cdn_cotendo_username" class="w3tc-ignore-change" type="text"
           <?php $this->sealing_disabled('cdn') ?> name="cdn.cotendo.username" value="<?php echo esc_attr($this->_config->get_string('cdn.cotendo.username')); ?>" size="60" />

    <?php _e('Password:', 'w3-total-cache'); ?>

        <input id="cdn_cotendo_password" class="w3tc-ignore-change"
           <?php $this->sealing_disabled('cdn') ?> type="password" name="cdn.cotendo.password" value="<?php echo esc_attr($this->_config->get_string('cdn.cotendo.password')); ?>" size="60" />

    <?php _e('Zones to purge:', 'w3-total-cache'); ?>

        <textarea id="cdn_cotendo_zones" name="cdn.cotendo.zones"
            <?php $this->sealing_disabled('cdn') ?> cols="40" rows="5"><?php echo esc_textarea(implode("\r\n", $this->_config->get_array('cdn.cotendo.zones'))); ?></textarea>

	<?php _e('<acronym title="Secure Sockets Layer">SSL</acronym> support:', 'w3-total-cache'); ?>

		<select id="cdn_cotendo_ssl" name="cdn.cotendo.ssl" <?php $this->sealing_disabled('cdn') ?>>
			<option value="auto"<?php selected($this->_config->get_string('cdn.cotendo.ssl'), 'auto'); ?>><?php _e('Auto (determine connection type automatically)', 'w3-total-cache'); ?></option>
			<option value="enabled"<?php selected($this->_config->get_string('cdn.cotendo.ssl'), 'enabled'); ?>><?php _e('Enabled (always use SSL)', 'w3-total-cache'); ?></option>
			<option value="disabled"<?php selected($this->_config->get_string('cdn.cotendo.ssl'), 'disabled'); ?>><?php _e('Disabled (always use HTTP)', 'w3-total-cache'); ?></option>
		</select>

<?php _e('Some <acronym>CDN</acronym> providers may or may not support <acronym title="Secure Sockets Layer">SSL</acronym>, contact your vendor for more information.', 'w3-total-cache'); ?>

    <?php _e('Replace site\'s hostname with:', 'w3-total-cache'); ?>

		<?php $cnames = $this->_config->get_array('cdn.cotendo.domain'); include W3TC_INC_DIR . '/options/cdn/common/cnames.php'; ?>

<?php _e('Enter the hostname provided by your <acronym>CDN</acronym> provider, this value will replace your site\'s hostname in the <acronym title="Hypertext Markup Language">HTML</acronym>.', 'w3-total-cache'); ?>

	<input id="cdn_test" class="button {type: 'cotendo', nonce: '<?php echo wp_create_nonce('w3tc'); ?>'}" type="button" value="<?php _e('Test Cotendo', 'w3-total-cache'); ?>" />


text:
#include "sam3u.h"
#include "RTL.h"
#include "debug_cm.h"
#include "target_reset.h"
#include "swd_host.h"
#include "gpio.h"
#include "target_config.h"
#include "DAP_config.h"
#include "intelhex.h"

#include "string.h"

// maybe a parameter in write but this is just for now.
extension_t file_extension;

static /*inline*/ uint32_t test_range(const uint32_t test, const uint32_t min, const uint32_t max)
{
    return ((test < min) || (test > max)) ? 0 : 1;
}

uint8_t validate_bin_nvic(uint8_t *buf)
{
    // test for known required NVIC entries
    //  0 is stack pointer (RAM address)
    //  1 is Reset vector  (FLASH address)
    uint32_t nvic_sp = 0;
    uint32_t nvic_rv = 0;
    // test the initial SP value
    memcpy(&nvic_sp, buf, sizeof(nvic_sp));

    if (0 == test_range(nvic_sp, target_device.ram_start, target_device.ram_end)) {
        return 0;
    }

    // test the initial reset vector
    memcpy(&nvic_rv, buf + 4, sizeof(nvic_rv));

    if (0 == test_range(nvic_rv, target_device.flash_start, target_device.flash_end)) {
        return 0;
    }

    return 1;
}

uint8_t validate_hexfile(uint8_t *buf)
{
    // look here for known hex records
    // add hex identifier b[0] == ':' && b[8] == {'0', '2', '3', '4', '5'}
    if (buf[0] == ':') {
        if ((buf[8] == '0') ||
                (buf[8] == '2') ||
                (buf[8] == '3') ||
                (buf[8] == '4') ||
                (buf[8] == '5')) {
            return 1;
        }
    }

    return 0;
}

target_flash_status_t target_flash_init(extension_t ext)
{
    if (!target_set_state(RESET_PROGRAM)) {
        return TARGET_FAIL_RESET;
    }

    // Download flash programming algorithm to target and initialise.
    if (!swd_write_memory(flash.algo_start, (uint8_t *)flash.image, flash.algo_size)) {
        return TARGET_FAIL_ALGO_DL;
    }

    if (!swd_flash_syscall_exec(&flash.sys_call_param, flash.init, target_device.flash_start, 0 /* clk value is not used */, 0, 0)) {
        return TARGET_FAIL_INIT;
    }

    file_extension = ext;
    return TARGET_OK;
}

target_flash_status_t target_flash_erase_sector(unsigned int addr)
{
    // Check to make sure the address is on a sector boundary
    if ((addr % target_device.sector_size) != 0) {
        return TARGET_FAIL_ERASE_SECTOR;
    }

    if (!swd_flash_syscall_exec(&flash.sys_call_param, flash.erase_sector, addr, 0, 0, 0)) {
        return TARGET_FAIL_ERASE_SECTOR;
    }

    return TARGET_OK;
}

target_flash_status_t target_flash_erase_chip(void)
{
    //
    // 1 == O.K.
    // 0 == Error
    //
    if (!swd_flash_syscall_exec(&flash.sys_call_param, flash.erase_chip, 0, 0, 0, 0)) {   // 1 == O.K., 0 == Error
        return TARGET_FAIL_ERASE_ALL;
    }

    target_set_state(RESET_PROGRAM);
    //target_flash_init();
    return TARGET_OK;
}

target_flash_status_t target_flash_program_page(uint32_t addr, uint8_t *buf, uint32_t size)
{
    uint32_t bytes_written = 0;
    target_flash_status_t status = TARGET_OK;
    addr += target_device.flash_start;

    // we need to erase a sector
    if (addr % target_device.sector_size == 0) {
        status = target_flash_erase_sector(addr);

        if (status != TARGET_OK) {
            return status;
        }
    }

    // Program a page in target RAM to be programmed.
    if (!swd_write_memory(flash.program_buffer, buf, size)) {
        return TARGET_FAIL_ALGO_DATA_SEQ;
    }

    while (bytes_written < size) {
        if (!swd_flash_syscall_exec(&flash.sys_call_param,
                                    flash.program_page,
                                    addr,
                                    flash.ram_to_flash_bytes_to_be_written,
                                    flash.program_buffer + bytes_written, 0)) {
            return TARGET_FAIL_WRITE;
        }

        bytes_written += flash.ram_to_flash_bytes_to_be_written;
        addr += flash.ram_to_flash_bytes_to_be_written;
    }

    return TARGET_OK;
}


text:
{% load i18n %}
{% if object.status_representation %}

{% endif %}

      {{ object.title }}

    {% blocktrans %}to{% endblocktrans %}
      {% if object.public_body_name %}
      {{ object.public_body_name }}
      {% elif object.public_body %}
        {{ object.public_body.name }}
        ({{ object.jurisdiction.name }})
      {% else %}
        {% blocktrans %}Not yet set{% endblocktrans %}
      {% endif %}

      {{ object.readable_status }},
      {% blocktrans with time=object.last_message|timesince %}{{ time }} ago{% endblocktrans %}{% if object.costs %},
      {{ object.costs|floatformat:2 }} {{ froide.currency }}{% endif %}
      {% if object.same_as_count %} - {% blocktrans count counter=object.same_as_count %}{{ counter }} identical request{% plural %}{{ counter }} identical requests{% endblocktrans %}{% endif %}


text:
#! /usr/bin/env node
"use strict";

/**
 *
 * Get our dependencies
 *
 */

var pkg = require("../package.json");
var program = require("commander");
var chalk = require("chalk");
var path = require("path");
var fs = require("fs-extra");
var helpers = require("./app/helpers");
var packageManager = require("./app/PackageManager");
var closet = require("./app/Closet");

/**
 *
 * Create the .closet folder and the ignore file if they don't exist
 *
 */

var thePromisedLandExists = closet.make();

/**
 *
 * Set up the CLI
 *
 */

thePromisedLandExists.then(function () {
  program.version(pkg.version).usage("<commands> [options]").option("--dry", "Do a dry-run.");

  program.command("create [name]").description("Create a new skeleton.").option("-e, --extend [skeleton]", "Base the new skeleton on an existing one.").action(packageManager.create.bind(packageManager));

  program.command("add [file] [toSkeleton]").description("Add a file to a skeleton.").action(packageManager.addFile);

  program.command("deploy [projectName] [skeleton...]").description("Deploy skeletons into the current working directory.").option("-t, --tinker [filename]", "Control freak mode. For each file, decide it's new path manually.").action(packageManager.deploy);

  program.parse(process.argv);

  /**
   *
   * Fallback to help display
   *
   */

  if (!program.args.length) {
    program.help();
  }
}).error(helpers.err);


text:
<?xml version="1.0" encoding="utf-8"?><!-- 渐变 从 1 到 0 -->
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="@android:integer/config_longAnimTime"
    android:fromAlpha="1.0"
    android:interpolator="@android:interpolator/accelerate_quad"
    android:toAlpha="0.0" />


text:
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
module Json.AlbumSpec (spec) where

import Data.Aeson (Value)
import Data.Aeson.Lens
import Data.Text (Text)
import Lastfm
import Lastfm.Album
import Test.Hspec

import SpecHelper

spec :: Spec
spec = do
  it "addTags" $
    shouldHaveJson_ . privately $
      addTags <*> artist "Pink Floyd" <*> album "The Wall" <*> tags ["70s", "awesome", "classic"]

  it "getTags-authenticated" $
    privately (getTags <*> artist "Pink Floyd" <*> album "The Wall")
   `shouldHaveJson`
    key "tags".key "tag".values.key "name"._String

  it "removeTag" $
    shouldHaveJson_ .  privately $
      removeTag <*> artist "Pink Floyd" <*> album "The Wall" <*> tag "awesome"

  it "share" $
    shouldHaveJson_ .  privately $
      share <*> album "Jerusalem" <*> artist "Sleep" <*> recipient "liblastfm" <* message "Just listen!"

  describe "getBuyLinks*" $ do
    let jsonQuery :: Fold Value Text
        jsonQuery = key "affiliations".key "physicals".key "affiliation".values.key "supplierName"._String

    it "getBuyLinks" $
      publicly (getBuyLinks <*> country "United Kingdom" <*> artist "Pink Floyd" <*> album "The Wall")
     `shouldHaveJson`
      jsonQuery

    it "getBuyLinks_mbid" $
      publicly (getBuyLinks <*> country "United Kingdom" <*> mbid "816abcd3-924a-3565-92b9-7ab750688f34")
     `shouldHaveJson`
      jsonQuery

  describe "getInfo*" $ do
    let jsonQuery :: Fold Value Text
        jsonQuery = key "album".key "toptags".key "tag".values.key "name"._String

    it "getInfo" $
      publicly (getInfo <*> artist "Pink Floyd" <*> album "The Wall")
     `shouldHaveJson`
      jsonQuery

    it "getInfo_mbid" $
      publicly (getInfo <*> mbid "816abcd3-924a-3565-92b9-7ab750688f34")
     `shouldHaveJson`
      jsonQuery

  describe "getShouts*" $ do
    let jsonQuery :: Fold Value Text
        jsonQuery = key "shouts".key "shout".values.key "body"._String

    it "getShouts" $
      publicly (getShouts <*> artist "Pink Floyd" <*> album "The Wall" <* limit 7)
     `shouldHaveJson`
      jsonQuery

    it "getShouts_mbid" $
      publicly (getShouts <*> mbid "816abcd3-924a-3565-92b9-7ab750688f34" <* limit 7)
     `shouldHaveJson`
      jsonQuery

  describe "getTags*" $ do
    let jsonQuery :: Fold Value Text
        jsonQuery = key "tags".key "tag".values.key "name"._String

    it "getTags" $
      publicly (getTags <*> artist "Pink Floyd" <*> album "The Wall" <* user "liblastfm")
     `shouldHaveJson`
      jsonQuery

    it "getTags_mbid" $
      publicly (getTags <*> mbid "816abcd3-924a-3565-92b9-7ab750688f34" <* user "liblastfm")
     `shouldHaveJson`
      jsonQuery

  describe "getTopTags*" $ do
    let jsonQuery :: Fold Value Text
        jsonQuery = key "toptags".key "tag".values.key "count"._String

    it "getTopTags" $
      publicly (getTopTags <*> artist "Pink Floyd" <*> album "The Wall")
     `shouldHaveJson`
      jsonQuery

    it "getTopTags_mbid" $
      publicly (getTopTags <*> mbid "816abcd3-924a-3565-92b9-7ab750688f34")
     `shouldHaveJson`
      jsonQuery

  it "search" $
    publicly (search <*> album "wall" <* limit 5)
   `shouldHaveJson`
    key "results".key "albummatches".key "album".values.key "name"._String


text:
/** Used for built-in method references. */
var arrayProto = Array.prototype;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeJoin = arrayProto.join;

/**
 * Converts all elements in `array` into a string separated by `separator`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Array
 * @param {Array} array The array to convert.
 * @param {string} [separator=','] The element separator.
 * @returns {string} Returns the joined string.
 * @example
 *
 * _.join(['a', 'b', 'c'], '~');
 * // => 'a~b~c'
 */
function join(array, separator) {
  return array == null ? '' : nativeJoin.call(array, separator);
}

module.exports = join;


text:
@interface PodsDummy_Pods_CarBookingTests : NSObject
@end
@implementation PodsDummy_Pods_CarBookingTests
@end


text:
This guide describes **Angular Universal**, a technology that renders Angular applications on the server.

A normal Angular application executes in the *browser*, rendering pages in the DOM in response to user actions.
Angular Universal executes on the *server*, generating *static* application pages that later get bootstrapped on the client.
This means that the application generally renders more quickly, giving users a chance to view the application layout before it becomes fully interactive.

For a more detailed look at different techniques and concepts surrounding SSR, check out this [article](https://developers.google.com/web/updates/2019/02/rendering-on-the-web).

Easily prepare an application for server-side rendering using the [Angular CLI](guide/glossary#cli).
The CLI schematic `@nguniversal/express-engine` performs the required steps, as described.

Angular Universal requires an [active LTS or maintenance LTS](https://nodejs.org/about/releases) version of Node.js.
See the `engines` property in the [package.json](https://unpkg.com/browse/@angular/platform-server/package.json) file to learn about the currently supported versions.

**NOTE**:

<live-example downloadOnly>Download the finished sample code</live-example>, which runs in a [Node.js® Express](https://expressjs.com) server.

## Universal tutorial

The [Tour of Heroes tutorial](tutorial) is the foundation for this walkthrough.

In this example, the Angular CLI compiles and bundles the Universal version of the application with the [Ahead-of-Time (AOT) compiler](guide/aot-compiler).
A Node.js Express web server compiles HTML pages with Universal based on client requests.

To create the server-side application module, `app.server.module.ts`, run the following CLI command.

ng add @nguniversal/express-engine

The command creates the following folder structure.

        src

          index.html                             // <-- app web page

          main.ts                                  // <-- bootstrapper for client app

          main.server.ts                       // <-- * bootstrapper for server app

          style.css                                // <-- styles for the app

          app/  …                                   // <-- application code

              app.server.module.ts     // <-- * server-side application module

          server.ts                                // <-- * express web server

          tsconfig.json                        // <-- TypeScript base configuration

          tsconfig.app.json                // <-- TypeScript browser application configuration

          tsconfig.server.json            // <-- TypeScript server application configuration

          tsconfig.spec.json              // <-- TypeScript tests configuration

The files marked with `*` are new and not in the original tutorial sample.

### Universal in action

To start rendering your application with Universal on your local system, use the following command.

npm run dev:ssr

Open a browser and navigate to `http://localhost:4200`.
You should see the familiar Tour of Heroes dashboard page.

Navigation using `routerLinks` works correctly because they use the built-in anchor \(`<a>`\) elements.
You can go from the Dashboard to the Heroes page and back.
Click a hero on the Dashboard page to display its Details page.

If you throttle your network speed so that the client-side scripts take longer to download \(instructions following\), you'll notice:

*   You can't add or delete a hero
*   The search box on the Dashboard page is ignored
*   The *Back* and *Save* buttons on the Details page don't work

User events other than `routerLink` clicks aren't supported.
You must wait for the full client application to bootstrap and run, or buffer the events using libraries like [preboot](https://github.com/angular/preboot), which lets you replay these events once the client-side scripts load.

The transition from the server-rendered application to the client application happens quickly on a development machine, but you should always test your applications in real-world scenarios.

You can simulate a slower network to see the transition more clearly as follows:

1.  Open the Chrome Dev Tools and go to the Network tab.
1.  Find the [Network Throttling](https://developers.google.com/web/tools/chrome-devtools/network-performance/reference#throttling) dropdown on the far right of the menu bar.
1.  Try one of the "3G" speeds.

The server-rendered application still launches quickly but the full client application might take seconds to load.

## Why use server-side rendering?

There are three main reasons to create a Universal version of your application.

*   Facilitate web crawlers through [search engine optimization (SEO)](https://static.googleusercontent.com/media/www.google.com/en//webmasters/docs/search-engine-optimization-starter-guide.pdf)
*   Improve performance on mobile and low-powered devices
*   Show the first page quickly with a [first-contentful paint (FCP)](https://developers.google.com/web/tools/lighthouse/audits/first-contentful-paint)

### Facilitate web crawlers (SEO)

Google, Bing, Facebook, Twitter, and other social media sites rely on web crawlers to index your application content and make that content searchable on the web.
These web crawlers might be unable to navigate and index your highly interactive Angular application as a human user could do.

Angular Universal can generate a static version of your application that is easily searchable, linkable, and navigable without JavaScript.
Universal also makes a site preview available because each URL returns a fully rendered page.

### Improve performance on mobile and low-powered devices

Some devices don't support JavaScript or execute JavaScript so poorly that the user experience is unacceptable.
For these cases, you might require a server-rendered, no-JavaScript version of the application.
This version, however limited, might be the only practical alternative for people who otherwise couldn't use the application at all.

### Show the first page quickly

Displaying the first page quickly can be critical for user engagement.
Pages that load faster perform better, [even with changes as small as 100ms](https://web.dev/shopping-for-speed-on-ebay).
Your application might have to launch faster to engage these users before they decide to do something else.

With Angular Universal, you can generate landing pages for the application that look like the complete application.
The pages are pure HTML, and can display even if JavaScript is disabled.
The pages don't handle browser events, but they *do* support navigation through the site using [`routerLink`](guide/router-reference#router-link).

In practice, you'll serve a static version of the landing page to hold the user's attention.
At the same time, you'll load the full Angular application behind it.
The user perceives near-instant performance from the landing page and gets the full interactive experience after the full application loads.

## Universal web servers

A Universal web server responds to application page requests with static HTML rendered by the [Universal template engine](#universal-engine).
The server receives and responds to HTTP requests from clients \(usually browsers\), and serves static assets such as scripts, CSS, and images.
It might respond to data requests, either directly or as a proxy to a separate data server.

The sample web server for this guide is based on the popular [Express](https://expressjs.com) framework.

**NOTE**:

*Any* web server technology can serve a Universal application as long as it can call Universal's `renderModule()` function.
The principles and decision points discussed here apply to any web server technology.

Universal applications use the Angular `platform-server` package \(as opposed to `platform-browser`\), which provides
server implementations of the DOM, `XMLHttpRequest`, and other low-level features that don't rely on a browser.

The server \([Node.js Express](https://expressjs.com) in this guide's example\) passes client requests for application pages to the NgUniversal `ngExpressEngine`.
Under the hood, this calls Universal's `renderModule()` function, while providing caching and other helpful utilities.

The `renderModule()` function takes as inputs a *template* HTML page \(usually `index.html`\), an Angular *module* containing components, and a *route* that determines which components to display.
The route comes from the client's request to the server.

Each request results in the appropriate view for the requested route.
The `renderModule()` function renders the view within the `<app>` tag of the template, creating a finished HTML page for the client.

Finally, the server returns the rendered page to the client.

### Working around the browser APIs

Because a Universal application doesn't execute in the browser, some of the browser APIs and capabilities might be missing on the server.

For example, server-side applications can't reference browser-only global objects such as `window`, `document`, `navigator`, or `location`.

Angular provides some injectable abstractions over these objects, such as [`Location`](api/common/Location) or [`DOCUMENT`](api/common/DOCUMENT); it might substitute adequately for these APIs.
If Angular doesn't provide it, it's possible to write new abstractions that delegate to the browser APIs while in the browser and to an alternative implementation while on the server \(also known as shimming\).

Similarly, without mouse or keyboard events, a server-side application can't rely on a user clicking a button to show a component.
The application must determine what to render based solely on the incoming client request.
This is a good argument for making the application [routable](guide/router).

### Universal template engine

The important bit in the `server.ts` file is the `ngExpressEngine()` function.

The `ngExpressEngine()` function is a wrapper around Universal's `renderModule()` function which turns a client's requests into server-rendered HTML pages.
It accepts an object with the following properties:

| Properties       | Details |
|:---              |:---     |
| `bootstrap`      | The root `NgModule` or `NgModule` factory to use for bootstrapping the application when rendering on the server. For the example application, it is `AppServerModule`. It's the bridge between the Universal server-side renderer and the Angular application. |
| `extraProviders` | This property is optional and lets you specify dependency providers that apply only when rendering the application on the server. Do this when your application needs information that can only be determined by the currently running server instance.       |

The `ngExpressEngine()` function returns a `Promise` callback that resolves to the rendered page.
It's up to the engine to decide what to do with that page.
This engine's `Promise` callback returns the rendered page to the web server, which then forwards it to the client in the HTTP response.

**NOTE**:

These wrappers help hide the complexity of the `renderModule()` function.
There are more wrappers for different backend technologies at the [Universal repository](https://github.com/angular/universal).

### Filtering request URLs

**NOTE**:

The basic behavior described below is handled automatically when using the NgUniversal Express schematic.
This is helpful when trying to understand the underlying behavior or replicate it without using the schematic.

The web server must distinguish *app page requests* from other kinds of requests.

It's not as simple as intercepting a request to the root address `/`.
The browser could ask for one of the application routes such as `/dashboard`, `/heroes`, or `/detail:12`.
In fact, if the application were only rendered by the server, *every* application link clicked would arrive at the server as a navigation URL intended for the router.

Fortunately, application routes have something in common: their URLs lack file extensions.
\(Data requests also lack extensions but they can be recognized because they always begin with `/api`.\)
All static asset requests have a file extension \(such as `main.js` or `/node_modules/zone.js/bundles/zone.umd.js`\).

Because you use routing, you can recognize the three types of requests and handle them differently.

| Routing request types | Details |
|:---                   |:---     |
| Data request          | Request URL that begins `/api`.     |
| App navigation        | Request URL with no file extension. |
| Static asset          | All other requests.                 |

A Node.js Express server is a pipeline of middleware that filters and processes requests one after the other.
You configure the Node.js Express server pipeline with calls to `server.get()` like this one for data requests.

**NOTE**:

This sample server doesn't handle data requests.

The tutorial's "in-memory web API" module, a demo and development tool, intercepts all HTTP calls and simulates the behavior of a remote data server.
In practice, you would remove that module and register your web API middleware on the server here.

The following code filters for request URLs with no extensions and treats them as navigation requests.

### Serving static files safely

A single `server.use()` treats all other URLs as requests for static assets such as JavaScript, image, and style files.

To ensure that clients can only download the files that they are permitted to see, put all client-facing asset files in the `/dist` folder and only honor requests for files from the `/dist` folder.

The following Node.js Express code routes all remaining requests to `/dist`, and returns a `404 - NOT FOUND` error if the
file isn't found.

### Using absolute URLs for HTTP (data) requests on the server

The tutorial's `HeroService` and `HeroSearchService` delegate to the Angular `HttpClient` module to fetch application data.
These services send requests to *relative* URLs such as `api/heroes`.
In a server-side rendered app, HTTP URLs must be *absolute* \(for example, `https://my-server.com/api/heroes`\).
This means that the URLs must be somehow converted to absolute when running on the server and be left relative when running in the browser.

If you are using one of the `@nguniversal/*-engine` packages \(such as `@nguniversal/express-engine`\), this is taken care for you automatically.
You don't need to do anything to make relative URLs work on the server.

If, for some reason, you are not using an `@nguniversal/*-engine` package, you might need to handle it yourself.

The recommended solution is to pass the full request URL to the `options` argument of [renderModule()](api/platform-server/renderModule) or [renderModuleFactory()](api/platform-server/renderModuleFactory) \(depending on what you use to render `AppServerModule` on the server\).
This option is the least intrusive as it does not require any changes to the application.
Here, "request URL" refers to the URL of the request as a response to which the application is being rendered on the server.
For example, if the client requested `https://my-server.com/dashboard` and you are rendering the application on the server to respond to that request, `options.url` should be set to `https://my-server.com/dashboard`.

Now, on every HTTP request made as part of rendering the application on the server, Angular can correctly resolve the request URL to an absolute URL, using the provided `options.url`.

### Useful scripts

| Scripts                                                                                | Details |
|:---                                                                                |:---     |
|  npm run dev:ssr                             | Similar to [`ng serve`](cli/serve), which offers live reload during development, but uses server-side rendering. The application runs in watch mode and refreshes the browser after every change. This command is slower than the actual `ng serve` command.                                                                                |
|  ng build && ng run app-name:server  | Builds both the server script and the application in production mode. Use this command when you want to build the project for deployment.                                                                                |
|  npm run serve:ssr                           | Starts the server script for serving the application locally with server-side rendering. It uses the build artifacts created by `ng run build:ssr`, so make sure you have run that command as well.
 **NOTE**:
 `serve:ssr` is not intended to be used to serve your application in production, but only for testing the server-side rendered application locally.
 |
|  npm run prerender                           | Used to prerender an application's pages. Read more about prerendering [here](guide/prerendering).                                                                                |

@reviewed 2022-02-28


text:
namespace anki {

/// @addtogroup util_memory
/// @{

/// Pool based allocator
///
/// This is a template that accepts memory pools with a specific interface
///
/// @tparam T The type
/// @tparam deallocationFlag If true then the allocator will try to deallocate
///                          the memory. It is extremely important to
///                          understand when it should be true. See notes
///
/// @note The deallocationFlag can brake the allocator when used with stack
///       pools and the deallocations are not in the correct order.
///
/// @note Don't ever EVER remove the double copy constructor and the double
///       operator=. The compiler will create defaults
template<typename T, typename TPool, Bool deallocationFlag = false>
class GenericPoolAllocator
{
	template<typename Y, typename TPool_, Bool deallocationFlag_>
	friend class GenericPoolAllocator;

public:
	// Typedefs
	typedef size_t size_type;
	typedef ptrdiff_t difference_type;
	typedef T* pointer;
	typedef const T* const_pointer;
	typedef T& reference;
	typedef const T& const_reference;
	typedef T value_type;

	/// Move assignments between containers will copy the allocator as well.
	/// If propagate_on_container_move_assignment is not defined then not moves
	/// are going to happen
	typedef std::true_type propagate_on_container_move_assignment;

	/// A struct to rebind the allocator to another allocator of type U
	template<typename Y>
	struct rebind
	{
		typedef GenericPoolAllocator<Y, TPool, deallocationFlag> other;
	};

	/// Default constructor
	GenericPoolAllocator() noexcept
	{}

	/// Copy constructor
	GenericPoolAllocator(const GenericPoolAllocator& b) noexcept
	{
		*this = b;
	}

	/// Copy constructor
	template<typename Y>
	GenericPoolAllocator(const GenericPoolAllocator<
		Y, TPool, deallocationFlag>& b) noexcept
	{
		*this = b;
	}

	/// Constuctor that accepts a pool
	explicit GenericPoolAllocator(const TPool& pool) noexcept
	:	m_pool(pool)
	{}

	/// Destructor
	~GenericPoolAllocator()
	{}

	/// Copy
	GenericPoolAllocator& operator=(const GenericPoolAllocator& b)
	{
		m_pool = b.m_pool;
		return *this;
	}

	/// Copy
	template<typename U>
	GenericPoolAllocator& operator=(const GenericPoolAllocator<
		U, TPool, deallocationFlag>& b)
	{
		m_pool = b.m_pool;
		return *this;
	}

	/// Get the address of a reference
	pointer address(reference x) const
	{
		return &x;
	}

	/// Get the const address of a const reference
	const_pointer address(const_reference x) const
	{
		return &x;
	}

	/// Allocate memory
	/// @param n The bytes to allocate
	/// @param hint It's been used to override the alignment. The type should
	///             be PtrSize
	pointer allocate(size_type n, const void* hint = nullptr)
	{
		(void)hint;

		size_type size = n * sizeof(value_type);

		// Operator new doesn't respect alignment (in GCC at least) so use
		// the types alignment. If hint override the alignment
		PtrSize alignment = (hint != nullptr)
			? *reinterpret_cast<const PtrSize*>(hint)
			: alignof(value_type);

		void* out = m_pool.allocate(size, alignment);

		if(out == nullptr)
		{
			throw ANKI_EXCEPTION("Allocation failed. There is not enough room");
		}

		return (pointer)out;
	}

	/// Deallocate memory
	void deallocate(void* p, size_type n)
	{
		(void)p;
		(void)n;

		if(deallocationFlag)
		{
			Bool ok = m_pool.free(p);

			if(!ok)
			{
				throw ANKI_EXCEPTION("Freeing wrong pointer. "
					"Pool's free returned false");
			}
		}
	}

	/// Call constructor
	void construct(pointer p, const T& val)
	{
		// Placement new
		new ((T*)p) T(val);
	}

	/// Call constructor with many arguments
	template<typename U, typename... Args>
	void construct(U* p, Args&&... args)
	{
		// Placement new
		::new((void *)p) U(std::forward<Args>(args)...);
	}

	/// Call destructor
	void destroy(pointer p)
	{
		p->~T();
	}

	/// Call destructor
	template<typename U>
	void destroy(U* p)
	{
		p->~U();
	}

	/// Get the max allocation size
	size_type max_size() const
	{
		return MAX_PTR_SIZE;
	}

	/// Get the memory pool
	/// @note This is AnKi specific
	const TPool& getMemoryPool() const
	{
		return m_pool;
	}

	/// Get the memory pool
	/// @note This is AnKi specific
	TPool& getMemoryPool()
	{
		return m_pool;
	}

	/// Allocate a new object and call it's constructor
	/// @note This is AnKi specific
	template<typename U, typename... Args>
	U* newInstance(Args&&... args)
	{
		typename rebind<U>::other alloc(*this);

		U* x = alloc.allocate(1);
		alloc.construct(x, std::forward<Args>(args)...);
		return x;
	}

	/// Allocate a new array of objects and call their constructor
	/// @note This is AnKi specific
	template<typename U, typename... Args>
	U* newArray(size_type n, Args&&... args)
	{
		typename rebind<U>::other alloc(*this);

		U* x = alloc.allocate(n);
		// Call the constuctors
		for(size_type i = 0; i < n; i++)
		{
			alloc.construct(&x[i], std::forward<Args>(args)...);
		}
		return x;
	}

	/// Call the destructor and deallocate an object
	/// @note This is AnKi specific
	template<typename U>
	void deleteInstance(U* x)
	{
		typename rebind<U>::other alloc(*this);

		alloc.destroy(x);
		alloc.deallocate(x, 1);
	}

	/// Call the destructor and deallocate an array of objects
	/// @note This is AnKi specific
	template<typename U>
	void deleteArray(U* x, size_type n)
	{
		typename rebind<U>::other alloc(*this);

		// Call the destructors
		for(size_type i = 0; i < n; i++)
		{
			alloc.destroy(&x[i]);
		}
		alloc.deallocate(x, n);
	}

private:
	TPool m_pool;
};

/// @name GenericPoolAllocator global functions
/// @{

/// Another allocator of the same type can deallocate from this one
template<typename T1, typename T2, typename TPool, Bool deallocationFlag>
inline bool operator==(
	const GenericPoolAllocator<T1, TPool, deallocationFlag>&,
	const GenericPoolAllocator<T2, TPool, deallocationFlag>&)
{
	return true;
}

/// Another allocator of the another type cannot deallocate from this one
template<typename T1, typename AnotherAllocator, typename TPool,
	Bool deallocationFlag>
inline bool operator==(
	const GenericPoolAllocator<T1, TPool, deallocationFlag>&,
	const AnotherAllocator&)
{
	return false;
}

/// Another allocator of the same type can deallocate from this one
template<typename T1, typename T2, typename TPool, Bool deallocationFlag>
inline bool operator!=(
	const GenericPoolAllocator<T1, TPool, deallocationFlag>&,
	const GenericPoolAllocator<T2, TPool, deallocationFlag>&)
{
	return false;
}

/// Another allocator of the another type cannot deallocate from this one
template<typename T1, typename AnotherAllocator, typename TPool,
	Bool deallocationFlag>
inline bool operator!=(
	const GenericPoolAllocator<T1, TPool, deallocationFlag>&,
	const AnotherAllocator&)
{
	return true;
}

/// @}

/// Heap based allocator. The default allocator. It uses malloc and free for
/// allocations/deallocations
template<typename T>
using HeapAllocator =
	GenericPoolAllocator<T, HeapMemoryPool, true>;

/// Allocator that uses a StackMemoryPool
template<typename T, Bool deallocationFlag = false>
using StackAllocator =
	GenericPoolAllocator<T, StackMemoryPool, deallocationFlag>;

/// Allocator that uses a ChainMemoryPool
template<typename T, Bool deallocationFlag = true>
using ChainAllocator =
	GenericPoolAllocator<T, ChainMemoryPool, deallocationFlag>;

/// @}

} // end namespace anki

#endif


text:
// Copyright 2005 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

// Author: ericv@google.com (Eric Veach)

#include "s2/s2testing.h"

#include <algorithm>
#include <cmath>
#include <cstddef>
#include <cstdlib>
#include <memory>
#include <utility>
#include <vector>

#include "absl/flags/flag.h"
#include "absl/memory/memory.h"
#include "absl/strings/str_split.h"

#include "s2/base/commandlineflags.h"
#include "s2/base/integral_types.h"
#include "s2/base/logging.h"
#include "s2/r1interval.h"
#include "s2/s1angle.h"
#include "s2/s1interval.h"
#include "s2/s2cap.h"
#include "s2/s2cell.h"
#include "s2/s2cell_union.h"
#include "s2/s2latlng.h"
#include "s2/s2latlng_rect.h"
#include "s2/s2lax_polygon_shape.h"
#include "s2/s2lax_polyline_shape.h"
#include "s2/s2loop.h"
#include "s2/s2pointutil.h"
#include "s2/s2polygon.h"
#include "s2/s2polyline.h"
#include "s2/s2region.h"
#include "s2/s2text_format.h"
#include "s2/strings/serialize.h"
#include "s2/util/math/matrix3x3.h"

using absl::make_unique;
using std::max;
using std::string;
using std::unique_ptr;
using std::vector;

S2_DEFINE_int32(s2_random_seed, 1,
             "Seed value that can be passed to S2Testing::rnd.Reset()");

const double S2Testing::kEarthRadiusKm = 6371.01;

S2Testing::Random::Random() {
  // Unfortunately we can't use FLAGS_s2_random_seed here, because the default
  // S2Testing::Random instance is initialized before command-line flags have
  // been parsed.
  srandom(1);
}

void S2Testing::Random::Reset(int seed) {
  srandom(seed);
}

// Return a 64-bit unsigned integer whose lowest "num_bits" are random, and
// whose other bits are zero.
inline uint64 GetBits(int num_bits) {
  S2_DCHECK_GE(num_bits, 0);
  S2_DCHECK_LE(num_bits, 64);

  // This code uses random(), which returns an integer in the range
  // from 0 to (2^31)-1 inclusive (i.e. all of the lower 31 bits are
  // in play, and the 32nd bit and higher are 0) regardless of whether
  // its return type (long) is larger than 32 bits.  See
  //
  // www.gnu.org/software/libc/manual/html_node/BSD-Random.html#BSD-Random
  //
  // Note that at some point the manual page in linux claimed that the range
  // is 0 to RAND_MAX as defined in stdlib.h.  RAND_MAX however is part only
  // of the ISO rand() interface.  At least as of glibc-2.21, rand() is
  // simply an alias for random().  On other systems, rand() may differ,
  // but random() should always adhere to the behavior specified in BSD.
  static const int RAND_BITS = 31;

  uint64 result = 0;
  for (int bits = 0; bits < num_bits; bits += RAND_BITS) {
    result = (result << RAND_BITS) + random();
  }
  if (num_bits < 64) {  // Not legal to shift by full bitwidth of type
    result &= ((1ULL << num_bits) - 1);
  }
  return result;
}

uint64 S2Testing::Random::Rand64() {
  return GetBits(64);
}

uint32 S2Testing::Random::Rand32() {
  return GetBits(32);
}

double S2Testing::Random::RandDouble() {
  const int NUM_BITS = 53;
  return ldexp(GetBits(NUM_BITS), -NUM_BITS);
}

int32 S2Testing::Random::Uniform(int32 n) {
  S2_DCHECK_GT(n, 0);
  return static_cast<uint32>(RandDouble() * n);
}

double S2Testing::Random::UniformDouble(double min, double limit) {
  S2_DCHECK_LT(min, limit);
  return min + RandDouble() * (limit - min);
}

bool S2Testing::Random::OneIn(int32 n) {
  return Uniform(n) == 0;
}

int32 S2Testing::Random::Skewed(int max_log) {
  S2_DCHECK_GE(max_log, 0);
  S2_DCHECK_LE(max_log, 31);
  int32 base = Uniform(max_log + 1);
  return GetBits(31) & ((1U << base) - 1);
}

S2Testing::Random S2Testing::rnd;

void S2Testing::AppendLoopVertices(const S2Loop& loop,
                                   vector<S2Point>* vertices) {
  int n = loop.num_vertices();
  const S2Point* base = &loop.vertex(0);
  S2_DCHECK_EQ(&loop.vertex(n - 1), base + n - 1);
  vertices->insert(vertices->end(), base, base + n);
}

vector<S2Point> S2Testing::MakeRegularPoints(const S2Point& center,
                                             S1Angle radius,
                                             int num_vertices) {
  unique_ptr<S2Loop> loop(
      S2Loop::MakeRegularLoop(center, radius, num_vertices));
  vector<S2Point> points;
  points.reserve(loop->num_vertices());
  for (int i = 0; i < loop->num_vertices(); i++) {
    points.push_back(loop->vertex(i));
  }
  return points;
}

S1Angle S2Testing::MetersToAngle(double meters) {
  return KmToAngle(0.001 * meters);
}

S1Angle S2Testing::KmToAngle(double km) {
  return S1Angle::Radians(km / kEarthRadiusKm);
}

double S2Testing::AreaToMeters2(double steradians) {
  return 1e6 * AreaToKm2(steradians);
}

double S2Testing::AreaToKm2(double steradians) {
  return steradians * kEarthRadiusKm * kEarthRadiusKm;
}

// The Dump*() functions are for use within a debugger.  They are similar to
// the corresponding s2textformat::ToString() functions except that they
// prefix their output with a label and they don't require default arguments
// or constructing absl::Span objects (which gdb doesn't know how to do).
void Dump(const S2Point& p) {
  std::cout << "S2Point: " << s2textformat::ToString(p) << std::endl;
}

void Dump(const vector<S2Point>& points) {
  std::cout << "S2Polygon: " << s2textformat::ToString(points) << std::endl;
}

void Dump(const S2Loop& loop) {
  std::cout << "S2Polygon: " << s2textformat::ToString(loop) << std::endl;
}

void Dump(const S2Polyline& polyline) {
  std::cout << "S2Polyline: " << s2textformat::ToString(polyline) << std::endl;
}

void Dump(const S2Polygon& polygon) {
  std::cout << "S2Polygon: " << s2textformat::ToString(polygon) << std::endl;
}

void Dump(const S2LaxPolylineShape& polyline) {
  std::cout << "S2Polyline: " << s2textformat::ToString(polyline) << std::endl;
}

void Dump(const S2LaxPolygonShape& polygon) {
  std::cout << "S2Polygon: " << s2textformat::ToString(polygon) << std::endl;
}

// Outputs the contents of an S2ShapeIndex in human-readable form.
void Dump(const S2ShapeIndex& index) {
  std::cout << "S2ShapeIndex: " << &index << std::endl;
  std::cout << "  " << s2textformat::ToString(index) << std::endl;
  for (S2ShapeIndex::Iterator it(&index, S2ShapeIndex::BEGIN);
       !it.done(); it.Next()) {
    std::cout << "  id: " << it.id().ToString() << std::endl;
    const S2ShapeIndexCell& cell = it.cell();
    for (int s = 0; s < cell.num_clipped(); ++s) {
      const S2ClippedShape& clipped = cell.clipped(s);
      std::cout << "    shape_id " << clipped.shape_id() << ": ";
      for (int e = 0; e < clipped.num_edges(); ++e) {
        if (e > 0) std::cout << ", ";
        std::cout << clipped.edge(e);
      }
      std::cout << std::endl;
    }
  }
}

S2Point S2Testing::RandomPoint() {
  // The order of evaluation of function arguments is unspecified,
  // so we may not just call S2Point with three RandDouble-based args.
  // Use temporaries to induce sequence points between calls.
  double x = rnd.UniformDouble(-1, 1);
  double y = rnd.UniformDouble(-1, 1);
  double z = rnd.UniformDouble(-1, 1);
  return S2Point(x, y, z).Normalize();
}

void S2Testing::GetRandomFrame(Vector3_d* x, Vector3_d* y, Vector3_d* z) {
  *z = RandomPoint();
  GetRandomFrameAt(*z, x, y);
}

Matrix3x3_d S2Testing::GetRandomFrame() {
  return GetRandomFrameAt(RandomPoint());
}

void S2Testing::GetRandomFrameAt(const S2Point& z, S2Point* x, S2Point *y) {
  *x = z.CrossProd(RandomPoint()).Normalize();
  *y = z.CrossProd(*x).Normalize();
}

Matrix3x3_d S2Testing::GetRandomFrameAt(const S2Point& z) {
  S2Point x, y;
  GetRandomFrameAt(z, &x, &y);
  return Matrix3x3_d::FromCols(x, y, z);
}

S2CellId S2Testing::GetRandomCellId(int level) {
  int face = rnd.Uniform(S2CellId::kNumFaces);
  uint64 pos = rnd.Rand64() & ((1ULL << S2CellId::kPosBits) - 1);
  return S2CellId::FromFacePosLevel(face, pos, level);
}

S2CellId S2Testing::GetRandomCellId() {
  return GetRandomCellId(rnd.Uniform(S2CellId::kMaxLevel + 1));
}

S2Cap S2Testing::GetRandomCap(double min_area, double max_area) {
  double cap_area = max_area * pow(min_area / max_area, rnd.RandDouble());
  S2_DCHECK_GE(cap_area, min_area);
  S2_DCHECK_LE(cap_area, max_area);

  // The surface area of a cap is 2*Pi times its height.
  return S2Cap::FromCenterArea(RandomPoint(), cap_area);
}

void S2Testing::ConcentricLoopsPolygon(const S2Point& center,
                                       int num_loops,
                                       int num_vertices_per_loop,
                                       S2Polygon* polygon) {
  Matrix3x3_d m;
  S2::GetFrame(center, &m);
  vector<unique_ptr<S2Loop>> loops;
  for (int li = 0; li < num_loops; ++li) {
    vector<S2Point> vertices;
    double radius = 0.005 * (li + 1) / num_loops;
    double radian_step = 2 * M_PI / num_vertices_per_loop;
    for (int vi = 0; vi < num_vertices_per_loop; ++vi) {
      double angle = vi * radian_step;
      S2Point p(radius * cos(angle), radius * sin(angle), 1);
      vertices.push_back(S2::FromFrame(m, p.Normalize()));
    }
    loops.push_back(make_unique<S2Loop>(vertices));
  }
  polygon->InitNested(std::move(loops));
}

S2Point S2Testing::SamplePoint(const S2Cap& cap) {
  // We consider the cap axis to be the "z" axis.  We choose two other axes to
  // complete the coordinate frame.

  Matrix3x3_d m;
  S2::GetFrame(cap.center(), &m);

  // The surface area of a spherical cap is directly proportional to its
  // height.  First we choose a random height, and then we choose a random
  // point along the circle at that height.

  double h = rnd.RandDouble() * cap.height();
  double theta = 2 * M_PI * rnd.RandDouble();
  double r = sqrt(h * (2 - h));  // Radius of circle.

  // The result should already be very close to unit-length, but we might as
  // well make it accurate as possible.
  return S2::FromFrame(m, S2Point(cos(theta) * r, sin(theta) * r, 1 - h))
         .Normalize();
}

S2Point S2Testing::SamplePoint(const S2LatLngRect& rect) {
  // First choose a latitude uniformly with respect to area on the sphere.
  double sin_lo = sin(rect.lat().lo());
  double sin_hi = sin(rect.lat().hi());
  double lat = asin(rnd.UniformDouble(sin_lo, sin_hi));

  // Now choose longitude uniformly within the given range.
  double lng = rect.lng().lo() + rnd.RandDouble() * rect.lng().GetLength();
  return S2LatLng::FromRadians(lat, lng).Normalized().ToPoint();
}

void S2Testing::CheckCovering(const S2Region& region,
                              const S2CellUnion& covering,
                              bool check_tight, S2CellId id) {
  if (!id.is_valid()) {
    for (int face = 0; face < 6; ++face) {
      CheckCovering(region, covering, check_tight, S2CellId::FromFace(face));
    }
    return;
  }

  if (!region.MayIntersect(S2Cell(id))) {
    // If region does not intersect id, then neither should the covering.
    if (check_tight) S2_CHECK(!covering.Intersects(id));

  } else if (!covering.Contains(id)) {
    // The region may intersect id, but we can't assert that the covering
    // intersects id because we may discover that the region does not actually
    // intersect upon further subdivision.  (MayIntersect is not exact.)
    S2_CHECK(!region.Contains(S2Cell(id)));
    S2_CHECK(!id.is_leaf());
    S2CellId end = id.child_end();
    S2CellId child;
    for (child = id.child_begin(); child != end; child = child.next()) {
      CheckCovering(region, covering, check_tight, child);
    }
  }
}

S2Testing::Fractal::Fractal()
    : max_level_(-1), min_level_arg_(-1), min_level_(-1),
      dimension_(log(4)/log(3)), /* standard Koch curve */
      edge_fraction_(0), offset_fraction_(0) {
  ComputeOffsets();
}

void S2Testing::Fractal::set_max_level(int max_level) {
  S2_DCHECK_GE(max_level, 0);
  max_level_ = max_level;
  ComputeMinLevel();
}

void S2Testing::Fractal::set_min_level(int min_level_arg) {
  S2_DCHECK_GE(min_level_arg, -1);
  min_level_arg_ = min_level_arg;
  ComputeMinLevel();
}

void S2Testing::Fractal::ComputeMinLevel() {
  if (min_level_arg_ >= 0 && min_level_arg_ <= max_level_) {
    min_level_ = min_level_arg_;
  } else {
    min_level_ = max_level_;
  }
}

void S2Testing::Fractal::set_fractal_dimension(double dimension) {
  S2_DCHECK_GE(dimension, 1.0);
  S2_DCHECK_LT(dimension, 2.0);
  dimension_ = dimension;
  ComputeOffsets();
}

void S2Testing::Fractal::ComputeOffsets() {
  edge_fraction_ = pow(4.0, -1.0 / dimension_);
  offset_fraction_ = sqrt(edge_fraction_ - 0.25);
}

void S2Testing::Fractal::SetLevelForApproxMinEdges(int min_edges) {
  // Map values in the range [3*(4**n)/2, 3*(4**n)*2) to level n.
  set_min_level(round(0.5 * log2(min_edges / 3)));
}

void S2Testing::Fractal::SetLevelForApproxMaxEdges(int max_edges) {
  // Map values in the range [3*(4**n)/2, 3*(4**n)*2) to level n.
  set_max_level(round(0.5 * log2(max_edges / 3)));
}

double S2Testing::Fractal::min_radius_factor() const {
  // The minimum radius is attained at one of the vertices created by the
  // first subdivision step as long as the dimension is not too small (at
  // least kMinDimensionForMinRadiusAtLevel1, see below).  Otherwise we fall
  // back on the incircle radius of the original triangle, which is always a
  // lower bound (and is attained when dimension = 1).
  //
  // The value below was obtained by letting AE be an original triangle edge,
  // letting ABCDE be the corresponding polyline after one subdivision step,
  // and then letting BC be tangent to the inscribed circle at the center of
  // the fractal O.  This gives rise to a pair of similar triangles whose edge
  // length ratios can be used to solve for the corresponding "edge fraction".
  // This method is slightly conservative because it is computed using planar
  // rather than spherical geometry.  The value below is equal to
  // -log(4)/log((2 + cbrt(2) - cbrt(4))/6).
  const double kMinDimensionForMinRadiusAtLevel1 = 1.0852230903040407;
  if (dimension_ >= kMinDimensionForMinRadiusAtLevel1) {
    return sqrt(1 + 3 * edge_fraction_ * (edge_fraction_ - 1));
  }
  return 0.5;
}

double S2Testing::Fractal::max_radius_factor() const {
  // The maximum radius is always attained at either an original triangle
  // vertex or at a middle vertex from the first subdivision step.
  return max(1.0, offset_fraction_ * sqrt(3) + 0.5);
}

void S2Testing::Fractal::GetR2Vertices(vector<R2Point>* vertices) const {
  // The Koch "snowflake" consists of three Koch curves whose initial edges
  // form an equilateral triangle.
  R2Point v0(1.0, 0.0);
  R2Point v1(-0.5, sqrt(3)/2);
  R2Point v2(-0.5, -sqrt(3)/2);
  GetR2VerticesHelper(v0, v1, 0, vertices);
  GetR2VerticesHelper(v1, v2, 0, vertices);
  GetR2VerticesHelper(v2, v0, 0, vertices);
}

// Given the two endpoints (v0,v4) of an edge, recursively subdivide the edge
// to the desired level, and insert all vertices of the resulting curve up to
// but not including the endpoint "v4".
void S2Testing::Fractal::GetR2VerticesHelper(const R2Point& v0,
                                             const R2Point& v4, int level,
                                             vector<R2Point>* vertices) const {
  if (level >= min_level_ && S2Testing::rnd.OneIn(max_level_ - level + 1)) {
    // Stop subdivision at this level.
    vertices->push_back(v0);
    return;
  }
  // Otherwise compute the intermediate vertices v1, v2, and v3.
  Vector2_d dir = v4 - v0;
  R2Point v1 = v0 + edge_fraction_ * dir;
  R2Point v2 = 0.5 * (v0 + v4) - offset_fraction_ * dir.Ortho();
  R2Point v3 = v4 - edge_fraction_ * dir;

  // And recurse on the four sub-edges.
  GetR2VerticesHelper(v0, v1, level+1, vertices);
  GetR2VerticesHelper(v1, v2, level+1, vertices);
  GetR2VerticesHelper(v2, v3, level+1, vertices);
  GetR2VerticesHelper(v3, v4, level+1, vertices);
}

std::unique_ptr<S2Loop> S2Testing::Fractal::MakeLoop(
    const Matrix3x3_d& frame,
    S1Angle nominal_radius) const {
  vector<R2Point> r2vertices;
  GetR2Vertices(&r2vertices);
  vector<S2Point> vertices;
  double r = nominal_radius.radians();
  for (const R2Point& v : r2vertices) {
    S2Point p(v[0] * r, v[1] * r, 1);
    vertices.push_back(S2::FromFrame(frame, p).Normalize());
  }
  return make_unique<S2Loop>(vertices);
}


text:
package model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * Class for database and manufacturer related tasks.
 */
public class ModelDatabase {
	/**
	 * List of models that are in the database.
	 */
	private List<Model> models;

	/**
	 * Constructs a {@code ModelDatabase} object.
	 */
	public ModelDatabase() {
		models = new LinkedList<Model>();
	}

	/**
	 * Loads those models from the database that belong to the specified
	 * manufacturer.
	 *
	 * @param con
	 *            - the database connection
	 * @param manufacturerName
	 *            - the name of the manufacturer for which models will be pullsed
	 *            from database
	 * @return the list of models, loaded from the database
	 * @throws SQLException
	 *             in case loading queries fail
	 */
	public List<Model> loadModels(Connection con, String manufacturerName)
			throws SQLException {
		models.clear();

		String loadSQL = "select model_id, manufacturer_id, model_name "
				+ "from h_b2wkl0.model "
				+ "where manufacturer_id = "
				+ "( select manufacturer_id from manufacturer where manufacturer_name = ? ) "
				+ "order by model_name";
		PreparedStatement loadStatement = con.prepareStatement(loadSQL);

		int col = 1;
		loadStatement.setString(col++, manufacturerName);

		ResultSet results = loadStatement.executeQuery();
		while (results.next()) {
			int modelId = results.getInt("model_id");
			int manId = results.getInt("manufacturer_id");
			String modelName = results.getString("model_name");

			Model model = new Model(modelId, manId, modelName);
			models.add(model);
		}

		results.close();
		loadStatement.close();

		return models;
	}

	/**
	 * Returns the list of models.
	 *
	 * @return the list of models
	 */
	public List<Model> getModels() {
		return Collections.unmodifiableList(models);
	}
}


text:
require('shelljs/global');
var args = require('minimist')(process.argv.slice(2));

// Note: The slot setting is not handled.

if (!which('azure')) {
  console.log('This script requires the Microsoft Azure Xplat-CLI.');
  exit(1);
}

if (!args.sourceApp) {
  console.log('Please provide a sourceApp parameter with the name of the Azure Web App.');
  exit(1);
}

if (!args.destApp) {
  console.log('Please provide a destApp parameter with the name of the Azure Web App.');
  exit(1);
}

// Use specified subscription, if specified.
// Otherwise, use current subscription.
var subscription = args.subscription || JSON.parse(exec(`azure account show --json`).output)[0].name;

console.log('--------------------------------------------------');
console.log('Begin copying appSettings');
console.log('--------------------------------------------------');

var appSettings = JSON.parse(exec(`azure site appsetting list "${args.sourceApp}" --subscription "${subscription}" --json`).output);

appSettings.forEach(x => {
  console.log(`Processing: "${x.name}"`);

  // Do we **need** to delete before adding?
  // Unsure if it will simply create a duplicate or replace.
  exec(`azure site appsetting delete "${x.name}" "${args.destApp}" --quiet --subscription "${subscription}"`);

  // Unsure if these nested quotes will cause a problem
  // If it does, we may need to not allow spaces in appSetting keys
  // or figure something else out.
  exec(`azure site appsetting add "${x.name}="\"${x.value}\""" "${args.destApp}" --subscription "${subscription}"`);
});

console.log('--------------------------------------------------');
console.log('Begin copying connectionStrings');
console.log('--------------------------------------------------');

var connectionStrings = JSON.parse(exec(`azure site connectionstring list "${args.sourceApp}" --subscription "${subscription}" --json`).output);

connectionStrings.forEach(x => {
  console.log(`Processing: "${x.name}"`);

  // Do we **need** to delete before adding?
  // Unsure if it will simply create a duplicate or replace.
  exec(`azure site connectionstring delete "${x.name}" "${args.destApp}" --quiet --subscription "${subscription}"`);

  // Hopefully just setting "Custom" here is OK.
  // The integers returned by `list` don't seem to match the expectations of `add`.
  exec(`azure site connectionstring add "${x.name}" "${x.connectionString}" "Custom" "${args.destApp}" --subscription "${subscription}"`);
});

console.log('--------------------------------------------------');
console.log();
console.log(`appSettings and connectionStrings have been synced from ${args.sourceApp} to ${args.destApp}.`);


text:
package com.xgr.unionpay.unionpay;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;

import com.unionpay.UPPayAssistEx;
import com.xgr.easypay.base.IPayStrategy;
import com.xgr.easypay.callback.IPayCallback;
import com.xgr.unionpay.activity.UnionPayAssistActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * 文 件 名: UnionPay
 * 创 建 人: King
 * 创建日期: 2017/2/14 18:58
 * 邮   箱: mikey1101@163.com
 * 博   客: www.smilevenus.com
 *
 * @see Des
 */
public class UnionPay implements IPayStrategy<UnionPayInfoImpli> {
    public static final String EXTRA_UNIONPAYINFO = "unionpay_info";
    public static IPayCallback sPayCallback;

    @Override
    public void pay(@NonNull Activity activity, @NonNull UnionPayInfoImpli payInfo, IPayCallback payCallback) {
        sPayCallback = payCallback;
        Intent intent = new Intent(activity, UnionPayAssistActivity.class);
        intent.putExtra(EXTRA_UNIONPAYINFO, payInfo);
        activity.startActivity(intent);
    }

    public static void pay(@NonNull Activity activity, @NonNull UnionPayInfoImpli payInfoImpli) {
        UPPayAssistEx.startPay(activity, null, null, payInfoImpli.getTn(), payInfoImpli.getMode()
                .getMode());
    }

    public static void handleResult(Activity activity, Intent data) {
        /*************************************************
         * 步骤3:处理银联手机支付控件返回的支付结果
         ************************************************/
        if (data == null) {
            activity.finish();
            return;
        }
        /*
         * 支付控件返回字符串:success、fail、cancel 分别代表支付成功,支付失败,支付取消
         */
        String str = data.getExtras().getString("pay_result");
        if (str.equalsIgnoreCase(UnionPayErrCode.RESPONSE_MESSAGE_SUCCESS)) {
            // 支付成功后,extra中如果存在result_data,取出校验
            // result_data结构见c)result_data参数说明
            if (data.hasExtra("result_data")) {
                String result = data.getExtras().getString("result_data");
                try {
                    JSONObject resultJson = new JSONObject(result);
                    String sign = resultJson.getString("sign");
                    String dataOrg = resultJson.getString("data");
                    // 验签证书同后台验签证书
                    // 此处的verify,商户需送去商户后台做验签
                    boolean ret = verify(dataOrg, sign, "mode");
                    if (ret) {
                        // 验证通过后,显示支付结果
                        if (sPayCallback != null) {
                            sPayCallback.success();
                        }
                    } else {
                        // 验证不通过后的处理
                        // 建议通过商户后台查询支付结果
                        if (sPayCallback != null) {
                            sPayCallback.failed(UnionPayErrCode.CODE_VERIFY_ERROR, UnionPayErrCode.MESSAGE_VERIFY_ERROR);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                // 未收到签名信息
                // 建议通过商户后台查询支付结果
                if (sPayCallback != null) {
                    sPayCallback.success();
                }
            }
        } else if (str.equalsIgnoreCase(UnionPayErrCode.RESPONSE_MESSAGE_FAIL)) {
            if (sPayCallback != null) {
                sPayCallback.failed(UnionPayErrCode.CODE_FAIL, UnionPayErrCode.MESSAGE_FAIL);
            }
        } else if (str.equalsIgnoreCase(UnionPayErrCode.RESPONSE_MESSAGE_CANCEL)) {
            if (sPayCallback != null) {
                sPayCallback.cancel();
            }
        }
        releaseUinonPayContext();
        activity.finish();
    }

    private static boolean verify(String msg, String sign64, String mode) {
        // 此处的verify,商户需送去商户后台做验签
        return true;
    }

    public static void releaseUinonPayContext() {

        Field[] fields = UPPayAssistEx.class.getDeclaredFields();

        for (Field field : fields) {
            if (Modifier.isStatic(field.getModifiers())) {
                if (field.getType() == Context.class) {
                    try {
                        field.setAccessible(true);
                        field.set(null, null);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }
}


text:
/**
 * Contains the code generators to create the {@link org.pepstock.charba.client.resources.AbstractInjectableResource} for all java script files that Charba is using and the java
 * script controller template.
 *
 * @author Andrea "Stock" Stocchero
 *
 */
package org.pepstock.charba.codegen;


text:
VOLUME_HOME="/var/lib/mysql"

TARGET_UID=$(stat -c "%u" /var/lib/mysql)
echo '-- Setting mysql user to use uid '$TARGET_UID
usermod -o -u $TARGET_UID mysql || true

TARGET_GID=$(stat -c "%g" /var/lib/mysql)
echo '-- Setting mysql group to use gid '$TARGET_GID
groupmod -o -g $TARGET_GID mysql || true

chown -R mysql:root /var/run/mysqld/

sed -i "s/bind-address.*/bind-address = 0.0.0.0/" /etc/mysql/my.cnf
sed -i "s/user.*/user = mysql/" /etc/mysql/my.cnf

if [[ ! -d $VOLUME_HOME/mysql ]]; then
    echo "=> An empty or uninitialized MySQL volume is detected in $VOLUME_HOME"
    echo "=> Installing MySQL ..."
    mysql_install_db > /dev/null 2>&1
    echo "=> Done!"
    /create_mysql_users.sh
else
    echo "=> Using an existing volume of MySQL"
fi

exec supervisord -n


text:
#import "JSONKit.h"

#import "iPhoneTestAppViewController.h"
#import "iPhoneTestAppAppDelegate.h"

#import "SCSoundCloudAPI+TestApp.h"

@interface iPhoneTestAppViewController(private)
-(void)commonAwake;
-(void)updateUserInfoFromData:(NSData *)data;
@end

@implementation iPhoneTestAppViewController

#pragma mark Lifecycle

- (void)awakeFromNib;
{
	scAPI = [appDelegate.soundCloudAPIMaster copyWithAPIDelegate:self];
}

- (void)dealloc;
{
	[uploadConnectionId release];
	[scAPI release];
	[super dealloc];
}

#pragma mark Accessors

@synthesize postButton, trackNameField;

#pragma mark Private

- (void)requestUserInfo;
{
	[scAPI meWithContext:@"userInfo"];
}

- (void)updateUserInfoFromData:(NSData *)data;
{
	id object = [data objectFromJSONData];

	if([object isKindOfClass:[NSDictionary class]]) {
		NSDictionary *userInfoDictionary = (NSDictionary *)object;
		[usernameLabel setText:[userInfoDictionary objectForKey:@"username"]];
		[trackNumberLabel setText:[NSString stringWithFormat:@"%d", [[userInfoDictionary objectForKey:@"private_tracks_count"] integerValue]]];
	}
}

#pragma mark Actions

-(IBAction)sendRequest:(id)sender;
{
	// sample from http://www.freesound.org/samplesViewSingle.php?id=1375
	NSString *dataPath = [[NSBundle mainBundle] pathForResource:@"1375_sleep_90_bpm_nylon2" ofType:@"wav"];
	NSURL *dataURL = [NSURL fileURLWithPath:dataPath];

	[progresBar setProgress:0];
	if (uploadConnectionId) {
		[scAPI cancelConnection:uploadConnectionId];
		[uploadConnectionId release]; uploadConnectionId = nil;
	}
	uploadConnectionId = [[scAPI postTrackWithTitle:[trackNameField text]
											fileURL:dataURL
										   isPublic:NO
											context:@"upload"] retain];
}

-(void)didReceiveMemoryWarning;
{
    [super didReceiveMemoryWarning];
    // Release anything that's not essential, such as cached data
}

#pragma mark SCSoundCloudAPIDelegate

- (void)soundCloudAPI:(SCSoundCloudAPI *)soundCloudAPI didFinishWithData:(NSData *)data context:(id)context userInfo:(id)userInfo;
{
	if([context isEqualToString:@"userInfo"]) {
		[self updateUserInfoFromData:data];
	}
	if([context isEqualToString:@"upload"]) {
		[uploadConnectionId release]; uploadConnectionId = nil;
		[self requestUserInfo];

		return; // comment this line to add the track to the field recordings group http://sandbox-soundcloud.com/groups/field-recordings

		NSDictionary *newTrack = [data objectFromJSONData];

		NSNumber *groupId = [NSNumber numberWithInt:8];	// check group id for production
		NSNumber *trackId = [newTrack objectForKey:@"id"];

		[scAPI postTrackWithId:trackId toGroupWithId:groupId context:@"addToGroup"];
	}
	if ([context isEqualToString:@"addToGroup"]) {
		NSLog(@"%@", [data objectFromJSONData]);
	}
}

- (void)soundCloudAPI:(SCSoundCloudAPI *)soundCloudAPI didFailWithError:(NSError *)error context:(id)context userInfo:(id)userInfo;
{
	if ([error.domain isEqualToString:NSURLErrorDomain]) {
		if (error.code == 401) {
			NSLog(@"401 - not authenticated");
		}
	}
	if ([context isEqualToString:@"upload"]) {
		[uploadConnectionId release]; uploadConnectionId = nil;
	}
	// check error code. if it's a http error get it from the userdict (see SCAPIErrors.h)
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
													message:[error localizedDescription]
												   delegate:nil
										  cancelButtonTitle:@"Ignore"
										  otherButtonTitles:@"Retry (dummy)", nil];
	[alert show];
	[alert release];
}

- (void)soundCloudAPI:(SCSoundCloudAPI *)soundCloudAPI didReceiveData:(NSData *)data context:(id)context userInfo:(id)userInfo;
{}

- (void)soundCloudAPI:(SCSoundCloudAPI *)soundCloudAPI didReceiveBytes:(unsigned long long)loadedBytes total:(unsigned long long)totalBytes context:(id)context userInfo:(id)userInfo;
{}

- (void)soundCloudAPI:(SCSoundCloudAPI *)soundCloudAPI didSendBytes:(unsigned long long)sendBytes total:(unsigned long long)totalBytes context:(id)context userInfo:(id)userInfo;
{
	if([context isEqual:@"upload"]) {
		[progresBar setProgress: ((float)sendBytes) / totalBytes];
	}
}

#pragma mark UITextField Delegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
	[textField resignFirstResponder];
	return NO;
}

@end


text:
#include <boost/test/auto_unit_test.hpp>
#include <thrift/transport/TSocket.h>
#include <thrift/transport/TServerSocket.h>
#include "TestPortFixture.h"
#include "TTransportCheckThrow.h"
#include <iostream>

using apache::thrift::transport::TServerSocket;
using apache::thrift::transport::TSocket;
using apache::thrift::transport::TTransport;
using apache::thrift::transport::TTransportException;

BOOST_FIXTURE_TEST_SUITE(TServerSocketTest, TestPortFixture)

BOOST_AUTO_TEST_CASE(test_bind_to_address) {
  TServerSocket sock1("localhost", m_serverPort);
  sock1.listen();
  TSocket clientSock("localhost", m_serverPort);
  clientSock.open();
  boost::shared_ptr<TTransport> accepted = sock1.accept();
  accepted->close();
  sock1.close();

  std::cout << "An error message from getaddrinfo on the console is expected:" << std::endl;
  TServerSocket sock2("257.258.259.260", m_serverPort);
  BOOST_CHECK_THROW(sock2.listen(), TTransportException);
  sock2.close();
}

BOOST_AUTO_TEST_CASE(test_listen_valid_port) {
  TServerSocket sock1(-1);
  TTRANSPORT_CHECK_THROW(sock1.listen(), TTransportException::BAD_ARGS);

  TServerSocket sock2(65536);
  TTRANSPORT_CHECK_THROW(sock2.listen(), TTransportException::BAD_ARGS);
}

BOOST_AUTO_TEST_CASE(test_close_before_listen) {
  TServerSocket sock1("localhost", m_serverPort);
  sock1.close();
}

BOOST_AUTO_TEST_CASE(test_get_port) {
  TServerSocket sock1("localHost", 888);
  BOOST_CHECK_EQUAL(888, sock1.getPort());
}

BOOST_AUTO_TEST_SUITE_END()


text:
var https = require('https');
var jsonsp = require('jsonsp');
var util = require('util');
var argv = require('optimist').argv;

// usage: node app.js -U <username> -P <password>

console.log('JSONSP: Twitter Stream Example');
console.log('  (using JSONSP + ' + jsonsp.version + ')');

// Intialize a new JSON stream parser.
//   Listen for the 'object' event, which is emitted whenever a complete JSON
//   object is parsed from the stream.  In this example, each object is a tweet
//   from the Twitter Streaming API.

var parser = new jsonsp.Parser()
parser.on('object', function(tweet) {
  if (tweet.user && tweet.text) {
    console.log('@' + tweet.user.screen_name + ': ' + tweet.text);
  }
});

// Connect and authenticate with the Twitter Streaming API.

function credentials(username, password) {
  return "Basic " + new Buffer(username + ":" + password).toString('base64');
};

var headers = {};
headers['Authorization'] = credentials(argv.U, argv.P);

var options = {
  host: 'stream.twitter.com',
  port: 443,
  path: '/1/statuses/sample.json',
  method: 'GET',
  headers: headers
};

var req = https.request(options, function(res) {
  // Feed each chunk of data incrementally to the JSON stream parser.  For each
  // complete JSON object parsed, an 'object' event will be emitted.
  res.on('data', function(chunk) {
    parser.parse(chunk.toString('utf8'));
  });
});
req.end();


text:
package org.qi4j.runtime.structure;

import org.qi4j.api.composite.ModelDescriptor;
import org.qi4j.api.object.ObjectDescriptor;
import org.qi4j.functional.Function;

/**
 * TODO
 */
public class ModelModule<T extends ModelDescriptor>
{
    public static <T extends ModelDescriptor> Function<T, ModelModule<T>> modelModuleFunction( final ModuleInstance module)
    {
        return new Function<T, ModelModule<T>>()
        {
            @Override
            public ModelModule<T> map( T model )
            {
                return new ModelModule<T>(module, model);
            }
        };
    }

    public static <T extends ModelDescriptor> Function<ModelModule<T>, T> modelFunction()
    {
        return new Function<ModelModule<T>, T>()
        {
            @Override
            public T map( ModelModule<T> modelModule )
            {
                return modelModule.model();
            }
        };
    }

    private ModuleInstance module;
    private T model;

    public ModelModule( ModuleInstance module, T model )
    {
        this.module = module;
        this.model = model;
    }

    public ModuleInstance module()
    {
        return module;
    }

    public T model()
    {
        return model;
    }

    @Override
    public boolean equals( Object o )
    {
        if( this == o ) return true;
        if( o == null || getClass() != o.getClass() ) return false;

        ModelModule that = (ModelModule) o;

        if( model != null ? !model.equals( that.model ) : that.model != null ) return false;
        if( module != null ? !module.equals( that.module ) : that.module != null ) return false;

        return true;
    }

    @Override
    public int hashCode()
    {
        int result = module != null ? module.hashCode() : 0;
        result = 31 * result + (model != null ? model.hashCode() : 0);
        return result;
    }

    @Override
    public String toString()
    {
        return module.name()+":"+model.type().getName();
    }
}


text:
package org.apache.ignite.spi.loadbalancing.weightedrandom;

import org.apache.ignite.testframework.junits.spi.GridSpiAbstractConfigTest;
import org.apache.ignite.testframework.junits.spi.GridSpiTest;

/**
 *
 */
@GridSpiTest(spi = WeightedRandomLoadBalancingSpi.class, group = "Load Balancing SPI")
public class GridWeightedRandomLoadBalancingSpiConfigSelfTest extends
    GridSpiAbstractConfigTest<WeightedRandomLoadBalancingSpi> {
    /**
     * @throws Exception If failed.
     */
    public void testNegativeConfig() throws Exception {
        checkNegativeSpiProperty(new WeightedRandomLoadBalancingSpi(), "nodeWeight", 0);
    }
}


text:
<!doctype html>

		<meta charset="utf-8">

		<title>函数作为对象 Functions as Objects</title>

		<meta name="description" content="Functions as Objects(函数作为对象) in Functional Programming Principles in Scala(Scala函数式编程原理)">
		<meta name="author" content="Martin Odersky">
		<meta name="translator" content="jasonqu">

		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

		<link rel="stylesheet" href="../../css/reveal.min.css">
		<link rel="stylesheet" href="../../css/theme/default.css" id="theme">

		<link rel="stylesheet" href="lib/css/zenburn.css">

Functions as Objects

scala中,函数也是被当做对象处理的

函数类型 A => B 是类scala.Function1[A, B]的简写:

package scala
trait Function1[A, B] {
  def apply(x: A): B
}

所以函数不过是拥有apply方法的对象

还有更多参数的类:Function2、Function3...直到22

Expansion of Function Values

匿名函数 (x: Int) => x * x 将被编译器扩展为:

{ class AnonFun extends Function1[Int, Int] {
    def apply(x: Int) = x * x
  }
  new AnonFun
}

等价于:

new Function1[Int, Int] {
  def apply(x: Int) = x * x
}

Expansion of Function Calls

f(a, b)这样的函数调用会被扩展成:f.apply(a, b)

所以下面的代码:

val f = (x: Int) => x * x
f(7)

会被扩展为:

val f = new Function1[Int, Int] {
  def apply(x: Int) = x * x
}
f.apply(7)

Functions and Methods

在类中定义的方法本身不是函数对象

def f(x: Int): Boolean = ...

但是当f被作为参数传给需要函数类型的地方时,就会被自动转化为函数类型的对象

(x: Int) => f(x)
// or, expanded:
new Function1[Int, Boolean] {
  def apply(x: Int) = f(x)
}

Exercise

定义并实现以下方法

object List {
...
}
// with 3 functions in it so that users can create lists of lengths 0-2 using syntax
List() // the empty list
List(1) // the list with single element 1
List(2, 3) // the list with elements 2 and 3.


text:
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'
import chai from 'chai'
import chailint from 'chai-lint'
import gtiff2json from '../index.js'

const __dirname = path.dirname(fileURLToPath(import.meta.url))

describe('weacast-gtiff2json', () => {
  before(() => {
    chailint(chai, chai.util)
  })

  it('is ES module compatible', () => {
    chai.expect(typeof gtiff2json).to.equal('function')
  })

  it('generates valid RLE json', () => {
    const jsonArray = JSON.parse(fs.readFileSync(path.join(__dirname, 'data', 'rle.json')))
    return gtiff2json(path.join(__dirname, 'data', 'rle.tif'), true, true).then(function (points) {
      chai.expect(points.length).to.equal(jsonArray.length)
      chai.expect(points).to.deep.equal(jsonArray)
    })
  })
  // Let enough time to process
    .timeout(10000)
})


text:
#ifndef _PARSER_H
#define _PARSER_H

#include <stdio.h>

#undef CLASS_IMPORT_EXPORT
#ifdef HHCTRL
#define CLASS_IMPORT_EXPORT
#else
#define CLASS_IMPORT_EXPORT __declspec(dllimport)
#endif

#define PARSER_API_INLINE
#define MAX_LINE_LEN 1024

#define F_OK 0
#define F_NOFILE 1
#define F_READ 2
#define F_WRITE 3
#define F_MEMORY 4
#define F_EOF 5
#define F_END 6
#define F_TAGMISSMATCH 7
#define F_MISSINGENDTAG 8
#define F_NOTFOUND 9
#define F_NOPARENT 10
#define F_NULL 11
#define F_NOTITLE 12
#define F_LOCATION 13
#define F_REFERENCED 14
#define F_DUPLICATE 15
#define F_DELETE 16
#define F_CLOSE 17
#define F_EXISTCHECK 19

class CParseXML {
private:
  CHAR m_cCurToken[MAX_LINE_LEN];
  CHAR m_cCurWord[MAX_LINE_LEN];
  CHAR m_cCurBuffer[MAX_LINE_LEN];
  FILE *m_fh;
  CHAR *m_pCurrentIndex;
  DWORD m_dwError;
private:
  DWORD Read();
  DWORD SetError(DWORD dw) { m_dwError = dw; return m_dwError; }
public:
  CParseXML() {
    m_fh = NULL;
    m_cCurBuffer[0] = '\0';
    m_pCurrentIndex = NULL;
    m_dwError = F_OK;
  }
  ~CParseXML() {
    End();
  }
  CHAR *GetFirstWord(CHAR *);
  CHAR *GetValue(CHAR *);
  DWORD Start(const CHAR *szFile);
  void End();
  CHAR *GetToken();
  DWORD GetError() { return m_dwError; }
};

typedef struct fifo {
  CHAR *string;
  fifo *prev;
} FIFO;

class CLASS_IMPORT_EXPORT CFIFOString {
private:
  FIFO *m_fifoTail;
public:
  CFIFOString() { m_fifoTail = NULL; }
  ~CFIFOString();
  void RemoveAll();
  DWORD AddTail(CHAR *sz);
  DWORD GetTail(CHAR **sz);
};
#endif


text:
<!DOCTYPE HTML>

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

    <link href="../cornerstone.min.css" rel="stylesheet">

Example of displaying a DICOM P10 multiframe images using Cornerstone

            Enter a URL for a DICOM P10 multiframe sop instance to view it using cornerstone.
            <button id="toggleCollapseInfo" class="btn btn-primary" type="button">
                Click for more info
            </button>

            This example illustrates how to use the cornerstoneWADOImageLoader to get a DICOM P10
            SOP instance using HTTP and display it in your web browser using cornerstone.
            Not all transfer syntaxes are currently supported,

                click here for the full list.

            For WADO-URI requests,
            you can request that the server return the SOP Instance in explicit little endian by
            appending the following query string to your URL:
            &transferSyntax=1.2.840.10008.1.2.1

        If you get an HTTP error and your URL is correct, it is probably because the server is not configured to
            allow Cross Origin Requests.
            Most browsers will allow you to enable cross domain requests via settings or command line switches,
            you can start chrome with the command line switch --disable-web-security to allow cross origin requests.
            See the  Enable CORS site for information about CORS.

            Looking for a CORS proxy?  Try CORSProxy

        Use of this example require IE10+ or any other modern browser.

Image Load Progress:

        <form id="form" class="form-horizontal">

                URL

                    <input class="form-control" type="text" id="wadoURL" placeholder="Enter WADO URL" value="https://raw.githubusercontent.com/cornerstonejs/cornerstoneWADOImageLoader/master/testImages/CT0012.fragmented_no_bot_jpeg_baseline.51.dcm">

                    <button class="form-control" type="button" id="downloadAndView" class="btn btn-primary">Download and View</button>

        </form>