text:
package activity;

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

import util.HttpCallbackListener;
import util.HttpUtil;
import util.Utility;

import model.City;
import model.County;
import model.Province;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.coolweather.app.R;

import db.CoolWeatherDB;

public class ChooseAreaActivity extends Activity {
	public static final int LEVEL_PROVINCE = 0;
	public static final int LEVEL_CITY = 1;
	public static final int LEVEL_COUNTY = 2;

	private ProgressDialog progressDialog;
	private TextView titleText;
	private ListView listView;
	private ArrayAdapter<String>adapter;
	private CoolWeatherDB coolWeatherDB;
	private List<String>dataList = new ArrayList<String>();

	private List<Province> provinceList;
	private List<City> cityList;
	private List<County> countyList;

	private Province selectedProvince;
	private City selectedCity;
	private int currentLevel;

	private boolean isFromWeatherActivity;

	protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);

		isFromWeatherActivity = getIntent().getBooleanExtra("from_weather_activity", false);

		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		//ÒѾÑ¡Ôñ³ÇÊв¢ÇÒ²»ÊÇ´ÓWeatherActivityÌøת¹ýÀ´µÄ£¬²Å»áÖ±½ÓÌøתµ½WeatherActivity
		if(prefs.getBoolean("city_selected", false) && !isFromWeatherActivity){
			Intent intent = new Intent(this, WeatherActivity.class);
			startActivity(intent);
			finish();
			return;
		}

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.choose_area);
		listView = (ListView)findViewById(R.id.list_view);
		titleText = (TextView)findViewById(R.id.title_text);
		adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dataList);
		listView.setAdapter(adapter);
		coolWeatherDB = CoolWeatherDB.getInstance(this);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int index,
					long arg3) {
				if(currentLevel==LEVEL_PROVINCE){
					selectedProvince = provinceList.get(index);
					queryCities();
				}else if(currentLevel==LEVEL_CITY){
					selectedCity = cityList.get(index);
					queryCounties();
				}else if(currentLevel==LEVEL_COUNTY){
					String countyCode = countyList.get(index).getCountyCode();
					Intent intent = new Intent(ChooseAreaActivity.this, WeatherActivity.class);
					intent.putExtra("county_code", countyCode);
					startActivity(intent);
					finish();
				}
			}
		});
		queryProvinces();//¼ÓÔØÊ¡¼¶Êý¾Ý
	}

	//²éѯËùÓÐÊ¡·Ý  ÓÅÏÈ´ÓÊý¾Ý¿â²é  ûÓÐÔòÈ¥·þÎñÆ÷²é
	private void queryProvinces() {
		provinceList = coolWeatherDB.loadProvinces();
		if(provinceList.size()>0){
			dataList.clear();
			for(Province province:provinceList){
				dataList.add(province.getProvinceName());
			}
			adapter.notifyDataSetChanged();
			listView.setSelection(0);
			titleText.setText("Öйú");
			currentLevel = LEVEL_PROVINCE;
		}else{
			queryFromSever(null, "province");
		}
	}

	//²éѯËùÓÐÊÐ  ÓÅÏÈ´ÓÊý¾Ý¿â²é  ûÓÐÔòÈ¥·þÎñÆ÷²é
	protected void queryCities() {
		cityList = coolWeatherDB.loadCities(selectedProvince.getId());
		if(cityList.size()>0){
			dataList.clear();
			for(City city:cityList){
				dataList.add(city.getCityName());
			}
			adapter.notifyDataSetChanged();
			listView.setSelection(0);
			titleText.setText(selectedProvince.getProvinceName());
			currentLevel = LEVEL_CITY;
		}else{
			queryFromSever(selectedProvince.getProvinceCode(), "city");
		}
	}

	//²éѯËùÓÐÏØ  ÓÅÏÈ´ÓÊý¾Ý¿â²é  ûÓÐÔòÈ¥·þÎñÆ÷²é
		protected void queryCounties() {
			countyList = coolWeatherDB.loadCounties(selectedCity.getId());
			if(countyList.size()>0){
				dataList.clear();
				for(County county:countyList){
					dataList.add(county.getCountyName());
				}
				adapter.notifyDataSetChanged();
				listView.setSelection(0);
				titleText.setText(selectedCity.getCityName());
				currentLevel = LEVEL_COUNTY;
			}else{
				queryFromSever(selectedCity.getCityCode(), "county");
			}
		}
	//¸ù¾Ý´úºÅºÍÀàÐÍ´Ó·þÎñÆ÷Éϲéѯ
	private void queryFromSever(final String code, final String type) {
		String address;
		if(!TextUtils.isEmpty(code)){
			address = "http://www.weather.com.cn/data/list3/city"+code+".xml";
		}else{
			address = "http://www.weather.com.cn/data/list3/city.xml";
		}
		showProgressDialog();
		HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {

			@Override
			public void onFinish(String response) {
				boolean result = false;
				if("province".equals(type)){
					result = Utility.handleProvincesResponse(coolWeatherDB, response);
				}else if("city".equals(type)){
					result = Utility.handleCitiesResponse(coolWeatherDB,
							response, selectedProvince.getId());
				}else if("county".equals(type)){
					result = Utility.handleCountiesResponse(coolWeatherDB,
							response, selectedCity.getId());
				}
				if(result){
					//ͨ¹ýrunOnUiThread·½·¨»Øµ½Ö÷Ï̴߳¦ÀíÂß¼
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							closeProgressDialog();
							if("province".equals(type)){
								queryProvinces();
							}else if("city".equals(type)){
								queryCities();
							}else if("county".equals(type)){
								queryCounties();
							}
						}
					});
				}
			}

			@Override
			public void onError(Exception e) {
				//ͨ¹ýrunOnUiThread·½·¨»Øµ½Ö÷Ï̴߳¦ÀíÂß¼
				runOnUiThread(new Runnable() {
					public void run() {
						closeProgressDialog();
						Toast.makeText(ChooseAreaActivity.this,
								"¼ÓÔØʧ°Ü", Toast.LENGTH_SHORT).show();
					}
				});
			}
		});
	}

	private void showProgressDialog() {
		if(progressDialog==null){
			progressDialog=new ProgressDialog(this);
			progressDialog.setMessage("ÕýÔÚ¼ÓÔØ¡¡");
			progressDialog.setCanceledOnTouchOutside(false);
		}
		progressDialog.show();
	}
	private void closeProgressDialog() {
		if(progressDialog != null){
			progressDialog.dismiss();
		}
	}

	public void onBackPressed(){
		if(currentLevel==LEVEL_COUNTY){
			queryCities();
		}else if(currentLevel==LEVEL_CITY){
			queryProvinces();
		}else{
			if(isFromWeatherActivity){
				Intent intent = new Intent (this, WeatherActivity.class);
				startActivity(intent);
			}
			finish();
		}
	}
}


text:
drop table hrana_backup;
create table hrana_backup
(	datum datetime
,	id int
,	code varchar(40)
,	name varchar(400)

,	amount int
,	currency varchar(10)
,	formatted_price varchar(10)

,	description text
,	product_path varchar(200)
,	image_path varchar(200)
,	thumbnail_image_path varchar(200)
,	product_details_path varchar(200)

,	manufacturer varchar(400)
,	sales_unit_of_measure varchar(20)
,	quantity_step double
,	min_order_quantity double
,	netto_weight_factor double
,	sliceable bool
,	catch_weight int
,	has_image bool
,	requires_deposit_packaging bool
,	image_s varchar(200)
,	image_m varchar(200)
,	image_l varchar(200)

,	netto_weight int
,	contact_person varchar(100)
,	contact_person_address varchar(100)
,	allergens_statement text
,	storage_instruction text
,	health_claim text
,	additives_statement text
,	drained_weight varchar(20)

,	active bool
,	price_unit_of_measure varchar(20)
,	statistical_price varchar(20)

,	favorite bool

,	ingredients_statement text
,	manufacturer_address varchar(400)
,	nutritional_claim text
,	origin_statement text
,	preparation_instruction text
,	serving_suggestion text
,	storage_instructions text
,	variant_description text );

redpajama_set_name: RedPajamaGithub


text:
'use strict'

var STORE

function OpenRecordCachePlugin(store) {
  this.store = store
  STORE = store
}

class OpenRecordCacheInfusionDependency {
  constructor(range, value, store) {
    if(!Array.isArray(range)) throw new Error('range must be valid')
    this.range = range
    this.value = value
    this.store = store
  }

  // methods needed by webpack
  updateHash() {}

  getWarnings() {
    return null
  }

  getErrors() {
    return null
  }

  getResourceIdentifier(){
    return null;
  }

  getReference() {
		return null
	}

  disconnect(){}
}

OpenRecordCacheInfusionDependency.Template = class OpenRecordCacheInfusionDependencyTemplate {
  apply(dep, source) {
    const before = [dep.range[0], dep.range[1] - 1] // => `require` call
    const after = [dep.range[1] - 1 + dep.value.length + 5, dep.range[1] - 1 + dep.value.length + 5] // => the position after `require('openrecord....')``

    // create a new constructor, add the cache to the config and call the original constructor
    const beforeCode = [
      'function CacheInfusedStore(config){',
      'config = config || {}',
      'config.cache = ' + JSON.stringify(dep.store.cache) + ';',
      'return new '
    ].join('\n')
    const afterCode = ['(config)', '}'].join('\n')
    /*
    BECOMES:
    function CacheInfusedStore(config){
      config = config || {}
      config.cache = {...}
      return new __webpack_require(1)(config)
    }
    */
    source.replace(before[0], before[1], beforeCode)
    source.replace(after[0], after[1], afterCode)
  }
}

OpenRecordCachePlugin.prototype.apply = function(compiler) {
  var store = STORE

  function compilation(compilation, params) {
    compilation.dependencyFactories.set(OpenRecordCacheInfusionDependency, params.normalModuleFactory)
    compilation.dependencyTemplates.set(OpenRecordCacheInfusionDependency, new OpenRecordCacheInfusionDependency.Template())

    function parser(parser){
      function callRequire(node){
        // and check if 'openrecord' or 'openrecord/store/...' was required
        if(node.arguments[0] && node.arguments[0].value && node.arguments[0].value.match(/^openrecord($|\/store\/)/)){
          // now we do the fancy webpack dance
          const dep = new OpenRecordCacheInfusionDependency(node.callee.range, node.arguments[0].value, store)
          dep.loc = node.loc
          dep.request = node.arguments[0].value // actually I don't know where request comes, but it's the file name/relative path of the required file in webpack code
          parser.state.current.addDependency(dep)
        }
      }

      // currently we search only for require calls
      if(parser.hooks){
        parser.hooks.call.for('require').tap('require', callRequire)
      }else{
        parser.plugin('call require', callRequire)
      }
    }

    if(params.normalModuleFactory.hooks){
      // from https://github.com/webpack/webpack/blob/master/lib/DefinePlugin.js
      params.normalModuleFactory.hooks.parser.for("javascript/auto").tap('parser', parser)
      params.normalModuleFactory.hooks.parser.for("javascript/dynamic").tap('parser', parser)
      params.normalModuleFactory.hooks.parser.for("javascript/esm").tap('parser', parser)
    }else{
      params.normalModuleFactory.plugin('parser', parser)
    }
  }

  function run(compiler, callback) {
    store.ready().then(function(){
      if(typeof callback === 'function') callback()
    })
  }

  function done(stats, callback){
    if(store.close) store.close()
    if(typeof callback === 'function') callback()
  }

  if(compiler.hooks){
    compiler.hooks.compilation.tap('openrecord', compilation)
    compiler.hooks.run.tapAsync('openrecord', run)
    // compiler.hooks.emit.tapAsync('openrecord', emit)
    compiler.hooks.done.tapAsync('openrecord', done)
  }else{
    compiler.plugin('compilation', compilation)
    compiler.plugin('run', run)
    // compiler.plugin('emit', emit)
    compiler.plugin('done', done)
  }
}

module.exports = OpenRecordCachePlugin


text:
Project archived.

VMware dvSwitch ML2 Mechanism driver for ML2 plugin at OpenStack Neutron
========================================================================

Source: https://github.com/cybercom-finland/neutron_vmware_dvswitch

This mechanism driver implements Neutron ML2 Driver API and it is used
to manage the VMware vSphere infrastructure with a distributed virtual
switch (VMware dvSwitch).

Prerequisites
-------------

You will need the **pyVmomi** library for Python in order to be able
to communicate with vSphere servers.

* Please refer to:

https://github.com/vmware/pyvmomi

The pyVmomi SDK is a nice and clean Python API implementation
for **VMware vSphere API** - highly recommended.

VMware vCenter vSphere Permissions
VIRTUAL MACHINE
        CONFIGURATION
                MODIFY DEVICE SETTINGS
                SETTINGS
HOST
        CONFIGURATION
                SYSTEM MANAGEMENT

Deployment
----------

You need to add a `[ml2_dvs]` section to your `ml2_conf.ini`,
usually found at the directory `/etc/neutron/plugins/ml2/`.

The driver should reside in the directory
`/usr/lib/python2.6/site-packages/neutron/plugins/ml2/drivers/dvs/`
or similar, whatever is correct for your Neutron installation.

Most importantly, you have to enable the driver in your WSGI
Python environment by editing a file like

`/usr/lib/python2.6/site-packages/neutron-2013.2.3-py2.6.egg-info/entry_points.txt`

or similar, whatever is correct for your Python version and Neutron.

In the python egg metadata, you will find something like this:

	[neutron.ml2.type_drivers]
	flat = neutron.plugins.ml2.drivers.type_flat:FlatTypeDriver
	vlan = neutron.plugins.ml2.drivers.type_vlan:VlanTypeDriver
	local = neutron.plugins.ml2.drivers.type_local:LocalTypeDriver
	gre = neutron.plugins.ml2.drivers.type_gre:GreTypeDriver
	vxlan = neutron.plugins.ml2.drivers.type_vxlan:VxlanTypeDriver

	[neutron.ml2.mechanism_drivers]
	hyperv = neutron.plugins.ml2.drivers.mech_hyperv:HypervMechanismDriver
	l2population = neutron.plugins.ml2.drivers.l2pop.mech_driver:L2populationMechanismDriver
	ncs = neutron.plugins.ml2.drivers.mechanism_ncs:NCSMechanismDriver
	cisco_nexus = neutron.plugins.ml2.drivers.cisco.mech_cisco_nexus:CiscoNexusMechanismDriver
	openvswitch = neutron.plugins.ml2.drivers.mech_openvswitch:OpenvswitchMechanismDriver
	linuxbridge = neutron.plugins.ml2.drivers.mech_linuxbridge:LinuxbridgeMechanismDriver
	arista = neutron.plugins.ml2.drivers.mech_arista.mechanism_arista:AristaDriver
	test = neutron.tests.unit.ml2.drivers.mechanism_test:TestMechanismDriver
	logger = neutron.tests.unit.ml2.drivers.mechanism_logger:LoggerMechanismDriver
	dvs = neutron.plugins.ml2.drivers.dvs.mechanism_dvs:VmwareDvswitchMechanismDriver

As you can see, the last line about **dvs** is important for us.
You probably need to add it manually, if you are installing
the dvSwitch driver separately, after installing Neutron from a package.

Configuration
-------------

First you have to enable the dvswitch mechanism driver from the ml2 config:

	[ml2]
	type_drivers = local,flat,vlan
	tenant_network_types = local,flat,vlan
	mechanism_drivers = openvswitch,dvs
	...

Then configure the dvs mech driver, use something like:

	[ml2_dvs]
	vsphere_server = my.vsphere.server.local
	vsphere_user = vsphereuser
	vsphere_pass = mypassword
	dvs_name = my-dvSwitch-name

A more complete example config with comments is included in the repo.
The default values for various tuning knobs should be reasonable,
so you should usually only need to specify vsphere server, user, password
and of course, the relevant dvSwitch name in your environment.

Please refer to `ml2_conf_dvs.ini` example config.

Random details about the implementation
---------------------------------------

In VMware, to connect a Virtual Machine (VM) to a certain
network/subnet/vlan/portgroup, you don't really configure
the dvswitch at all. The connection is made by *reconfiguring
the virtual network card* of the VM. In VMware terms, you make
a new *backing* for the virtual device and then issue a *VM Reconfigure
Request* for the given VM via the vSphere API.

Of course, the reconfiguration can only be done *after the VM is created*.
OpenStack and Neutron will call this driver well before
the relevant VM does even exist. All this means that the
driver must keep a **TODO List** of all VM Reconfiguration requests
to be done.

The TODO request is handled by a *separate worker thread* in some 10 seconds
after the driver's `create_port_postcommit()` call. The exact timing
values are configurable, with reasonable defaults.
The worker TODO List resides in memory only.

The VM reconfiguration attempts might be repeated until the driver
detects that the VM exists and the network connection of the VM
is what it should be, i.e. the *port backing* of the virtual ethernet
is correct.

This periodic checking with adjustable polling interval is done
in order to rule out any sporadic errors in vSphere.
If the reconfiguration really does not *ever* succeed,
the failing TODO task will finally expire.

The default TODO request expiration time is 5 minutes and adjustable.
The driver is trying hard to be as robust as possible without being
too spammy for the vSphere server.

The vSphere connection and login session is first requested at the
driver initialization phase. The vSphere session handle is stored
in the driver's in-memory state, and checked for validity immediately
before each real vSphere API call. The checking is done by asking
the current time from the vSphere server. If this fails, a new login
is attempted right away, just before the actual vSphere API call.
This behaviour is in accordance with the vSphere API Best Practices.
Usually there is a session idle timeout of 30 minutes
in the vSphere server side.

At the driver initialization, the relevant dvSwitch is searched for
by its name and the driver will read the *port group information*
from the dvSwitch. This port group data will be stored to the driver's
in-memory state. The information will be automatically refreshed
from vSphere in every 10 minutes (adjustable).

The OpenStack/Neutron network names are matched with the VMware dvSwitch
portgroup names. The driver does care about the VLAN ID.

Restrictions, shortcomings, bugs, warnings, TODO
------------------------------------------------

* **Only VLAN network type is relevant and supported.**

* There is not yet support for portgroup i.e. OpenStack network
  creation. **All networks must have pre-existing portgroups in the dvSwitch.**

* **Only VMs with a single nic are supported.**
  Or at least, the driver only supports connecting the first nic.

* There is no permanent state e.g. in form of SQL tables for this driver.
  The TODO queue is volatile, because it resides only in the driver's
  in-memory state. It will be lost on Neutron server restart.
  **Care should be taken to not restart the Neutron server while there are
  any VM creation in progress.**

* Edit: There is now a watchdog thread capable of restarting the worker.

* So far the driver has only been tested with vSphere version 5.1.
  There should really be no reason why it would not run with any
  newer version as well. **Please give us feedback.**

* The driver works only if Neutron server process is single threaded.

Contact
-------

Issues/Questions/Bugs: GitHub


text:
// Copyright (c) Costin Morariu. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Windows.UI.Xaml.Controls;

namespace Wontstop.Climb.Ui.Uwp.Views
{
    public sealed partial class WallSectionItemView : UserControl
    {
        public WallSectionItemView()
        {
            InitializeComponent();
        }
    }
}


text:
import expect from 'expect'
import { constants, actions, reducer } from '../app/gameStore'

describe('gameStore', () => {
  describe('.constants', () => {
    it('should have a constant named `START_GAME`', () => {
      expect(constants.START_GAME).toEqual('START_GAME')
    })
    it('should have a constant named `ADD_PIECE`', () => {
      expect(constants.ADD_PIECE).toEqual('ADD_PIECE')
    })
    it('should have a constant named `CHECK_ANSWER`', () => {
      expect(constants.CHECK_ANSWER).toEqual('CHECK_ANSWER')
    })
    it('should have a constant named `WIN_GAME`', () => {
      expect(constants.WIN_GAME).toEqual('WIN_GAME')
    })
    it('should have a constant named `DRAW_GAME`', () => {
      expect(constants.DRAW_GAME).toEqual('DRAW_GAME')
    })
    it('should have a constant named `EXIT_GAME`', () => {
      expect(constants.EXIT_GAME).toEqual('EXIT_GAME')
    })
    it('should have a constant named `HOVER_PIECE`', () => {
      expect(constants.HOVER_PIECE).toEqual('HOVER_PIECE')
    })
    it('should have a constant named `BLUR_PIECE`', () => {
      expect(constants.BLUR_PIECE).toEqual('BLUR_PIECE')
    })
    it('should have a constant named `PIECE_EMPTY`', () => {
      expect(constants.PIECE_EMPTY).toEqual(0)
    })
    it('should have a constant named `PIECE_PLAYER_1`', () => {
      expect(constants.PIECE_PLAYER_1).toEqual(1)
    })
    it('should have a constant named `PIECE_PLAYER_2`', () => {
      expect(constants.PIECE_PLAYER_2).toEqual(2)
    })
  })

  describe('.actions', () => {
    it('should create an action to start a game', () => {
      const cols = 7
      const rows = 6
      const expectedAction = {
        type: constants.START_GAME,
        payload: {
          cols,
          rows
        }
      }
      expect(actions.startGame(cols, rows)).toEqual(expectedAction)
    })

    it('should create an action to add a new piece', () => {
      const player = 1
      const columnIndex = 1
      const pieceIndex = 4
      const expectedAction = {
        type: constants.ADD_PIECE,
        payload: {
          columnIndex,
          player
        }
      }
      expect(actions.addPiece(columnIndex, pieceIndex, player)).toEqual(expectedAction)
    })

    it('should create an action to check answer', () => {
      const expectedAction = {
        type: constants.CHECK_ANSWER
      }
      expect(actions.checkAnswer()).toEqual(expectedAction)
    })

    it('should create an action to hover a piece', () => {
      const columnIndex = 1
      const expectedAction = {
        type: constants.HOVER_PIECE,
        payload: {
          columnIndex
        }
      }
      expect(actions.hoverPiece(columnIndex)).toEqual(expectedAction)
    })

    it('should create an action to blur a piece', () => {
      const expectedAction = {
        type: constants.BLUR_PIECE
      }
      expect(actions.blurPiece()).toEqual(expectedAction)
    })

    it('should create an action to win a game', () => {
      const expectedAction = {
        type: constants.WIN_GAME
      }
      expect(actions.winGame()).toEqual(expectedAction)
    })

    it('should create an action to draw a game', () => {
      const expectedAction = {
        type: constants.DRAW_GAME
      }
      expect(actions.drawGame()).toEqual(expectedAction)
    })

    it('should create an action to exit game', () => {
      const expectedAction = {
        type: constants.EXIT_GAME
      }
      expect(actions.exitGame()).toEqual(expectedAction)
    })
  })

  describe('reducers', () => {

    // Initial state
    const initialState = {
      grid: [],
      cols: 7,
      rows: 6,
      inserts: 0,
      player: 1,
      boardActive: false,
      matches: false,
      gameTied: false,
      result: null,
      isGameRunning: false,
      pieceIndex: null,
      hoverColumnIndex: null,
      splashSkipped: false
    }

    it('should return the initial state', () => {
      expect(reducer(undefined, {})).toEqual(initialState)
    })

    // it('should handle `START_GAME`', () => {
      // expect(
      //   reducer({
      //     grid: [],
      //     cols: 7,
      //     rows: 6,
      //     inserts: 0,
      //     player: 1,
      //     boardActive: false,
      //     matches: false,
      //     gameTied: false,
      //     result: null,
      //     isGameRunning: false,
      //     hovered: false,
      //     hoverColumnIndex: null
      //   }, {
      //     type: actions.START_GAME,
      //     payload: {
      //       cols: 7,
      //       rows: 6
      //     }
      //   })
      // ).toEqual({
      //   grid: [
      //     [0, 0, 0, 0, 0, 0, 0],
      //     [0, 0, 0, 0, 0, 0, 0],
      //     [0, 0, 0, 0, 0, 0, 0],
      //     [0, 0, 0, 0, 0, 0, 0],
      //     [0, 0, 0, 0, 0, 0, 0],
      //     [0, 0, 0, 0, 0, 0, 0]
      //   ],
      //   cols: 7,
      //   rows: 6,
      //   inserts: 0,
      //   player: 1,
      //   boardActive: true,
      //   matches: false,
      //   gameTied: false,
      //   result: null,
      //   isGameRunning: true,
      //   hovered: false,
      //   hoverColumnIndex: null
      // })
    // })

    // it('should handle `ADD_PIECE`', () => {

    // })

  })

})


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Grevillea 13(no. 67): 70 (1885)

#### Original name
Phyllachora puncta subsp. puncta (Cooke) Cooke

### Remarks
null


text:
<?php
/**
 *
 * This file is part of Aura for PHP.
 *
 * @license http://opensource.org/licenses/bsd-license.php BSD
 *
 */
namespace Aura\Web\Exception;

use Aura\Web\Exception;

/**
 *
 * Tried to get an invalid URL component.
 *
 * @package Aura.Web
 *
 */
class InvalidComponent extends Exception
{
}


text:
class Board
	attr_reader :columns, :rows

	def initialize(m,n)
		@columns = m
		@rows = n
	end
end


text:
package com.orm;

import android.content.Context;

import com.google.common.collect.MapMaker;

import java.util.concurrent.ConcurrentMap;

public class SugarContext {

    private static SugarContext instance = null;
    private SugarDb sugarDb;
    private Context context;
    private ConcurrentMap<Object, Long> entitiesMap;

    private SugarContext(Context context) {
        this.context = context;
        this.sugarDb = new SugarDb(context);
        this.entitiesMap = new MapMaker().weakKeys().makeMap();
    }

    public static SugarContext getSugarContext() {
        if (instance == null) {
            throw new NullPointerException("SugarContext has not been initialized properly. Call SugarContext.init(Context) in your Application.onCreate() method and SugarContext.terminate() in your Application.onTerminate() method.");
        }
        return instance;
    }

    public static void init(Context context) {
        instance = new SugarContext(context);
    }

    public static void terminate() {
        if (instance == null) {
            return;
        }
        instance.doTerminate();
    }

    /*
     * Per issue #106 on Github, this method won't be called in
     * any real Android device. This method is used purely in
     * emulated process environments such as an emulator or
     * Robolectric Android mock.
     */
    private void doTerminate() {
        if (this.sugarDb != null) {
            this.sugarDb.getDB().close();
        }
    }

    protected SugarDb getSugarDb() {
        return sugarDb;
    }

    ConcurrentMap<Object, Long> getEntitiesMap() {
        return entitiesMap;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">PriceCheck</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="title_activity_price_list">PriceList</string>
    <string name="title_activity_details">Details</string>
    <string name="title_activity_about">About</string>

</resources>


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/**
 * @path ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-219.js
 * @description Object.create - 'writable' property of one property in 'Properties' is a Boolean object (8.10.5 step 6.b)
 */

function testcase() {

        var newObj = Object.create({}, {
            prop: {
                writable: new Boolean()
            }
        });
        var hasProperty = newObj.hasOwnProperty("prop");

        newObj.prop = 121;

        return hasProperty && newObj.prop === 121;
    }
runTestCase(testcase);


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>SimpleJspWebsite</display-name>

  <welcome-file-list>
    <welcome-file>home.jsp</welcome-file>
  </welcome-file-list>

  <filter>
    <filter-name>Filter</filter-name>
    <filter-class>com.coolonWeb.Filter</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>Filter</filter-name>
    <url-pattern>*.jsp</url-pattern>
  </filter-mapping>

</web-app>


text:
<?php

namespace Pis\Framework\Annotation;

/**
 * @Annotation
 */
class ControllerActionSecurity
{
    /** @var bool */
    public $user = null;
    /** @var array */
    public $roles = null;
}


text:
typedef enum {
    MenuPageNone,
    MenuPageBreakfast,
    MenuPageLunch,
    MenuPageDinner,
    MenuPageDessert,
    MenuPageAbout,
} MenuPage;

@interface MenuController : UIViewController <UITableViewDataSource, UITableViewDelegate> {
    MenuPage _page;
}

@property (nonatomic) MenuPage page;

- (id)initWithMenu:(MenuPage)page;

@end


text:
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "device/fido/win/authenticator.h"

#include <windows.h>
#include <string>
#include <utility>
#include <vector>

#include "base/bind.h"
#include "base/check_op.h"
#include "base/containers/flat_map.h"
#include "base/memory/ref_counted.h"
#include "base/notreached.h"
#include "base/strings/string_util_win.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "components/device_event_log/device_event_log.h"
#include "device/fido/authenticator_supported_options.h"
#include "device/fido/ctap_get_assertion_request.h"
#include "device/fido/ctap_make_credential_request.h"
#include "device/fido/discoverable_credential_metadata.h"
#include "device/fido/fido_constants.h"
#include "device/fido/fido_transport_protocol.h"
#include "device/fido/win/type_conversions.h"
#include "device/fido/win/webauthn_api.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/microsoft_webauthn/webauthn.h"

namespace device {

namespace {

struct PlatformCredentialListDeleter {
  PlatformCredentialListDeleter(WinWebAuthnApi* win_api) : win_api_(win_api) {}
  inline void operator()(PWEBAUTHN_CREDENTIAL_DETAILS_LIST ptr) const {
    win_api_->FreePlatformCredentialList(ptr);
  }
  WinWebAuthnApi* win_api_;
};

}  // namespace

// static
void WinWebAuthnApiAuthenticator::IsUserVerifyingPlatformAuthenticatorAvailable(
    WinWebAuthnApi* api,
    base::OnceCallback<void(bool is_available)> callback) {
  base::ThreadPool::PostTaskAndReplyWithResult(
      FROM_HERE,
      {base::TaskPriority::USER_VISIBLE, base::MayBlock(),
       base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
      base::BindOnce(
          [](WinWebAuthnApi* api) {
            BOOL result;
            return api && api->IsAvailable() &&
                   api->IsUserVerifyingPlatformAuthenticatorAvailable(
                       &result) == S_OK &&
                   result == TRUE;
          },
          api),
      std::move(callback));
}

// static
void WinWebAuthnApiAuthenticator::IsConditionalMediationAvailable(
    WinWebAuthnApi* api,
    base::OnceCallback<void(bool is_available)> callback) {
  base::ThreadPool::PostTaskAndReplyWithResult(
      FROM_HERE,
      {base::TaskPriority::USER_VISIBLE, base::MayBlock(),
       base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
      base::BindOnce(
          [](WinWebAuthnApi* api) {
            return api && api->IsAvailable() && api->SupportsSilentDiscovery();
          },
          api),
      std::move(callback));
}

// static
void WinWebAuthnApiAuthenticator::EnumeratePlatformCredentials(
    WinWebAuthnApi* api,
    base::OnceCallback<
        void(std::vector<device::DiscoverableCredentialMetadata>)> callback) {
  base::ThreadPool::PostTaskAndReplyWithResult(
      FROM_HERE,
      {base::TaskPriority::USER_VISIBLE, base::MayBlock(),
       base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
      base::BindOnce(
          [](WinWebAuthnApi* api)
              -> std::vector<device::DiscoverableCredentialMetadata> {
            if (!api || !api->IsAvailable() ||
                !api->SupportsSilentDiscovery()) {
              return {};
            }

            WEBAUTHN_GET_CREDENTIALS_OPTIONS options{
                .dwVersion = WEBAUTHN_GET_CREDENTIALS_OPTIONS_VERSION_1,
                .pwszRpId = nullptr,
                .bBrowserInPrivateMode = false};

            PWEBAUTHN_CREDENTIAL_DETAILS_LIST credentials = nullptr;
            HRESULT hresult =
                api->GetPlatformCredentialList(&options, &credentials);
            std::unique_ptr<WEBAUTHN_CREDENTIAL_DETAILS_LIST,
                            PlatformCredentialListDeleter>
                credentials_deleter(credentials,
                                    PlatformCredentialListDeleter(api));

            if (hresult != S_OK) {
              return {};
            }
            return WinCredentialDetailsListToCredentialMetadata(*credentials);
          },
          api),
      std::move(callback));
}

// static
void WinWebAuthnApiAuthenticator::DeletePlatformCredential(
    WinWebAuthnApi* api,
    base::span<const uint8_t> credential_id,
    base::OnceCallback<void(bool)> callback) {
  base::ThreadPool::PostTaskAndReplyWithResult(
      FROM_HERE,
      {base::TaskPriority::USER_VISIBLE, base::MayBlock(),
       base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
      base::BindOnce(
          [](WinWebAuthnApi* api, std::vector<uint8_t> credential_id) -> bool {
            return api && api->IsAvailable() &&
                   api->SupportsSilentDiscovery() &&
                   api->DeletePlatformCredential(credential_id) == S_OK;
          },
          api,
          std::vector<uint8_t>(credential_id.begin(), credential_id.end())),
      std::move(callback));
}

WinWebAuthnApiAuthenticator::WinWebAuthnApiAuthenticator(
    HWND current_window,
    WinWebAuthnApi* win_api)
    : current_window_(current_window), win_api_(win_api) {
  CHECK(win_api_->IsAvailable());
  CoCreateGuid(&cancellation_id_);
}

WinWebAuthnApiAuthenticator::~WinWebAuthnApiAuthenticator() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  Cancel();
}

void WinWebAuthnApiAuthenticator::InitializeAuthenticator(
    base::OnceClosure callback) {
  std::move(callback).Run();
}

void WinWebAuthnApiAuthenticator::MakeCredential(
    CtapMakeCredentialRequest request,
    MakeCredentialOptions options,
    MakeCredentialCallback callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (is_pending_) {
    NOTREACHED();
    return;
  }
  is_pending_ = true;

  base::ThreadPool::PostTaskAndReplyWithResult(
      FROM_HERE, {base::TaskPriority::USER_BLOCKING, base::MayBlock()},
      base::BindOnce(&AuthenticatorMakeCredentialBlocking, win_api_,
                     current_window_, cancellation_id_, std::move(request),
                     std::move(options)),
      base::BindOnce(&WinWebAuthnApiAuthenticator::MakeCredentialDone,
                     weak_factory_.GetWeakPtr(), std::move(callback)));
}

void WinWebAuthnApiAuthenticator::MakeCredentialDone(
    MakeCredentialCallback callback,
    std::pair<CtapDeviceResponseCode,
              absl::optional<AuthenticatorMakeCredentialResponse>> result) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(is_pending_);
  is_pending_ = false;
  if (waiting_for_cancellation_) {
    // Don't bother invoking the reply callback if the caller has already
    // cancelled the operation.
    waiting_for_cancellation_ = false;
    return;
  }
  if (result.first != CtapDeviceResponseCode::kSuccess) {
    std::move(callback).Run(result.first, absl::nullopt);
    return;
  }
  if (!result.second) {
    std::move(callback).Run(CtapDeviceResponseCode::kCtap2ErrInvalidCBOR,
                            absl::nullopt);
    return;
  }
  std::move(callback).Run(result.first, std::move(result.second));
}

void WinWebAuthnApiAuthenticator::GetAssertion(CtapGetAssertionRequest request,
                                               CtapGetAssertionOptions options,
                                               GetAssertionCallback callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(!is_pending_);
  if (is_pending_)
    return;

  is_pending_ = true;

  base::ThreadPool::PostTaskAndReplyWithResult(
      FROM_HERE, {base::TaskPriority::USER_BLOCKING, base::MayBlock()},
      base::BindOnce(&AuthenticatorGetAssertionBlocking, win_api_,
                     current_window_, cancellation_id_, std::move(request),
                     std::move(options)),
      base::BindOnce(&WinWebAuthnApiAuthenticator::GetAssertionDone,
                     weak_factory_.GetWeakPtr(), std::move(callback)));
}

void WinWebAuthnApiAuthenticator::GetAssertionDone(
    GetAssertionCallback callback,
    std::pair<CtapDeviceResponseCode,
              absl::optional<AuthenticatorGetAssertionResponse>> result) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(is_pending_);
  is_pending_ = false;
  if (waiting_for_cancellation_) {
    waiting_for_cancellation_ = false;
    return;
  }
  if (result.first != CtapDeviceResponseCode::kSuccess) {
    std::move(callback).Run(result.first, absl::nullopt);
    return;
  }
  if (!result.second) {
    std::move(callback).Run(CtapDeviceResponseCode::kCtap2ErrInvalidCBOR,
                            absl::nullopt);
    return;
  }
  std::move(callback).Run(result.first, std::move(result.second));
}

void WinWebAuthnApiAuthenticator::GetCredentialInformationForRequest(
    const CtapGetAssertionRequest& request,
    base::OnceCallback<void(std::vector<DiscoverableCredentialMetadata>, bool)>
        callback) {
  // Since the Windows authenticator forwards requests to other devices such as
  // security keys, we cannot know if there are no available credentials for a
  // given request. Therefore, this function always sets has_credentials to
  // true.
  if (!request.allow_list.empty()) {
    std::move(callback).Run(/*credentials=*/{}, /*has_credentials=*/true);
    return;
  }
  if (!win_api_->SupportsSilentDiscovery()) {
    // The Windows platform authenticator is the only authenticator available to
    // us and we can't know if there are credentials in advance. Assume there
    // are credentials available.
    FIDO_LOG(DEBUG) << "Windows API version does not support silent discovery";
    std::move(callback).Run(/*credentials=*/{}, /*has_credentials=*/true);
    return;
  }
  FIDO_LOG(DEBUG) << "Silently discovering credentials for " << request.rp_id;
  std::u16string rp_id = base::UTF8ToUTF16(request.rp_id);
  WEBAUTHN_GET_CREDENTIALS_OPTIONS options{
      .dwVersion = WEBAUTHN_GET_CREDENTIALS_OPTIONS_VERSION_1,
      .pwszRpId = base::as_wcstr(rp_id),
      // TODO(nsatragno): plumb browser private mode status in.
      .bBrowserInPrivateMode = false};
  PWEBAUTHN_CREDENTIAL_DETAILS_LIST credentials = nullptr;
  HRESULT hresult = win_api_->GetPlatformCredentialList(&options, &credentials);
  std::unique_ptr<WEBAUTHN_CREDENTIAL_DETAILS_LIST,
                  PlatformCredentialListDeleter>
      credentials_deleter(credentials, PlatformCredentialListDeleter(win_api_));

  switch (hresult) {
    case S_OK: {
      std::vector<DiscoverableCredentialMetadata> result =
          WinCredentialDetailsListToCredentialMetadata(*credentials);
      FIDO_LOG(DEBUG) << "Found " << result.size() << " credentials";
      std::move(callback).Run(std::move(result), /*has_credentials=*/true);
      return;
    }
    case NTE_NOT_FOUND:
      FIDO_LOG(DEBUG) << "No credentials found";
      std::move(callback).Run(/*credentials=*/{}, /*has_credentials=*/true);
      return;
    default:
      FIDO_LOG(ERROR) << "Windows API returned unknown result: " << hresult;
      std::move(callback).Run(/*credentials=*/{}, /*has_credentials=*/true);
      return;
  }
}

void WinWebAuthnApiAuthenticator::GetTouch(base::OnceClosure callback) {
  NOTREACHED();
}

void WinWebAuthnApiAuthenticator::Cancel() {
  if (!is_pending_ || waiting_for_cancellation_)
    return;

  waiting_for_cancellation_ = true;
  // This returns immediately.
  win_api_->CancelCurrentOperation(&cancellation_id_);
}

FidoAuthenticator::Type WinWebAuthnApiAuthenticator::GetType() const {
  return Type::kWinNative;
}

std::string WinWebAuthnApiAuthenticator::GetId() const {
  return "WinWebAuthnApiAuthenticator";
}

bool WinWebAuthnApiAuthenticator::IsInPairingMode() const {
  return false;
}

bool WinWebAuthnApiAuthenticator::IsPaired() const {
  return false;
}

bool WinWebAuthnApiAuthenticator::RequiresBlePairingPin() const {
  return false;
}

absl::optional<FidoTransportProtocol>
WinWebAuthnApiAuthenticator::AuthenticatorTransport() const {
  // The Windows API could potentially use any external or
  // platform authenticator.
  return absl::nullopt;
}

bool WinWebAuthnApiAuthenticator::SupportsCredProtectExtension() const {
  return win_api_->Version() >= WEBAUTHN_API_VERSION_2;
}

bool WinWebAuthnApiAuthenticator::SupportsHMACSecretExtension() const {
  return true;
}

bool WinWebAuthnApiAuthenticator::SupportsEnterpriseAttestation() const {
  return win_api_->Version() >= WEBAUTHN_API_VERSION_3;
}

bool WinWebAuthnApiAuthenticator::SupportsCredBlobOfSize(
    size_t num_bytes) const {
  return win_api_->Version() >= WEBAUTHN_API_VERSION_3;
}

const absl::optional<AuthenticatorSupportedOptions>&
WinWebAuthnApiAuthenticator::Options() const {
  // The request can potentially be fulfilled by any device that Windows
  // communicates with, so returning AuthenticatorSupportedOptions really
  // doesn't make much sense.
  static const absl::optional<AuthenticatorSupportedOptions> no_options =
      absl::nullopt;
  return no_options;
}

base::WeakPtr<FidoAuthenticator> WinWebAuthnApiAuthenticator::GetWeakPtr() {
  return weak_factory_.GetWeakPtr();
}

bool WinWebAuthnApiAuthenticator::ShowsPrivacyNotice() const {
  return win_api_->Version() >= WEBAUTHN_API_VERSION_2;
}

}  // namespace device


text:
'use strict';

var Joi = require('joi'),
		User = require('../models/user').User,
		Boom = require('boom');

exports.subscribe = {
	handler: function(request, reply) {
		var user = new User({email: request.payload.email, name: request.payload.email});
		user.save(function(err, user) {
      if (!err) {
        reply(user).created('/users/' + user._id); // HTTP 201
      } else {
 	      if (11000 === err.code || 11001 === err.code) {
          reply(Boom.forbidden("You have already subscribed!"));
        }
        else reply(Boom.forbidden(getErrorMessageFrom(err))); // HTTP 403
      }
	  });
	},
	validate: {
		payload: {
			email: Joi.string().email()
		}
	}
}

exports.unsubscribe = {
	handler: function(request, reply) {
		User.findOne({ 'email': request.query.email }, function(err, user) {
      if (!err && user) {
        user.remove();
        reply({ message: "User unsubscribed successfully"});
      } else if (!err) {
        // Couldn't find the object.
        reply(Boom.notFound());
      } else {
        console.log(err);
        reply(Boom.badRequest("Could not delete user"));
      }
	  });
	},
	validate: {
		query: {
			email: Joi.string().email()
		}
	}
}


text:
package org.motechproject.odk.service.impl;

import org.motechproject.odk.domain.FormInstance;
import org.motechproject.odk.repository.FormInstanceDataService;
import org.motechproject.odk.service.FormInstanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Implementation of {@link FormInstanceService}.
 */
@Service("odkFormInstanceService")
public class FormInstanceServiceImpl implements FormInstanceService {

    @Autowired
    private FormInstanceDataService formInstanceDataService;

    @Override
    public void create(FormInstance formInstance) {
        formInstanceDataService.create(formInstance);
    }

    @Override
    public FormInstance getByInstanceId(String instanceId) {
        return formInstanceDataService.byInstanceId(instanceId);
    }
}


text:
(function ($_) {
	$_.Template = {};
	var attrBind = function(element, attrs) {
		var hasAttribute =  function (node, attr) {
			if (node.hasAttribute)
				return node.hasAttribute(attr);
			else
				return node.getAttribute(attr);
		};
		for(var key in attrs){
			if(key.toLowerCase() === 'html'){
				htmlBind(element,attrs[key]);
			}else if(key.toLowerCase() === 'text'){
				textBind(element,attrs[key]);
			}else if(key.toLowerCase() === 'class'){
				element.className = attrs[key];
			}else if(key.toLowerCase() === 'value'){
				element.value = attrs[key];
			}else if(hasAttribute(element, key)) {
				element.setAttribute(key,attrs[key]);
			}
		}
	}
	,textBind = function(element, text) {
		$_.Element.text(element, text);
	}
	,htmlBind = function(element, html) {
		element.innerHTML = html;
	}
	,findElements = function(root,selector) {
		return $_.Element.find(root, selector);
	}
	,bind = function(element, obj) {
		var key, targets;
		var valiableNodeType = element.nodeType === 1 || element.nodeType === 11;
		// validate
		if (!valiableNodeType) throw new TypeError();
		if (!$_.O.isPlainObject(obj)) throw new TypeError();
		for (key in obj){
			targets = findElements(element, key);
			if(targets.length === 0) continue;
			$_.A.each(targets, function(value) {
				if($_.O.isString(obj[key])||$_.O.isNumber(obj[key])) {
					textBind(value, obj[key]);
				}
				else if($_.O.isPlainObject(obj[key])){
					attrBind(value, obj[key]);
				}
			});

		}
		return element;

	};
	$_.Template.bind = bind;
})(Asdf);


text:
function GameBoard() {
  this.gameBoard = ["0","1","2","3","4","5","6","7","8"];
}

GameBoard.prototype.getBoard = function() {
  return this.gameBoard;
}

GameBoard.prototype.updateBoard = function(id, playerMarker) {
  this.gameBoard[id] = playerMarker;
}

GameBoard.prototype.switchMarker = function(playerMarker) {
  playerMarker = playerMarker === "O" ? "X":"O"
  return playerMarker;
}

module.exports = GameBoard;


text:
Compression::Result GZipFile::ReadRestOfFile(const std::string & a_FileName)
{
	InputFileStream File(a_FileName, InputFileStream::binary);
	const std::string Input{ std::istreambuf_iterator<char>(File), std::istreambuf_iterator<char>() };
	const ContiguousByteBufferView Data{ reinterpret_cast<const std::byte *>(Input.data()), Input.size() };

	return Compression::Extractor().ExtractGZip(Data);
}

void GZipFile::Write(const std::string & a_FileName, ContiguousByteBufferView a_Contents)
{
	OutputFileStream(a_FileName, OutputFileStream::binary) << Compression::Compressor().CompressGZip(a_Contents).GetStringView();
}


text:
package com.orionplatform.core.reflection.tasks;

import java.lang.reflect.Field;
import com.orionplatform.core.abstraction.Orion;
import com.orionplatform.core.exception.InaccessibleException;

public class InjectStringToInstanceVariableTask extends Orion
{
    public void run(Object object, String stringToInject, Field instanceVariable) throws InaccessibleException
    {
        try
        {
            instanceVariable.set(object, stringToInject);
        }
        catch(IllegalArgumentException e)
        {
            throw e;
        }
        catch(IllegalAccessException e)
        {
            throw new InaccessibleException("The instance variable is inaccessible.");
        }
    }
}


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

describe "/export/index" do
  fixtures :users

  before(:each) do
    login_as :taro
    assigns[:export_file_name] = "kozuchi-2009-04-01"
    render 'export/index'
  end

  it "should be success" do
    response.should be_success
  end
end


text:
Api Reference
=============

.. automodule:: pluggy
    :members:
    :undoc-members:
    :show-inheritance:

.. automethod:: pluggy._Result.get_result

.. automethod:: pluggy._Result.force_result

.. automethod:: pluggy._HookCaller.call_extra


text:
<?php

namespace Scrutinizer\Tests\PhpAnalyzer\PhpParser\Type;

use Scrutinizer\PhpAnalyzer\PhpParser\Type\TypeRegistry;

abstract class BaseTypeTest extends \PHPUnit_Framework_TestCase
{
    protected $provider;
    protected $registry;

    protected function setUp()
    {
        $this->provider = $this->getMock('Scrutinizer\PhpAnalyzer\PhpParser\Type\TypeProviderInterface');
        $this->registry = new TypeRegistry($this->provider);
    }

    protected function assertTypeEquals($thisType, $thatType)
    {
        $thisType = $this->resolveType($thisType);
        $thatType = $this->resolveType($thatType);

        $this->assertTrue($thisType->equals($thatType), 'Expected type "'.$thisType.'", but got type "'.$thatType.'".');
    }

    protected function createUnionType($types)
    {
        if (!is_array($types)) {
            $types = func_get_args();
        }

        return $this->registry->createUnionType($types);
    }

    protected function getNative($type)
    {
        return $this->registry->getNativeType($type);
    }

    protected function createNullableType($type)
    {
        $type = $this->resolveType($type);

        return $this->registry->createNullableType($type);
    }

    protected function resolveType($type)
    {
        return $this->registry->resolveType($type);
    }

    protected function getType($type)
    {
        return $this->registry->getNativeType($type);
    }
}


text:
define([
  "../../../components/utils",
  "angular"
], function(utils, angular) {
  resize.$inject = ["$window", "$timeout"];

  /**
   * @param {Service} $window - A reference to the browser's window object
   * @param {Function} $timeout - Angular wrapper for window.setTimeout.
   * @return {{restrict: string, link: link}} - resizeFolders directive
   */
  function resize($window, $timeout) {
    return {
      restrict: "A",
      link: function(scope, element, attrs) {
        var w = angular.element($window);

        scope.$watch(attrs.resizeFolders, function() {
          resizeFolderWidths();
        });

        w.on("resize", function() {
          $timeout(function() {
            resizeFolderWidths();
            scope.$apply();
          });
        });

        /**
         * Sets the scope.vm.width of either the maximum width of any visible folder,
         * or to the client width of the folder container
         */
        function resizeFolderWidths() {
          var maxWidth = scope.vm.maxWidth;
          var clientWidth = element[0].parentElement.parentElement.clientWidth;
          var overflowAuto = maxWidth > clientWidth;
          scope.vm.width = maxWidth > clientWidth ? maxWidth : clientWidth;
          angular.element(element[0].parentElement.parentElement).css("overflow-x", overflowAuto ? "auto" : "hidden");
        }
      }
    };
  }

  return {
    name: "resizeFolders",
    options: ["$window", "$timeout", resize]
  };
});


text:
package com.davidbracewell.apollo.stat.measure;

import com.davidbracewell.apollo.linear.NDArray;
import lombok.NonNull;

/**
 *
Distance measure implementation that is the one minus the value of a similarity measure

 *
 * @author David B. Bracewell
 */
class OneMinusSimilarityDistance implements DistanceMeasure {
   private static final long serialVersionUID = 1L;
   private final SimilarityMeasure similarityMeasure;

   /**
    * Instantiates a new One minus similarity distance.
    *
    * @param similarityMeasure the similarity measure
    */
   public OneMinusSimilarityDistance(@NonNull SimilarityMeasure similarityMeasure) {
      this.similarityMeasure = similarityMeasure;
   }

   @Override
   public SimilarityMeasure asSimilarityMeasure() {
      return similarityMeasure;
   }

   @Override
   public double calculate(NDArray v1, NDArray v2) {
      return 1d - similarityMeasure.calculate(v1,v2);
   }

}//END OF OneMinusSimilarityDistance


text:
---
title: Custom Output Formats
linktitle: Custom Output Formats
description: Hugo can output content in multiple formats, including calendar events, e-book formats, Google AMP, and JSON search indexes, or any custom text format.
date: 2017-03-22
publishdate: 2017-03-22
lastmod: 2019-12-11
categories: [templates]
keywords: ["amp", "outputs", "rss"]
menu:
  docs:
    parent: "templates"
    weight: 18
weight: 18
sections_weight: 18
draft: false
aliases: [/templates/outputs/,/extras/output-formats/,/content-management/custom-outputs/]
toc: true
---

This page describes how to properly configure your site with the media types and output formats, as well as where to create your templates for your custom outputs.

## Media Types

A [media type][] (also known as _MIME type_ and _content type_) is a two-part identifier for file formats and format contents transmitted on the internet.

This is the full set of built-in media types in Hugo:

{{< datatable "media" "types" "type" "suffixes" >}}

**Note:**

- It is possible to add custom media types or change the defaults; e.g., if you want to change the suffix for `text/html` to `asp`.
- `Suffixes` are the values that will be used for URLs and filenames for that media type in Hugo.
- The `Type` is the identifier that must be used when defining new/custom `Output Formats` (see below).
- The full set of media types will be registered in Hugo's built-in development server to make sure they are recognized by the browser.

To add or modify a media type, define it in a `mediaTypes` section in your [site configuration][config], either for all sites or for a given language.

{{< code-toggle file="config" >}}
[mediaTypes]
  [mediaTypes."text/enriched"]
  suffixes = ["enr"]
  [mediaTypes."text/html"]
  suffixes = ["asp"]
{{</ code-toggle >}}

The above example adds one new media type, `text/enriched`, and changes the suffix for the built-in `text/html` media type.

**Note:** these media types are configured for **your output formats**. If you want to redefine one of Hugo's default output formats (e.g. `HTML`), you also need to redefine the media type. So, if you want to change the suffix of the `HTML` output format from `html` (default) to `htm`:

```toml
[mediaTypes]
[mediaTypes."text/html"]
suffixes = ["htm"]

# Redefine HTML to update its media type.
[outputFormats]
[outputFormats.HTML]
mediaType = "text/html"
```

**Note** that for the above to work, you also need to add an `outputs` definition in your site config.

## Output Format Definitions

Given a media type and some additional configuration, you get an **Output Format**.

This is the full set of Hugo's built-in output formats:

{{< datatable "output" "formats" "name" "mediaType" "path" "baseName" "rel" "protocol" "isPlainText" "isHTML" "noUgly" "permalinkable" >}}

- A page can be output in as many output formats as you want, and you can have an infinite amount of output formats defined **as long as they resolve to a unique path on the file system**. In the above table, the best example of this is `AMP` vs. `HTML`. `AMP` has the value `amp` for `Path` so it doesn't overwrite the `HTML` version; e.g. we can now have both `/index.html` and `/amp/index.html`.
- The `MediaType` must match the `Type` of an already defined media type.
- You can define new output formats or redefine built-in output formats; e.g., if you want to put `AMP` pages in a different path.

To add or modify an output format, define it in an `outputFormats` section in your site's [configuration file](/getting-started/configuration/), either for all sites or for a given language.

{{< code-toggle file="config" >}}
[outputFormats.MyEnrichedFormat]
mediaType = "text/enriched"
baseName = "myindex"
isPlainText = true
protocol = "bep://"
{{</ code-toggle >}}

The above example is fictional, but if used for the homepage on a site with `baseURL` `https://example.org`, it will produce a plain text homepage with the URL `bep://example.org/myindex.enr`.

### Configure Output Formats

The following is the full list of configuration options for output formats and their default values:

`name`
: the output format identifier. This is used to define what output format(s) you want for your pages.

`mediaType`
: this must match the `Type` of a defined media type.

`path`
: sub path to save the output files.

`baseName`
: the base filename for the list filenames (homepage, etc.). **Default:** `index`.

`rel`
: can be used to create `rel` values in `link` tags. **Default:** `alternate`.

`protocol`
: will replace the "http://" or "https://" in your `baseURL` for this output format.

`isPlainText`
: use Go's plain text templates parser for the templates. **Default:** `false`.

`isHTML`
: used in situations only relevant for `HTML`-type formats; e.g., page aliases. **Default:** `false`.

`noUgly`
: used to turn off ugly URLs If `uglyURLs` is set to `true` in your site. **Default:** `false`.

`notAlternative`
: enable if it doesn't make sense to include this format in an `AlternativeOutputFormats` format listing on `Page` (e.g., with `CSS`). Note that we use the term _alternative_ and not _alternate_ here, as it does not necessarily replace the other format. **Default:** `false`.

`permalinkable`
: make `.Permalink` and `.RelPermalink` return the rendering Output Format rather than main ([see below](#link-to-output-formats)). This is enabled by default for `HTML` and `AMP`. **Default:** `false`.

`weight`
: Setting this to a non-zero value will be used as the first sort criteria.

## Output Formats for Pages

A `Page` in Hugo can be rendered to multiple _output formats_ on the file
system.

### Default Output Formats

Every `Page` has a [`Kind`][page_kinds] attribute, and the default Output
Formats are set based on that.

| Kind       | Default Output Formats |
| ---------- | ---------------------- |
| `page`     | HTML                   |
| `home`     | HTML, RSS              |
| `section`  | HTML, RSS              |
| `taxonomy` | HTML, RSS              |
| `term`     | HTML, RSS              |

### Customizing Output Formats

This can be changed by defining an `outputs` list of output formats in either
the `Page` front matter or in the site configuration (either for all sites or
per language).

Example from site config file:

{{< code-toggle file="config" >}}
[outputs]
  home = ["HTML", "AMP", "RSS"]
  page = ["HTML"]
{{</ code-toggle >}}

Note that in the above examples, the _output formats_ for `section`,
`taxonomy` and `term` will stay at their default value `["HTML", "RSS"]`.

{{% page-kinds %}}

* The `outputs` definition is per [`Page` `Kind`][page_kinds] (`page`, `home`, `section`, `taxonomy`, or `term`).
* The names (e.g. `HTML`, `AMP`) used must match the `Name` of a defined *Output Format*.
  * These names are case insensitive.
* These can be overridden per `Page` in the front matter of content files.

The following is an example of `YAML` front matter in a content file that defines output formats for the rendered `Page`:

```yaml
---
date: "2016-03-19"
outputs:
- html
- amp
- json
---
```

## List Output formats

Each `Page` has both an `.OutputFormats` (all formats, including the current) and an `.AlternativeOutputFormats` variable, the latter of which is useful for creating a `link rel` list in your site's `<head>`:

```go-html-template
{{ range .AlternativeOutputFormats -}}
<link rel="{{ .Rel }}" type="{{ .MediaType.Type }}" href="{{ .Permalink | safeURL }}">
{{ end -}}
```

## Link to Output Formats

`.Permalink` and `.RelPermalink` on `Page` will return the first output format defined for that page (usually `HTML` if nothing else is defined). This is regardless of the template file they are being called from.

__from `single.json.json`:__
```go-html-template
{{ .RelPermalink }} > /that-page/
{{ with  .OutputFormats.Get "json" -}}
{{ .RelPermalink }} > /that-page/index.json
{{- end }}
```

In order for them to return the output format of the current template file instead, the given output format should have its `permalinkable` setting set to true.

**Same template file as above with json output format's `permalinkable` set to true:**

```go-html-template
{{ .RelPermalink }} > /that-page/index.json
{{ with  .OutputFormats.Get "html" -}}
{{ .RelPermalink }} > /that-page/
{{- end }}
```

From content files, you can use the [`ref` or `relref` shortcodes](/content-management/shortcodes/#ref-and-relref):

```go-html-template
[Neat]({{</* ref "blog/neat.md" "amp" */>}})
[Who]({{</* relref "about.md#who" "amp" */>}})
```

## Templates for Your Output Formats

A new output format needs a corresponding template in order to render anything useful.

{{% note %}}
The key distinction for Hugo versions 0.20 and newer is that Hugo looks at an output format's `Name` and MediaType's `Suffixes` when choosing the template used to render a given `Page`.
{{% /note %}}

The following table shows examples of different output formats, the suffix used, and Hugo's respective template [lookup order][]. All the examples in the table can:

* Use a [base template][base].
* Include [partial templates][partials]

{{< datatable "output" "layouts" "Example" "OutputFormat" "Suffix" "Template Lookup Order" >}}

Hugo will now also detect the media type and output format of partials, if possible, and use that information to decide if the partial should be parsed as a plain text template or not.

Hugo will look for the name given, so you can name it whatever you want. But if you want it treated as plain text, you should use the file suffix and, if needed, the name of the Output Format. The pattern is as follows:

```go-html-template
[partial name].[OutputFormat].[suffix]
```

The partial below is a plain text template (Output Format is `CSV`, and since this is the only output format with the suffix `csv`, we don't need to include the Output Format's `Name`):

```go-html-template
{{ partial "mytextpartial.csv" . }}
```

[base]: /templates/base/
[config]: /getting-started/configuration/
[lookup order]: /templates/lookup/
[media type]: https://en.wikipedia.org/wiki/Media_type
[partials]: /templates/partials/
[page_kinds]: /templates/section-templates/#page-kinds


text:
import { combineReducers, createStore, applyMiddleware } from 'redux';
import { normalize } from 'normalizr';
import thunk from 'redux-thunk';
import { composeWithDevTools } from 'redux-devtools-extension/developmentOnly';
import { name, version } from '../../package.json';
import * as schemas from '../schemas';
import * as reducerMaps from '../reducerMaps';
import createHelpers from './createHelpers';
import createLogger from './logger';

const generateReducer = (map, initial) => (state = initial, action) => {
  const reducer = map.get(action.type);
  if (reducer === undefined) {
    return state;
  }

  return reducer(state, action);
};

const generateReducers = (newReducerMaps, normalizedInitialState) => {
  const reducers = {};

  Object.keys(newReducerMaps).forEach(mapName => {
    reducers[mapName] = generateReducer(reducerMaps[mapName], normalizedInitialState[mapName] || {});
  });

  return reducers;
};

// Add the reducer to your store on the `routing` key
export default function configureStore(initialState, helpersConfig) {
  const normalizedInitialState = JSON.parse(JSON.stringify(initialState));

  normalizedInitialState.restaurants.items = normalize(initialState.restaurants.items, [schemas.restaurant]);
  normalizedInitialState.tags.items = normalize(initialState.tags.items, [schemas.tag]);
  normalizedInitialState.teams.items = normalize(initialState.teams.items, [schemas.team]);
  normalizedInitialState.users.items = normalize(initialState.users.items, [schemas.user]);
  normalizedInitialState.restaurants.items.entities.votes = normalizedInitialState.restaurants.items.entities.votes || {};

  const reducers = generateReducers(reducerMaps, normalizedInitialState);

  const helpers = createHelpers(helpersConfig);
  const middleware = [thunk.withExtraArgument(helpers)];

  let enhancer;

  if (__DEV__) {
    middleware.push(createLogger());

    // https://github.com/zalmoxisus/redux-devtools-extension#14-using-in-production
    const composeEnhancers = composeWithDevTools({
      // Options: https://github.com/zalmoxisus/redux-devtools-extension/blob/master/docs/API/Arguments.md#options
      name: `${name}@${version}`,
    });

    // https://redux.js.org/docs/api/applyMiddleware.html
    enhancer = composeEnhancers(applyMiddleware(...middleware));
  } else {
    enhancer = applyMiddleware(...middleware);
  }

  const store = createStore(
    combineReducers(reducers),
    normalizedInitialState,
    enhancer
  );

  // Hot reload reducers (requires Webpack or Browserify HMR to be enabled)
  if (__DEV__ && module.hot) {
    module.hot.accept('../reducerMaps', () => {
      // eslint-disable-next-line global-require
      const newReducerMaps = require('../reducerMaps');
      const newReducers = generateReducers(newReducerMaps, normalizedInitialState);
      return store.replaceReducer(combineReducers(newReducers));
    });
  }

  return store;
}


text:
{% if sponsors %}

        {% if instance.title %}
{{ instance.title }}
{% endif %}

        {% if instance.group %}
            {% for group in groups %}

{{ group.level.name }}

                {% for sponsor in group.sponsors %}

                {% endfor %}

            {% endfor %}
        {% else %}
            {% if sublists %}
                {% for list in sublists %}

                    {% for sponsor in list %}
                        {% ifchanged sponsor.level.name %}

{{ sponsor.level.name }}

                        {% endifchanged %}

                    {% endfor %}

                {% endfor %}
            {% else %}
                {% if sponsors %}

                {% for sponsor in sponsors %}

                {% endfor %}

                {% endif %}
            {% endif %}
        {% endif %}

{% endif %}


text:
require 'test_helper'

class OpenidUserStoriesTest < ActionController::IntegrationTest

  fixtures :all

  def test_verifying_identifier_ownership
    claimed_id = "http://www.example.com/quentin"
    request_params = checkid_request_params.merge(
      'openid.identity' => claimed_id,
      'openid.claimed_id' => claimed_id)
    # OpenID requests comes in
    post '/server', request_params
    # User has to log in
    assert_redirected_to safe_login_url
    post '/session', :login => 'quentin', :password => 'test'
    # User has to verify the request
    assert_redirected_to proceed_url
    follow_redirect!
    assert_redirected_to decide_url
    follow_redirect!
    assert_template 'server/decide'
    post 'server/complete', :temporary => 1
    assert_match checkid_request_params['openid.return_to'], @response.redirect_url
    assert_match "mode=id_res", @response.redirect_url
  end

  def test_providing_sreg_data
    @account = accounts(:standard)
    @persona = @account.personas.first
    claimed_id = "http://www.example.com/quentin"
    request_params = checkid_request_params.merge(
      'openid.identity' => claimed_id,
      'openid.claimed_id' => claimed_id).merge(
      sreg_request_params)
    # OpenID requests comes in
    post '/server', request_params
    # User has to log in
    assert_redirected_to safe_login_url
    post '/session', :login => @account.login, :password => 'test'
    # User has to verify the request
    assert_redirected_to proceed_url
    follow_redirect!
    assert_redirected_to decide_url
    follow_redirect!
    assert_template 'server/decide'
    post 'server/complete', :temporary => 1, :site => { :persona_id => @persona.id, :sreg => { 'nickname' => @persona.nickname } }
    assert_match checkid_request_params['openid.return_to'], @response.redirect_url
    assert_match "mode=id_res", @response.redirect_url
    assert_match "openid.sreg.nickname=#{@persona.nickname}", @response.redirect_url, "Response was expected to have SReg nickname"
  end

  def test_providing_data_without_persona
    @account = accounts(:standard)
    @account.personas.each { |p| p.destroy }
    claimed_id = "http://www.example.com/quentin"
    request_params = checkid_request_params.merge(
      'openid.identity' => claimed_id,
      'openid.claimed_id' => claimed_id).merge(
      sreg_request_params)
    # OpenID requests comes in
    post '/server', request_params
    # User has to log in
    assert_redirected_to safe_login_url
    post '/session', :login => @account.login, :password => 'test'
    # User has to verify the request
    assert_redirected_to proceed_url
    follow_redirect!
    assert_redirected_to decide_url
    follow_redirect!
    assert_template 'server/decide'
    assert_match I18n.translate(:create_persona_link), @response.body
  end

  def test_responding_to_immidiate_requests_when_already_logged_in
    claimed_id = "http://www.example.com/quentin"
    request_params = checkid_request_params.merge(
      'openid.mode' => 'checkid_immediate',
      'openid.identity' => claimed_id,
      'openid.claimed_id' => claimed_id)
    # User will be logged in when the request comes in
    post '/session', :login => 'quentin', :password => 'test'
    post '/server', request_params
    # Request has to be answered directly
    assert_redirected_to proceed_url
    follow_redirect!
    assert_match checkid_request_params['openid.return_to'], @response.redirect_url
    assert_match "mode=id_res", @response.redirect_url
  end

  def test_trusting_a_site_and_responding_with_the_stored_release_policy_on_subsequent_requests
    @account = accounts(:standard)
    @persona = @account.personas.first
    claimed_id = "http://www.example.com/#{@account.login}"
    request_params = checkid_request_params.merge(
      'openid.identity' => claimed_id,
      'openid.claimed_id' => claimed_id).merge(
      sreg_request_params)
    # User will be logged in when the request comes in
    post '/session', :login => @account.login, :password => 'test'
    post '/server', request_params
    # User verifies the request and stores the details for this site
    assert_redirected_to proceed_url
    follow_redirect!
    assert_redirected_to decide_url
    follow_redirect!
    assert_template 'server/decide'
    post 'server/complete', :always => 1, :site => {
      :persona_id => @persona.id,
      :url => checkid_request_params['openid.trust_root'],
      :sreg => { 'nickname' => @persona.nickname } }
    assert_match checkid_request_params['openid.return_to'], @response.redirect_url
    assert_match "mode=id_res", @response.redirect_url, "Response mode was expected to be id_res"
    assert_match "openid.sreg.nickname=#{@persona.nickname}", @response.redirect_url, "Response was expected to have SReg nickname"
    # Has the site been saved?
    assert_not_nil @account.sites.find_by_url(checkid_request_params['openid.trust_root'])
    # Now comes the second request
    post '/server', request_params
    assert_redirected_to proceed_url
    follow_redirect!
    assert_match "mode=id_res", @response.redirect_url, "Response mode was expected to be id_res on subsequent request"
    assert_match "openid.sreg.nickname=#{@persona.nickname}", @response.redirect_url, "Response was expected to have SReg nickname on subsequent request"
  end

  def test_providing_ax_data
    @account = accounts(:standard)
    @persona = @account.personas.first
    claimed_id = "http://www.example.com/quentin"
    request_params = checkid_request_params.merge(
      'openid.identity' => claimed_id,
      'openid.claimed_id' => claimed_id).merge(
      ax_fetch_request_params)
    # OpenID requests comes in
    post '/server', request_params
    # User has to log in
    assert_redirected_to safe_login_url
    post '/session', :login => 'quentin', :password => 'test'
    # User has to verify the request
    assert_redirected_to proceed_url
    follow_redirect!
    assert_redirected_to decide_url
    follow_redirect!
    assert_template 'server/decide'
    post 'server/complete', :temporary => 1, :site => {
      :persona_id => @persona.id,
      :ax_fetch => {
        'nickname' => { 'type' => 'http://axschema.org/namePerson/friendly', 'value' => @persona.nickname },
        'gender' => { 'type' => 'http://axschema.org/person/gender', 'value' => @persona.gender } } }
    assert_match checkid_request_params['openid.return_to'], @response.redirect_url
    assert_match "openid.mode=id_res", @response.redirect_url, "Response mode was expected to be id_res"
    assert_match "openid.ax.mode=fetch_response", @response.redirect_url, "AX mode was expected to be fetch_response"
    assert_match @persona.nickname, @response.redirect_url, "Response was expected to have AX nickname: #{@response.redirect_url}"
    assert_match @persona.gender, @response.redirect_url, "Response was expected to have AX gender: #{@response.redirect_url}"
  end

  def test_storing_ax_data
    @account = accounts(:standard)
    @persona = @account.personas.first
    claimed_id = "http://www.example.com/quentin"
    request_params = checkid_request_params.merge(
      'openid.identity' => claimed_id,
      'openid.claimed_id' => claimed_id).merge(
      ax_store_request_params)
    # OpenID requests comes in
    post '/server', request_params
    # User has to log in
    assert_redirected_to safe_login_url
    post '/session', :login => 'quentin', :password => 'test'
    # User has to verify the request
    assert_redirected_to proceed_url
    follow_redirect!
    assert_redirected_to decide_url
    follow_redirect!
    assert_template 'server/decide'
    sent_fullname = ax_store_request_params['openid.ax.value.fullname.1']
    sent_email = ax_store_request_params['openid.ax.value.email.1']
    # Simulate accepting the fullname but not the email
    post 'server/complete', :temporary => 1, :site => {
      :persona_id => @persona.id,
      :ax_store => {
        'fullname' => { 'type' => ax_store_request_params['openid.ax.type.fullname'], 'value' => sent_fullname },
        'email' => { 'type' => ax_store_request_params['openid.ax.type.email'] } } }
    assert_match checkid_request_params['openid.return_to'], @response.redirect_url
    assert_match "openid.mode=id_res", @response.redirect_url, "Response mode was expected to be id_res"
    assert_match "openid.ax.mode=store_response", @response.redirect_url, "AX mode was expected to be store_response"
    # Check the attributes
    @persona.reload
    assert_equal sent_fullname, @persona.fullname, "Full name was expected to be #{sent_fullname}"
    assert_not_equal sent_email, @persona.email, "E-mail was not expected to be #{sent_email}"
  end

  def test_storing_ax_data
    @account = accounts(:standard)
    @persona = @account.personas.first
    claimed_id = "http://www.example.com/quentin"
    request_params = checkid_request_params.merge(
      'openid.identity' => claimed_id,
      'openid.claimed_id' => claimed_id).merge(
      ax_store_request_params)
    # OpenID requests comes in
    post '/server', request_params
    # User has to log in
    assert_redirected_to safe_login_url
    post '/session', :login => 'quentin', :password => 'test'
    # User has to verify the request
    assert_redirected_to proceed_url
    follow_redirect!
    assert_redirected_to decide_url
    follow_redirect!
    assert_template 'server/decide'
    sent_fullname = ax_store_request_params['openid.ax.value.fullname.1']
    sent_email = ax_store_request_params['openid.ax.value.email.1']
    # Simulate accepting the fullname but not the email
    post 'server/complete', :temporary => 1, :site => {
      :persona_id => @persona.id,
      :ax_store => {
        'fullname' => { 'type' => ax_store_request_params['openid.ax.type.fullname'], 'value' => sent_fullname },
        'email' => { 'type' => ax_store_request_params['openid.ax.type.email'] } } }
    assert_match checkid_request_params['openid.return_to'], @response.redirect_url
    assert_match "openid.mode=id_res", @response.redirect_url, "Response mode was expected to be id_res"
    assert_match "openid.ax.mode=store_response", @response.redirect_url, "AX mode was expected to be store_response"
    # Check the attributes
    @persona.reload
    assert_equal sent_fullname, @persona.fullname, "Full name was expected to be #{sent_fullname}"
    assert_not_equal sent_email, @persona.email, "E-mail was not expected to be #{sent_email}"
  end

  def test_responding_to_pape_requests
    claimed_id = "http://www.example.com/quentin"
    request_params = checkid_request_params.merge(
      'openid.identity' => claimed_id,
      'openid.claimed_id' => claimed_id).merge(
      pape_request_params)
    # OpenID requests comes in
    post '/server', request_params
    # User has to log in
    assert_redirected_to safe_login_url
    post '/session', :login => 'quentin', :password => 'test'
    # User has to verify the request
    assert_redirected_to proceed_url
    follow_redirect!
    assert_redirected_to decide_url
    follow_redirect!
    assert_template 'server/decide'
    post 'server/complete', :temporary => 1
    assert_match checkid_request_params['openid.return_to'], @response.redirect_url, "Redirected to: #{@response.redirect_url}"
    assert_match "openid.mode=id_res", @response.redirect_url, "Response mode was expected to be id_res"
    assert_match "openid.pape.auth_policies=", @response.redirect_url
    assert_match "openid.pape.auth_time=", @response.redirect_url, "Response was expected to have PAPE Auth Age: #{@response.redirect_url}"
    assert_match "openid.pape.nist_auth_level=", @response.redirect_url, "Response was expected to have PAPE NIST Auth Level: #{@response.redirect_url}"
  end

end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Jard. bot. État Brux. 15(1): 38 (1938)

#### Original name
Pleurotus palmicola Beeli

### Remarks
null


text:
<?php

namespace Tommaso\FooBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Tommaso\FooBundle\Entity\User;
use Tommaso\FooBundle\Entity\Phone;
use Symfony\Component\HttpFoundation\JsonResponse;

class DefaultController extends Controller
{
    public function insertAction($name, $surname, $birthdate)
    {
        //$date = date_parse($birthdate);
        $user = new User();
        $user->setName($name)->setSurname($surname)->setBirthdate(null);
        $phone = new Phone();
        $phone->setNumber("+393935345173")->setUser($user);
        $em = $this->getDoctrine()->getManager();
        $em->persist($user);
        $em->persist($phone);
        $em->flush();
        return $this->render('TommasoFooBundle:Default:index.html.twig', array('name' => $name));
    }

    public function listAction() {
        $em = $this->getDoctrine()->getManager();
        $phones = $em->getRepository("TommasoFooBundle:Phone")->findAll();
        $dato = array();
        foreach($phones as $user) :
            $dato[]['name'] = $user->getUser()->getName();
        endforeach;
        return new JsonResponse($dato);
    }
}


text:
{% extends "withnav_template.html" %}
{% from "components/form.html" import form_wrapper %}
{% from "components/file-upload.html" import file_upload %}
{% from "components/page-footer.html" import page_footer %}
{% from "components/page-header.html" import page_header %}
{% from "govuk_frontend_jinja/components/button/macro.html" import govukButton %}
{% from "govuk_frontend_jinja/components/back-link/macro.html" import govukBackLink %}
{% from "components/error-summary.html" import errorSummary %}

{% block service_page_title %}
  {{ form.logo.label.text }}
{% endblock %}

{% block backLink %}
  {{ govukBackLink({"href": back_link }) }}
{% endblock %}

{% block maincolumn_content %}
  {{ errorSummary(form) }}

  {{ page_header(form.logo.label.text) }}

a PNG file

at least 108 pixels high

a landscape image with a transparent background

        We do not recommend portrait images because they'll look very small. This is because the space for email branding has a fixed height.

      {{ file_upload(form.logo, allowed_file_extensions=[form.EXPECTED_LOGO_FORMAT], button_text='Upload logo') }}

        I do not have a file to upload

{% endblock %}


text:
PLUGIN_ID = "Corfunc Plug-In 0.1"
from corfunc import *


text:
<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Api_Transit extends Controller_Api
{
	public function before()
	{
		parent::before();

		$this->auto_render = FALSE;
		$this->response->headers('Content-Type', 'application/json');
	}

	/**
	 * Get data from the Bus Stops table
	 */
	public function action_bus()
	{
		try
		{
			$db = new Model_Api_Transit_Bus();
			echo json_encode($db->get_records('bus', $_GET['limit']));
		}
		catch ( Database_Exception $e )
		{
			echo $e->getMessage();
		}
	}

	/**
	 * Get data from the Lightrail table
	 */
	public function action_lightrail()
	{
		try
		{
			$db = new Model_Api_Transit_Lightrail();
			echo json_encode($db->get_records('lightrail', $_GET['limit']));
		}
		catch ( Database_Exception $e )
		{
			echo $e->getMessage();
		}
	}

	/**
	 * Get data from the Carpool table
	 */
	public function action_carpool()
	{
		try
		{
			$db = new Model_Api_Transit_Carpool();
			echo json_encode($db->get_records('carpool', $_GET['limit']));
		}
		catch ( Database_Exception $e )
		{
			echo $e->getMessage();
		}
	}

}


text:
* Handle Split View
* Error-marks are now displayed in all editors (inline or full)
* Error-ticks are displayed in both panels


text:
import { Server } from 'http';
import path from 'path';

import { Express, Request } from 'express';
import { graphqlHTTP } from 'express-graphql';
import fs from 'fs-extra';
import { execute, subscribe } from 'graphql';
import { Context } from 'graphql-ws';
import { useServer, Extra } from 'graphql-ws/lib/use/ws';
import ws from 'ws';

import { getSchema } from './schema';
import { authMiddleware, getUidFromToken, jwtFromRequest } from '~api/modules/auth';
import { Context as ExecutionContext } from '~api/types/resolver';

const anonymousContext = {
  user: undefined,
  session: {},
} as ExecutionContext;

function getWSContext(ctx: Context<Extra>): ExecutionContext {
  const apiKey = ctx.connectionParams?.apiKey ?? null;
  if (!apiKey) {
    return anonymousContext;
  }

  try {
    const token = jwtFromRequest({
      headers: {
        authorization: apiKey,
      },
    } as Request);

    const uid = getUidFromToken(token);
    if (!uid) {
      return anonymousContext;
    }

    return { user: { uid }, session: {} } as ExecutionContext;
  } catch {
    return anonymousContext;
  }
}

export async function setupGraphQL(app: Express, server: Server): Promise<() => void> {
  const introspection = await fs.readFile(path.resolve(__dirname, '../../introspection.json'));

  app.use(
    '/graphql',
    graphqlHTTP({
      schema: getSchema(),
      graphiql: process.env.NODE_ENV !== 'production',
    }),
  );

  app.get('/introspection', authMiddleware, (_, res) => {
    res.send(introspection);
  });

  const wsServer = new ws.Server({
    server,
    path: '/subscriptions',
  });

  return (): void => {
    useServer(
      {
        schema: getSchema(),
        context: getWSContext,
        execute,
        subscribe,
      },
      wsServer,
    );
  };
}


text:
import select

if hasattr(select, 'poll'):
    from polls import *
elif hasattr(select, 'select'):
    from selects import *
else:
    raise RuntimeError(select)


text:
package io.jawg.h2geo.model;

import com.google.gson.annotations.SerializedName;
import io.jawg.h2geo.parser.Type;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class PoiTypeTag {

  @SerializedName("key")
  private String key;

  @SerializedName("value")
  private String value;

  @SerializedName("type")
  private Type type;

  @SerializedName("required")
  private Boolean required;

  @SerializedName("editable")
  private Boolean editable;

  @SerializedName("show")
  private Boolean show;

  @SerializedName("values")
  private List<Map<String, Map<String,String>>> values;

  public PoiTypeTag() {
    values = new ArrayList<>();
  }

  public String getKey() {
    return key;
  }

  public void setKey(String key) {
    this.key = key;
  }

  public String getValue() {
    return value;
  }

  public void setValue(String value) {
    this.value = value;
  }

  public Boolean getRequired() {
    return required;
  }

  public void setRequired(Boolean required) {
    this.required = required;
  }

  public Boolean getShow() {
    return show;
  }

  public void setShow(Boolean show) {
    this.show = show;
  }

  public Boolean getEditable() {
    return editable;
  }

  public void setEditable(Boolean editable) {
    this.editable = editable;
  }

  public List<Map<String, Map<String,String>>> getValues() {
    return values;
  }

  public List<String> getReducedValues() {
    return values.stream().flatMap(o -> o.keySet().stream()).collect(Collectors.toList());
  }

  public void setValues(List<String> values) {
    if (values == null) {
      this.values = null;
    } else {
      this.values = Collections.synchronizedList(new ArrayList<>(values.size()));
      values.forEach(v -> {
        Map<String, Map<String, String>> valueMap = new HashMap<>();
        Map<String, String> map = new HashMap<>();
        map.put("default", v);
        valueMap.put(v, map);
        this.values.add(valueMap);
      });

    }
  }

  public Type getType() {
    return type;
  }

  public void setType(Type type) {
    this.type = type;
  }

  public void addValue(String value) {
    if (this.values == null) {
      values = Collections.synchronizedList(new ArrayList<>());
    }
    Map<String, Map<String, String>> valueMap = new HashMap<>();
    Map<String, String> map = new HashMap<>();
    map.put("default", value);
    valueMap.put(value, map);
    this.values.add(valueMap);
  }
}


text:
using System.Threading.Tasks;
using AllReady.Areas.Admin.Features.Itineraries;
using AllReady.Models;
using Xunit;
using System.Linq;
using MediatR;
using Moq;
using Shouldly;

namespace AllReady.UnitTest.Areas.Admin.Features.Itineraries
{
    public class SetTeamLeadCommandHandlerShould : InMemoryContextTest
    {
        protected override void LoadTestData()
        {
            var itinerary1 = new Itinerary
            {
                Id = 1,
                Name = "Test Itinerary 1"
            };

            var task1 = new VolunteerTask
            {
                Id = 1,
                Name = "Test Task"
            };

            var volunteerTaskUser1 = new ApplicationUser()
            {
                Id = "B8C2A338-837E-4157-B9F2-B3D5A072917B",
                Email = "volunteer1@example.com",
                PhoneNumber = "+1 (999) 999-9999",
                FirstName = "FirstName100",
                LastName = "LastName100"
            };

            var taskSignup1 = new VolunteerTaskSignup
            {
                Id = 1,
                VolunteerTask = task1,
                Itinerary = itinerary1,
                User = volunteerTaskUser1
            };

            var itinerary2= new Itinerary
            {
                Id = 2,
                Name = "Test Itinerary 2"
            };

            var task2 = new VolunteerTask
            {
                Id = 2,
                Name = "Test Task"
            };

            var volunteerTaskUser2 = new ApplicationUser()
            {
                Id = "B8C2A338-837E-4157-B9F2-B3D5A072917B",
                Email = "volunteer2@example.com",
                PhoneNumber = "+1 (999) 999-9999",
                FirstName = "FirstName200",
                LastName = "LastName200"
            };

            var taskSignup2 = new VolunteerTaskSignup
            {
                Id = 2,
                VolunteerTask = task2,
                Itinerary = itinerary2,
                User = volunteerTaskUser2,
                IsTeamLead = true
            };

            var volunteerTaskUser3 = new ApplicationUser()
            {
                Id = "65DBF162-074D-4E11-8258-6E12BC6B06B8",
                Email = "volunteer3@example.com",
                PhoneNumber = "+1 (999) 999-9999",
                FirstName = "FirstName300",
                LastName = "LastName300"
            };

            var taskSignup3 = new VolunteerTaskSignup
            {
                Id = 3,
                VolunteerTask = task2,
                Itinerary = itinerary2,
                User = volunteerTaskUser3
            };

            Context.Add(itinerary1);
            Context.Add(task1);
            Context.Add(taskSignup1);

            Context.Add(itinerary2);
            Context.Add(task2);
            Context.Add(taskSignup2);
            Context.Add(taskSignup3);

            Context.SaveChanges();
        }

        [Fact]
        public async Task SetsTeamLead_WhenNoPriorTeamLead()
        {
            var mockMediator = new Mock<IMediator>();

            var sut = new SetTeamLeadCommandHandler(Context, mockMediator.Object);
            var itineraryUrl = "https://localhost/Admin/Itinerary/Details/1";

            await sut.Handle(new SetTeamLeadCommand(1, 1, itineraryUrl));

            Context.VolunteerTaskSignups.Any(x => x.IsTeamLead && x.ItineraryId == 1).ShouldBeTrue();
        }

        [Fact]
        public async Task ReturnsSuccessResult_WhenTeamLeadChanged()
        {
            var mockMediator = new Mock<IMediator>();

            var sut = new SetTeamLeadCommandHandler(Context, mockMediator.Object);
            var itineraryUrl = "https://localhost/Admin/Itinerary/Details/1";

            var result = await sut.Handle(new SetTeamLeadCommand(1, 1, itineraryUrl));

            result.ShouldBe(SetTeamLeadResult.Success);
        }

        [Fact]
        public async Task ReplacesTeamLead_WhenPriorTeamLead()
        {
            var mockMediator = new Mock<IMediator>();

            var sut = new SetTeamLeadCommandHandler(Context, mockMediator.Object);
            var itineraryUrl = "https://localhost/Admin/Itinerary/Details/2";

            await sut.Handle(new SetTeamLeadCommand(2, 3, itineraryUrl));

            Context.VolunteerTaskSignups.Count(x => x.IsTeamLead && x.ItineraryId == 2).ShouldBe(1);

            var teamLead = Context.VolunteerTaskSignups.FirstOrDefault(x => x.IsTeamLead);

            teamLead.Id.ShouldBe(3);
        }

        [Fact]
        public async Task ReturnsFailureResult_WhenVolunteerTaskIdNotFound()
        {
            var mockMediator = new Mock<IMediator>();

            var sut = new SetTeamLeadCommandHandler(Context, mockMediator.Object);
            var itineraryUrl = "https://localhost/Admin/Itinerary/Details/1";

            var result = await sut.Handle(new SetTeamLeadCommand(1, 400, itineraryUrl));

            result.ShouldBe(SetTeamLeadResult.VolunteerTaskSignupNotFound);
        }
    }
}


text:
title: Extended Statistics Aggregation
short_title: Extended Statistics
---

A _multi-value_ metrics aggregation that computes extended statistics over
numeric values extracted from the aggregated documents.

The `_extended_stats` aggregations is an extended version of the
[Statistics Aggregation](stats-aggregation), where additional metrics are added
such as `_sum_of_squares`, `_variance`, `_std_deviation` and
`_std_deviation_bounds`, these are detailed in their corresponding aggregation
section:

* [Variance Aggregation](variance-aggregation)
* [Standard Deviation Aggregation](std_deviation-aggregation)

## Structuring

The following snippet captures the structure of extended statistics aggregations:

```json
"<aggregation_name>": {
  "_extended_stats": {
    "_field": "<field_name>"
  },
  ...
}
```

### Field

The `<field_name>` in the `_field` parameter defines the specific field from
which the numeric values in the documents are extracted and used to compute the
returned extended statistics.

Assuming the data consists of documents representing bank accounts, as shown in
the sample dataset of [Data Exploration]({{ '/docs/exploration' | relative_url }}#sample-dataset)
section:

{% capture req %}

```json
SEARCH /bank/

{
  "_query": "*",
  "_limit": 0,
  "_check_at_least": 1000,
  "_aggs": {
    "balance_stats": {
      "_extended_stats": {
        "_field": "balance"
      }
    }
  }
}
```
{% endcapture %}
{% include curl.html req=req %}

{% comment %}

```js
pm.test("Response is success", function() {
  pm.response.to.be.success;
});
```

```js
pm.test("Response is aggregation", function() {
  var jsonData = pm.response.json();
  function expectEqualNumbers(a, b) {
    pm.expect(Math.round(parseFloat(a) * 1000) / 1000).to.equal(Math.round(parseFloat(b) * 1000) / 1000);
  }
  expectEqualNumbers(jsonData.aggregations._doc_count, 1000);
  expectEqualNumbers(jsonData.aggregations.balance_stats._count, 1000);
  expectEqualNumbers(jsonData.aggregations.balance_stats._min, 7.99);
  expectEqualNumbers(jsonData.aggregations.balance_stats._max, 12699.46);
  expectEqualNumbers(jsonData.aggregations.balance_stats._avg, 2565.03304);
  expectEqualNumbers(jsonData.aggregations.balance_stats._sum, 2565033.04);
  expectEqualNumbers(jsonData.aggregations.balance_stats._sum_of_squares, 8844461934.66);
  expectEqualNumbers(jsonData.aggregations.balance_stats._variance, 2267334.7731415);
  expectEqualNumbers(jsonData.aggregations.balance_stats._std_deviation, 1505.7671709602053);
  expectEqualNumbers(jsonData.aggregations.balance_stats._std_deviation_bounds._upper, 5576.56738192041);
  expectEqualNumbers(jsonData.aggregations.balance_stats._std_deviation_bounds._lower, -446.50130192041049);
});
```
{% endcomment %}

The above aggregation computes the balance statistics over all documents. The
above will return the following:

```json
  "aggregations": {
    "_doc_count": 1000,
    "balance_stats": {
      "_count": 1000,
      "_min": 7.99,
      "_max": 12699.46,
      "_avg": 2565.03304,
      "_sum": 2565033.04,
      "_sum_of_squares": 8844461934.66,
      "_variance": 2267334.7731415,
      "_std_deviation": 1505.7671709602053,
      "_std_deviation_bounds": {
        "_upper": 5576.56738192041,
        "_lower": -446.50130192041049
      }
    }
  }, ...
```

The name of the aggregation (`balance_stats` above) also serves as the key by
which the aggregation result can be retrieved from the returned response.


text:
layout: feature
title: 'Foreign'
shortdef: 'is this a foreign word?'
---

Boolean feature. Is this a foreign word? Not a loan word and not a
foreign name but a genuinely foreign word appearing inside native
text, e.g. inside direct speech, titles of books etc. This feature
would apply either to the "X" part of speech (unanalyzable token), or
to other parts of speech if we know and are willing to annotate the
class to which the word belongs in its original language.

### Foreign: it is foreign

Example: _He said I could "dra åt helvete!"_

### Fscript: it is foreign and written in a foreign script

Example: _In Nepali, the mountain is called सगरमाथा._

### Tscript: it is foreign and transcribed from a foreign script

Example: _The above Nepali word can be transcribed Sagaramāthā._


text:
package cc.redpen.tokenizer;

import org.junit.jupiter.api.Test;

import java.util.List;

import static org.junit.jupiter.api.Assertions.assertEquals;

class WhiteSpaceTokenizerTest {
    @Test
    void testTokenize() {
        RedPenTokenizer tokenizer = new WhiteSpaceTokenizer();
        List<TokenElement> results = tokenizer.tokenize("this is a\u00A0pen");
        assertEquals(4, results.size());
        assertEquals("this", results.get(0).getSurface());
        assertEquals(0, results.get(0).getTags().size());
        assertEquals("is", results.get(1).getSurface());
        assertEquals(0, results.get(1).getTags().size());
        assertEquals("a", results.get(2).getSurface());
        assertEquals(0, results.get(2).getTags().size());
        assertEquals("pen", results.get(3).getSurface());
        assertEquals(0, results.get(3).getTags().size());
    }

    @Test
    void testTokenizeSentenceWithNoSpaceBracket() {
        RedPenTokenizer tokenizer = new WhiteSpaceTokenizer();
        List<TokenElement> results = tokenizer.tokenize("distributed(cluster) systems are good");
        assertEquals(7, results.size());
        assertEquals("distributed", results.get(0).getSurface());
        assertEquals(0, results.get(0).getTags().size());
        assertEquals("cluster", results.get(2).getSurface());
        assertEquals(0, results.get(1).getTags().size());
        assertEquals("systems", results.get(4).getSurface());
        assertEquals(0, results.get(2).getTags().size());
        assertEquals("are", results.get(5).getSurface());
        assertEquals(0, results.get(3).getTags().size());
        assertEquals("good", results.get(6).getSurface());
        assertEquals(0, results.get(4).getTags().size());
    }

    @Test
    void testTokenizeSentenceEndsWithPeriod() {
        RedPenTokenizer tokenizer = new WhiteSpaceTokenizer();
        List<TokenElement> results = tokenizer.tokenize("I am an engineer.");
        assertEquals(5, results.size());
        assertEquals("I", results.get(0).getSurface());
        assertEquals("am", results.get(1).getSurface());
        assertEquals("an", results.get(2).getSurface());
        assertEquals("engineer", results.get(3).getSurface());
        assertEquals(".", results.get(4).getSurface());
    }

    @Test
    void testTokenizeSentenceWithContraction() {
        RedPenTokenizer tokenizer = new WhiteSpaceTokenizer();
        List<TokenElement> results = tokenizer.tokenize("I'm an engineer");
        assertEquals(3, results.size());
        assertEquals("I'm", results.get(0).getSurface());
        assertEquals("an", results.get(1).getSurface());
        assertEquals("engineer", results.get(2).getSurface());
    }
}