text:
<?php

namespace Forthicime\MedecinBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * LoginHistoryRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class LoginHistoryRepository extends EntityRepository
{
}


text:
<?php

// Add options page (ACF Controller)
if( function_exists('acf_add_options_page') ) {
	acf_add_options_page();
}

if ( ! class_exists( 'Timber' ) ) {
	add_action( 'admin_notices', function() {
			echo '

Timber not activated. Make sure you activate the plugin in ' . esc_url( admin_url( 'plugins.php' ) ) . '

';
		} );
	return;
}

// Allow SVGs
function cc_mime_types($mimes) {
  $mimes['svg'] = 'image/svg+xml';
  return $mimes;
}
add_filter('upload_mimes', 'cc_mime_types');

if ( ! class_exists( 'Timber' ) ) {
	add_action( 'admin_notices', function() {
		echo '

Timber not activated. Make sure you activate the plugin in ' . esc_url( admin_url( 'plugins.php') ) . '

';
	});

	add_filter('template_include', function($template) {
		return get_stylesheet_directory() . '/static/no-timber.html';
	});

	return;
}

Timber::$dirname = array('templates', 'views');

class StarterSite extends TimberSite {

	function __construct() {
		add_theme_support( 'post-formats' );
		add_theme_support( 'post-thumbnails' );
		add_theme_support( 'menus' );
		add_theme_support( 'html5', array( 'comment-list', 'comment-form', 'search-form', 'gallery', 'caption' ) );
		add_filter( 'timber_context', array( $this, 'add_to_context' ) );
		add_filter( 'get_twig', array( $this, 'add_to_twig' ) );
		add_action( 'init', array( $this, 'register_post_types' ) );
		add_action( 'init', array( $this, 'register_taxonomies' ) );
		parent::__construct();
	}

	function register_post_types() {
		register_post_type( 'project',
      // CPT Options
      array(
        'labels' => array(
        'name' => __( 'Projects' ),
        'singular_name' => __( 'Project' )
      ),
        'menu_icon' => 'dashicons-megaphone',
        'supports' => array( 'title', 'editor', 'thumbnail' ),
        'public' => true,
        'has_archive' => false,
        'rewrite' => array('slug' => 'project'),
      )
    );
	}

	function register_taxonomies() {
		//this is where you can register custom taxonomies
	}

	function add_to_context( $data ) {
		$data['menu'] = new TimberMenu('main');
    $data['topnav'] = new TimberMenu('2');
    $data['footernav'] = new TimberMenu('3');
    $data['options'] = get_fields('option');
    $data['projects'] = Timber::get_posts('post_type=project');
		return $data;
	}

	function myfoo( $text ) {
		$text .= ' bar!';
		return $text;
	}

	function add_to_twig( $twig ) {
		/* this is where you can add your own functions to twig */
		$twig->addExtension( new Twig_Extension_StringLoader() );
		$twig->addFilter('myfoo', new Twig_SimpleFilter('myfoo', array($this, 'myfoo')));
		return $twig;
	}

}

// Call the google CDN version of jQuery for the frontend
// Make sure you use this with wp_enqueue_script('jquery'); in your header
function wpfme_jquery_enqueue() {
	wp_deregister_script('jquery');
	wp_register_script('jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js", false, null);
	wp_enqueue_script('jquery');
}
if (!is_admin()) add_action("wp_enqueue_scripts", "wpfme_jquery_enqueue", 11);

new StarterSite();

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

	<title>Viewport as an existing object</title>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
	<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
	<link rel="stylesheet" type="text/css" href="../../../codebase/fonts/font_roboto/roboto.css"/>
	<link rel="stylesheet" type="text/css" href="../../../codebase/dhtmlx.css"/>

			In this case dhtmlxWindows will use the existing object

			on page as a viewport. This type of a viewport is used

			to make elements in it selectable.

			By default the viewport has no border. In our samples

			we showed the border to specify the boundaries

			in which the window is displayed on page,

			i.e. we visualised the viewport.

			<input type="text" value="check input">
			<input type="button" value="click me">
			<select><option>select</option></select>

			Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.


text:
package com.petpet.c3po.command;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.petpet.c3po.common.Constants;
import com.petpet.c3po.controller.Controller;
import com.petpet.c3po.parameters.GatherParams;
import com.petpet.c3po.parameters.Params;
import com.petpet.c3po.utils.Configurator;
import com.petpet.c3po.utils.exceptions.C3POConfigurationException;

/**
 * Submits a gather meta data request to the controller based on the passed
 * parameters.
 *
 * @author Petar Petrov <me@petarpetrov.org>
 *
 */
public class GatherCommand extends AbstractCLICommand implements Command {

  /**
   * Default logger.
   */
  private static final Logger LOG = LoggerFactory.getLogger( GatherCommand.class );

  /**
   * The gathering params passed on the command line.
   */
  private GatherParams params;

  /**
   * Creates a controller and submits a process meta data request.
   */
  @Override
  public void execute() {
    LOG.info( "Starting meta data gathering command." );
    long start = System.currentTimeMillis();

    final Configurator configurator = Configurator.getDefaultConfigurator();
    //configurator.configure();

    final Map<String, String> conf = new HashMap<String, String>();
    conf.put( Constants.OPT_COLLECTION_LOCATION, this.params.getLocation() );
    conf.put( Constants.OPT_COLLECTION_NAME, this.params.getCollection() );
    conf.put( Constants.OPT_INPUT_TYPE, this.params.getType() );
    conf.put( Constants.OPT_RECURSIVE, this.params.isRecursive() + "" );

    final Controller ctrl = new Controller( configurator );
    try {
      ctrl.processMetaData( conf );
      System.out.println( "I finished translating the data. I am fluent in over six million forms of communication." );
      System.out.println( "I finished memorizing all the data." );
    } catch ( C3POConfigurationException e ) {
      LOG.error( e.getMessage() );
      System.err.println("An error occurred: " + e.getMessage());
      return;

    } finally {
      cleanup();
    }

    long end = System.currentTimeMillis();
    this.setTime( end - start );
  }

  @Override
  public void setParams( Params params ) {
    if ( params != null && params instanceof GatherParams ) {
      this.params = (GatherParams) params;
    }
  }

}


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer/autoload_real.php';

return ComposerAutoloaderInit21ad58890ca5cc8e381ffeafc0bbde31::getLoader();


text:
import defaultOptions from './default.options'
import store from './menu.store'
import utils from './utils/utils'
import Menu from './models/menu'
import Button from './models/button'
import runner from './runner'
import dom from './utils/dom'

export default {
  new (selector, options) {
    let settings = utils.extend(defaultOptions, options)
    let buttons = dom.qsa(selector)

    store.add(settings.name, new Menu(settings))
    for (let i = 0; i < buttons.length; i++) {
      new Button(buttons[i], settings)
    }
  },

  status () {
    return runner('status', ...arguments)
  },

  reload () {
    return runner('reload', ...arguments)
  },

  close () {
    return runner('close', ...arguments)
  },

  open () {
    return runner('open', ...arguments)
  },

  toggle () {
    return runner('toggle', ...arguments)
  }
}


text:
SELFDIR=$(dirname $(readlink -f $0))
cd ${NODEMCU_TESTTMP}

exec /usr/sbin/mosquitto -c ${SELFDIR}/test-mqtt.mosquitto.conf


text:
<?php
/*
	Question2Answer by Gideon Greenspan and contributors
	http://www.question2answer.org/

	File: qa-include/qa-page-question-view.php
	Description: Common functions for question page viewing, either regular or via Ajax

	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	More about this license: http://www.question2answer.org/license.php
*/

	if (!defined('QA_VERSION')) { // don't allow this page to be requested directly from browser
		header('Location: ../');
		exit;
	}

	function qa_page_q_load_as($question, $childposts)
/*
	Given a $question and its $childposts from the database, return a list of that question's answers
*/
	{
		$answers=array();

		foreach ($childposts as $postid => $post)
			switch ($post['type']) {
				case 'A':
				case 'A_HIDDEN':
				case 'A_QUEUED':
					$answers[$postid]=$post;
					break;
			}

		return $answers;
	}

	function qa_page_q_load_c_follows($question, $childposts, $achildposts)
/*
	Given a $question, its $childposts and its answers $achildposts from the database,
	return a list of comments or follow-on questions for that question or its answers
*/
	{
		$commentsfollows=array();

		foreach ($childposts as $postid => $post)
			switch ($post['type']) {
				case 'Q': // never show follow-on Qs which have been hidden, even to admins
				case 'C':
				case 'C_HIDDEN':
				case 'C_QUEUED':
					$commentsfollows[$postid]=$post;
					break;
			}

		foreach ($achildposts as $postid => $post)
			switch ($post['type']) {
				case 'Q': // never show follow-on Qs which have been hidden, even to admins
				case 'C':
				case 'C_HIDDEN':
				case 'C_QUEUED':
					$commentsfollows[$postid]=$post;
					break;
			}

		return $commentsfollows;
	}

	function qa_page_q_post_rules($post, $parentpost=null, $siblingposts=null, $childposts=null)
/*
	Returns elements that can be added to $post which describe which operations the current user may perform on that
	post. This function is a key part of Q2A's logic and is ripe for overriding by plugins. Pass $post's $parentpost if
	there is one, or null otherwise. Pass an array which contains $post's siblings (i.e. other posts with the same type
	and parent) in $siblingposts and $post's children in $childposts. Both of these latter arrays can contain additional
	posts retrieved from the database, and these will be ignored.
*/
	{
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

		$userid=qa_get_logged_in_userid();
		$cookieid=qa_cookie_get();
		$userlevel=qa_user_level_for_post($post);

		$rules['isbyuser']=qa_post_is_by_user($post, $userid, $cookieid);
		$rules['queued']=(substr($post['type'], 1)=='_QUEUED');
		$rules['closed']=($post['basetype']=='Q') && (isset($post['closedbyid']) || (isset($post['selchildid']) && qa_opt('do_close_on_select')));

	//	Cache some responses to the user permission checks

		$permiterror_post_q=qa_user_permit_error('permit_post_q', null, $userlevel); // don't check limits here, so we can show error message
		$permiterror_post_a=qa_user_permit_error('permit_post_a', null, $userlevel);
		$permiterror_post_c=qa_user_permit_error('permit_post_c', null, $userlevel);

		$permiterror_edit=qa_user_permit_error(($post['basetype']=='Q') ? 'permit_edit_q' :
			(($post['basetype']=='A') ? 'permit_edit_a' : 'permit_edit_c'), null, $userlevel);
		$permiterror_retagcat=qa_user_permit_error('permit_retag_cat', null, $userlevel);
		$permiterror_flag=qa_user_permit_error('permit_flag', null, $userlevel);
		$permiterror_hide_show=qa_user_permit_error($rules['isbyuser'] ? null : 'permit_hide_show', null, $userlevel);
		$permiterror_close_open=qa_user_permit_error($rules['isbyuser'] ? null : 'permit_close_q', null, $userlevel);
		$permiterror_moderate=qa_user_permit_error('permit_moderate', null, $userlevel);

	//	General permissions

		$rules['authorlast']=((!isset($post['lastuserid'])) || ($post['lastuserid']===$post['userid']));
		$rules['viewable']=$post['hidden'] ? (!$permiterror_hide_show) : ($rules['queued'] ? ($rules['isbyuser'] || !$permiterror_moderate) : true);

	//	Answer, comment and edit might show the button even if the user still needs to do something (e.g. log in)

		$rules['answerbutton']=($post['type']=='Q') && ($permiterror_post_a!='level') && (!$rules['closed']) &&
			(qa_opt('allow_self_answer') || !$rules['isbyuser']);

		$rules['commentbutton']=(($post['type']=='Q') || ($post['type']=='A')) &&
			($permiterror_post_c!='level') && qa_opt(($post['type']=='Q') ? 'comment_on_qs' : 'comment_on_as');
		$rules['commentable']=$rules['commentbutton'] && !$permiterror_post_c;

		$rules['editbutton']=(!$post['hidden']) && (!$rules['closed']) &&
			($rules['isbyuser'] || (($permiterror_edit!='level') && ($permiterror_edit!='approve') && (!$rules['queued'])));
		$rules['editable']=$rules['editbutton'] && ($rules['isbyuser'] || !$permiterror_edit);

		$rules['retagcatbutton']=($post['basetype']=='Q') && (qa_using_tags() || qa_using_categories()) &&
			(!$post['hidden']) && ($rules['isbyuser'] || (($permiterror_retagcat!='level') && ($permiterror_retagcat!='approve')) );
		$rules['retagcatable']=$rules['retagcatbutton'] && ($rules['isbyuser'] || !$permiterror_retagcat);

		if ($rules['editbutton'] && $rules['retagcatbutton']) { // only show one button since they lead to the same form
			if ($rules['retagcatable'] && !$rules['editable'])
				$rules['editbutton']=false; // if we can do this without getting an error, show that as the title
			else
				$rules['retagcatbutton']=false;
		}

		$rules['aselectable']=($post['type']=='Q') && !qa_user_permit_error($rules['isbyuser'] ? null : 'permit_select_a', null, $userlevel);

		$rules['flagbutton']=qa_opt('flagging_of_posts') && (!$rules['isbyuser']) && (!$post['hidden']) && (!$rules['queued']) &&
			(!@$post['userflag']) && ($permiterror_flag!='level') && ($permiterror_flag!='approve');
		$rules['flagtohide']=$rules['flagbutton'] && (!$permiterror_flag) && (($post['flagcount']+1)>=qa_opt('flagging_hide_after'));
		$rules['unflaggable']=@$post['userflag'] && (!$post['hidden']);
		$rules['clearflaggable']=($post['flagcount']>=(@$post['userflag'] ? 2 : 1)) && !qa_user_permit_error('permit_hide_show', null, $userlevel);

	//	Other actions only show the button if it's immediately possible

		$notclosedbyother=!($rules['closed'] && isset($post['closedbyid']) && !$rules['authorlast']);
		$nothiddenbyother=!($post['hidden'] && !$rules['authorlast']);

		$rules['closeable']=qa_opt('allow_close_questions') && ($post['type']=='Q') && (!$rules['closed']) && !$permiterror_close_open;
		$rules['reopenable']=$rules['closed'] && isset($post['closedbyid']) && (!$permiterror_close_open) && (!$post['hidden']) &&
			($notclosedbyother || !qa_user_permit_error('permit_close_q', null, $userlevel));
			// cannot reopen a question if it's been hidden, or if it was closed by someone else and you don't have global closing permissions
		$rules['moderatable']=$rules['queued'] && !$permiterror_moderate;
		$rules['hideable']=(!$post['hidden']) && ($rules['isbyuser'] || !$rules['queued']) &&
			(!$permiterror_hide_show) && ($notclosedbyother || !qa_user_permit_error('permit_hide_show', null, $userlevel));
			// cannot hide a question if it was closed by someone else and you don't have global hiding permissions
		$rules['reshowimmed']=$post['hidden'] && !qa_user_permit_error('permit_hide_show', null, $userlevel);
			// means post can be reshown immediately without checking whether it needs moderation
		$rules['reshowable']=$post['hidden'] && (!$permiterror_hide_show) &&
			($rules['reshowimmed'] || ($nothiddenbyother && !$post['flagcount']));
			// cannot reshow a question if it was hidden by someone else, or if it has flags - unless you have global hide/show permissions
		$rules['deleteable']=$post['hidden'] && !qa_user_permit_error('permit_delete_hidden', null, $userlevel);
		$rules['claimable']=(!isset($post['userid'])) && isset($userid) && strlen(@$post['cookieid']) && (strcmp(@$post['cookieid'], $cookieid)==0) &&
			!(($post['basetype']=='Q') ? $permiterror_post_q : (($post['basetype']=='A') ? $permiterror_post_a : $permiterror_post_c));
		$rules['followable']=($post['type']=='A') ? qa_opt('follow_on_as') : false;

	//	Check for claims that could break rules about self answering and multiple answers

		if ($rules['claimable'] && ($post['basetype']=='A')) {
			if ( (!qa_opt('allow_self_answer')) && isset($parentpost) && qa_post_is_by_user($parentpost, $userid, $cookieid) )
				$rules['claimable']=false;

			if (isset($siblingposts) && !qa_opt('allow_multi_answers'))
				foreach ($siblingposts as $siblingpost)
					if ( ($siblingpost['parentid']==$post['parentid']) && ($siblingpost['basetype']=='A') && qa_post_is_by_user($siblingpost, $userid, $cookieid))
						$rules['claimable']=false;
		}

	//	Now make any changes based on the child posts

		if (isset($childposts))
			foreach ($childposts as $childpost)
				if ($childpost['parentid']==$post['postid']) {
					$rules['deleteable']=false;

					if (($childpost['basetype']=='A') && qa_post_is_by_user($childpost, $userid, $cookieid)) {
						if (!qa_opt('allow_multi_answers'))
							$rules['answerbutton']=false;

						if (!qa_opt('allow_self_answer'))
							$rules['claimable']=false;
					}
				}

	//	Return the resulting rules

		return $rules;
	}

	function qa_page_q_question_view($question, $parentquestion, $closepost, $usershtml, $formrequested)
/*
	Return the $qa_content['q_view'] element for $question as viewed by the current user. If this question is a
	follow-on, pass the question for this question's parent answer in $parentquestion, otherwise null. If the question
	is closed, pass the post used to close this question in $closepost, otherwise null. $usershtml should be an array
	which maps userids to HTML user representations, including the question's author and (if present) last editor. If a
	form has been explicitly requested for the page, set $formrequested to true - this will hide the buttons.
*/
	{
		$questionid=$question['postid'];
		$userid=qa_get_logged_in_userid();
		$cookieid=qa_cookie_get();

		$htmloptions=qa_post_html_options($question, null, true);
		$htmloptions['answersview']=false; // answer count is displayed separately so don't show it here
		$htmloptions['avatarsize']=qa_opt('avatar_q_page_q_size');
		$htmloptions['q_request']=qa_q_request($question['postid'], $question['title']);
		$q_view=qa_post_html_fields($question, $userid, $cookieid, $usershtml, null, $htmloptions);

		$q_view['main_form_tags']='method="post" action="'.qa_self_html().'"';
		$q_view['voting_form_hidden']=array('code' => qa_get_form_security_code('vote'));
		$q_view['buttons_form_hidden']=array('code' => qa_get_form_security_code('buttons-'.$questionid), 'qa_click' => '');

	//	Buttons for operating on the question

		if (!$formrequested) { // don't show if another form is currently being shown on page
			$clicksuffix=' onclick="qa_show_waiting_after(this, false);"'; // add to operations that write to database
			$buttons=array();

			if ($question['editbutton'])
				$buttons['edit']=array(
					'tags' => 'name="q_doedit"',
					'label' => qa_lang_html('question/edit_button'),
					'popup' => qa_lang_html('question/edit_q_popup'),
				);

			$hascategories=qa_using_categories();

			if ($question['retagcatbutton'])
				$buttons['retagcat']=array(
					'tags' => 'name="q_doedit"',
					'label' => qa_lang_html($hascategories ? 'question/recat_button' : 'question/retag_button'),
					'popup' => qa_lang_html($hascategories
						? (qa_using_tags() ? 'question/retag_cat_popup' : 'question/recat_popup')
						: 'question/retag_popup'
					),
				);

			if ($question['flagbutton'])
				$buttons['flag']=array(
					'tags' => 'name="q_doflag"'.$clicksuffix,
					'label' => qa_lang_html($question['flagtohide'] ? 'question/flag_hide_button' : 'question/flag_button'),
					'popup' => qa_lang_html('question/flag_q_popup'),
				);

			if ($question['unflaggable'])
				$buttons['unflag']=array(
					'tags' => 'name="q_dounflag"'.$clicksuffix,
					'label' => qa_lang_html('question/unflag_button'),
					'popup' => qa_lang_html('question/unflag_popup'),
				);

			if ($question['clearflaggable'])
				$buttons['clearflags']=array(
					'tags' => 'name="q_doclearflags"'.$clicksuffix,
					'label' => qa_lang_html('question/clear_flags_button'),
					'popup' => qa_lang_html('question/clear_flags_popup'),
				);

			if ($question['closeable'])
				$buttons['close']=array(
					'tags' => 'name="q_doclose"',
					'label' => qa_lang_html('question/close_button'),
					'popup' => qa_lang_html('question/close_q_popup'),
				);

			if ($question['reopenable'])
				$buttons['reopen']=array(
					'tags' => 'name="q_doreopen"'.$clicksuffix,
					'label' => qa_lang_html('question/reopen_button'),
					'popup' => qa_lang_html('question/reopen_q_popup'),
				);

			if ($question['moderatable']) {
				$buttons['approve']=array(
					'tags' => 'name="q_doapprove"'.$clicksuffix,
					'label' => qa_lang_html('question/approve_button'),
					'popup' => qa_lang_html('question/approve_q_popup'),
				);

				$buttons['reject']=array(
					'tags' => 'name="q_doreject"'.$clicksuffix,
					'label' => qa_lang_html('question/reject_button'),
					'popup' => qa_lang_html('question/reject_q_popup'),
				);
			}

			if ($question['hideable'])
				$buttons['hide']=array(
					'tags' => 'name="q_dohide"'.$clicksuffix,
					'label' => qa_lang_html('question/hide_button'),
					'popup' => qa_lang_html('question/hide_q_popup'),
				);

			if ($question['reshowable'])
				$buttons['reshow']=array(
					'tags' => 'name="q_doreshow"'.$clicksuffix,
					'label' => qa_lang_html('question/reshow_button'),
					'popup' => qa_lang_html('question/reshow_q_popup'),
				);

			if ($question['deleteable'])
				$buttons['delete']=array(
					'tags' => 'name="q_dodelete"'.$clicksuffix,
					'label' => qa_lang_html('question/delete_button'),
					'popup' => qa_lang_html('question/delete_q_popup'),
				);

			if ($question['claimable'])
				$buttons['claim']=array(
					'tags' => 'name="q_doclaim"'.$clicksuffix,
					'label' => qa_lang_html('question/claim_button'),
					'popup' => qa_lang_html('question/claim_q_popup'),
				);

			if ($question['answerbutton']) // don't show if shown by default
				$buttons['answer']=array(
					'tags' => 'name="q_doanswer" id="q_doanswer" onclick="return qa_toggle_element(\'anew\')"',
					'label' => qa_lang_html('question/answer_button'),
					'popup' => qa_lang_html('question/answer_q_popup'),
				);

			if ($question['commentbutton'])
				$buttons['comment']=array(
					'tags' => 'name="q_docomment" onclick="return qa_toggle_element(\'c'.$questionid.'\')"',
					'label' => qa_lang_html('question/comment_button'),
					'popup' => qa_lang_html('question/comment_q_popup'),
				);

			if (substr($question['notify'],0,3)==='vk:') {
				$datafy = json_decode(substr($question['notify'],3), true);
					if ($datafy) {
						// Get group info
						require_once QA_INCLUDE_DIR.'vk/vks.php';
						$ginfo = $vks->getGroupInfo($datafy['groupid']);

						$buttons['vk']=array(
							'tags' => 'name="q_openinvk" id="q_openinvk" onclick="window.open(\'https://vk.com/'.$ginfo['screen_name'].'?w=wall-'.$datafy['groupid'].'_'.$datafy['id'].'%2Fall\'); return false;"',
							'label' => qa_lang_html('vk/openinvk'),
							'popup' => qa_lang_html('vk/openinvk'),
						);

						if ($question['hideable']) {
							$buttons['shortlink2']=array(
								'tags' => 'name="q_shortlink2" id="q_shortlink2" onclick="if (prompt(\''.qa_lang_html('vk/shortthislink').'\', \''.qa_opt('site_url').'index.php?qa='.$question['postid'].'\')) window.open(\'https://vk.com/'.$ginfo['screen_name'].'?w=wall-'.$datafy['groupid'].'_'.$datafy['id'].'%2Fall\'); return false;"',
								'label' => qa_lang_html('vk/advertise'),
								'popup' => qa_lang_html('vk/advertise'),
							);
						}
					}
			};

			$q_view['form']=array(
				'style' => 'light',
				'buttons' => $buttons,
			);
		}

	//	Information about the question of the answer that this question follows on from (or a question directly)

		if (isset($parentquestion))
			$q_view['follows']=array(
				'label' => qa_lang_html(($question['parentid']==$parentquestion['postid']) ? 'question/follows_q' : 'question/follows_a'),
				'title' => qa_html(qa_block_words_replace($parentquestion['title'], qa_get_block_words_preg())),
				'url' => qa_q_path_html($parentquestion['postid'], $parentquestion['title'], false,
					($question['parentid']==$parentquestion['postid']) ? 'Q' : 'A', $question['parentid']),
			);

	//	Information about the question that this question is a duplicate of (if appropriate)

		if (isset($closepost)) {

			if ($closepost['basetype']=='Q') {
				$q_view['closed']=array(
					'state' => qa_lang_html('main/closed'),
					'label' => qa_lang_html('question/closed_as_duplicate'),
					'content' => qa_html(qa_block_words_replace($closepost['title'], qa_get_block_words_preg())),
					'url' => qa_q_path_html($closepost['postid'], $closepost['title']),
				);

			} elseif ($closepost['type']=='NOTE') {
				$viewer=qa_load_viewer($closepost['content'], $closepost['format']);

				$q_view['closed']=array(
					'state' => qa_lang_html('main/closed'),
					'label' => qa_lang_html('question/closed_with_note'),
					'content' => $viewer->get_html($closepost['content'], $closepost['format'], array(
						'blockwordspreg' => qa_get_block_words_preg(),
					)),
				);
			}
		}

	//	Extra value display

		if (strlen(@$question['extra']) && qa_opt('extra_field_active') && qa_opt('extra_field_display'))
			$q_view['extra']=array(
				'label' => qa_html(qa_opt('extra_field_label')),
				'content' => qa_html(qa_block_words_replace($question['extra'], qa_get_block_words_preg())),
			);

		return $q_view;
	}

	function qa_page_q_answer_view($question, $answer, $isselected, $usershtml, $formrequested)
/*
	Returns an element to add to $qa_content['a_list']['as'] for $answer as viewed by $userid and $cookieid. Pass the
	answer's $question and whether it $isselected. $usershtml should be an array which maps userids to HTML user
	representations, including the answer's author and (if present) last editor. If a form has been explicitly requested
	for the page, set $formrequested to true - this will hide the buttons.
*/
	{
		$answerid=$answer['postid'];
		$userid=qa_get_logged_in_userid();
		$cookieid=qa_cookie_get();

		$htmloptions=qa_post_html_options($answer, null, true);
		$htmloptions['isselected']=$isselected;
		$htmloptions['avatarsize']=qa_opt('avatar_q_page_a_size');
		$htmloptions['q_request']=qa_q_request($question['postid'], $question['title']);
		$a_view=qa_post_html_fields($answer, $userid, $cookieid, $usershtml, null, $htmloptions);

		if ($answer['queued'])
			$a_view['error']=$answer['isbyuser'] ? qa_lang_html('question/a_your_waiting_approval') : qa_lang_html('question/a_waiting_your_approval');

		$a_view['main_form_tags']='method="post" action="'.qa_self_html().'"';
		$a_view['voting_form_hidden']=array('code' => qa_get_form_security_code('vote'));
		$a_view['buttons_form_hidden']=array('code' => qa_get_form_security_code('buttons-'.$answerid), 'qa_click' => '');

	//	Selection/unselect buttons and others for operating on the answer

		if (!$formrequested) { // don't show if another form is currently being shown on page
			$prefix='a'.qa_html($answerid).'_';
			$clicksuffix=' onclick="return qa_answer_click('.qa_js($answerid).', '.qa_js($question['postid']).', this);"';

			if ($question['aselectable'] && !$answer['hidden'] && !$answer['queued']) {
				if ($isselected)
					$a_view['unselect_tags']='title="'.qa_lang_html('question/unselect_popup').'" name="'.$prefix.'dounselect"'.$clicksuffix;
				else
					$a_view['select_tags']='title="'.qa_lang_html('question/select_popup').'" name="'.$prefix.'doselect"'.$clicksuffix;
			}

			$buttons=array();

			if ($answer['editbutton'])
				$buttons['edit']=array(
					'tags' => 'name="'.$prefix.'doedit"',
					'label' => qa_lang_html('question/edit_button'),
					'popup' => qa_lang_html('question/edit_a_popup'),
				);

			if ($answer['flagbutton'])
				$buttons['flag']=array(
					'tags' => 'name="'.$prefix.'doflag"'.$clicksuffix,
					'label' => qa_lang_html($answer['flagtohide'] ? 'question/flag_hide_button' : 'question/flag_button'),
					'popup' => qa_lang_html('question/flag_a_popup'),
				);

			if ($answer['unflaggable'])
				$buttons['unflag']=array(
					'tags' => 'name="'.$prefix.'dounflag"'.$clicksuffix,
					'label' => qa_lang_html('question/unflag_button'),
					'popup' => qa_lang_html('question/unflag_popup'),
				);

			if ($answer['clearflaggable'])
				$buttons['clearflags']=array(
					'tags' => 'name="'.$prefix.'doclearflags"'.$clicksuffix,
					'label' => qa_lang_html('question/clear_flags_button'),
					'popup' => qa_lang_html('question/clear_flags_popup'),
				);

			if ($answer['moderatable']) {
				$buttons['approve']=array(
					'tags' => 'name="'.$prefix.'doapprove"'.$clicksuffix,
					'label' => qa_lang_html('question/approve_button'),
					'popup' => qa_lang_html('question/approve_a_popup'),
				);

				$buttons['reject']=array(
					'tags' => 'name="'.$prefix.'doreject"'.$clicksuffix,
					'label' => qa_lang_html('question/reject_button'),
					'popup' => qa_lang_html('question/reject_a_popup'),
				);
			}

			if ($answer['hideable'])
				$buttons['hide']=array(
					'tags' => 'name="'.$prefix.'dohide"'.$clicksuffix,
					'label' => qa_lang_html('question/hide_button'),
					'popup' => qa_lang_html('question/hide_a_popup'),
				);

			if ($answer['reshowable'])
				$buttons['reshow']=array(
					'tags' => 'name="'.$prefix.'doreshow"'.$clicksuffix,
					'label' => qa_lang_html('question/reshow_button'),
					'popup' => qa_lang_html('question/reshow_a_popup'),
				);

			if ($answer['deleteable'])
				$buttons['delete']=array(
					'tags' => 'name="'.$prefix.'dodelete"'.$clicksuffix,
					'label' => qa_lang_html('question/delete_button'),
					'popup' => qa_lang_html('question/delete_a_popup'),
				);

			if ($answer['claimable'])
				$buttons['claim']=array(
					'tags' => 'name="'.$prefix.'doclaim"'.$clicksuffix,
					'label' => qa_lang_html('question/claim_button'),
					'popup' => qa_lang_html('question/claim_a_popup'),
				);

			if ($answer['followable'])
				$buttons['follow']=array(
					'tags' => 'name="'.$prefix.'dofollow"',
					'label' => qa_lang_html('question/follow_button'),
					'popup' => qa_lang_html('question/follow_a_popup'),
				);

			if ($answer['commentbutton'])
				$buttons['comment']=array(
					'tags' => 'name="'.$prefix.'docomment" onclick="return qa_toggle_element(\'c'.$answerid.'\')"',
					'label' => qa_lang_html('question/comment_button'),
					'popup' => qa_lang_html('question/comment_a_popup'),
				);

			$a_view['form']=array(
				'style' => 'light',
				'buttons' => $buttons,
			);
		}

		return $a_view;
	}

	function qa_page_q_comment_view($question, $parent, $comment, $usershtml, $formrequested)
/*
	Returns an element to add to the appropriate $qa_content[...]['c_list']['cs'] array for $comment as viewed by the
	current user. Pass the comment's $parent post and antecedent $question. $usershtml should be an array which maps
	userids to HTML user representations, including the comments's author and (if present) last editor. If a form has
	been explicitly requested for the page, set $formrequested to true - this will hide the buttons.
*/
	{
		$commentid=$comment['postid'];
		$questionid=($parent['basetype']=='Q') ? $parent['postid'] : $parent['parentid'];
		$answerid=($parent['basetype']=='Q') ? null : $parent['postid'];
		$userid=qa_get_logged_in_userid();
		$cookieid=qa_cookie_get();

		$htmloptions=qa_post_html_options($comment, null, true);
		$htmloptions['avatarsize']=qa_opt('avatar_q_page_c_size');
		$htmloptions['q_request']=qa_q_request($question['postid'], $question['title']);
		$c_view=qa_post_html_fields($comment, $userid, $cookieid, $usershtml, null, $htmloptions);

		if ($comment['queued'])
			$c_view['error']=$comment['isbyuser'] ? qa_lang_html('question/c_your_waiting_approval') : qa_lang_html('question/c_waiting_your_approval');

	//	Buttons for operating on this comment

		if (!$formrequested) { // don't show if another form is currently being shown on page
			$prefix='c'.qa_html($commentid).'_';
			$clicksuffix=' onclick="return qa_comment_click('.qa_js($commentid).', '.qa_js($questionid).', '.qa_js($parent['postid']).', this);"';

			$buttons=array();

			if ($comment['editbutton'])
				$buttons['edit']=array(
					'tags' => 'name="'.$prefix.'doedit"',
					'label' => qa_lang_html('question/edit_button'),
					'popup' => qa_lang_html('question/edit_c_popup'),
				);

			if ($comment['flagbutton'])
				$buttons['flag']=array(
					'tags' => 'name="'.$prefix.'doflag"'.$clicksuffix,
					'label' => qa_lang_html($comment['flagtohide'] ? 'question/flag_hide_button' : 'question/flag_button'),
					'popup' => qa_lang_html('question/flag_c_popup'),
				);

			if ($comment['unflaggable'])
				$buttons['unflag']=array(
					'tags' => 'name="'.$prefix.'dounflag"'.$clicksuffix,
					'label' => qa_lang_html('question/unflag_button'),
					'popup' => qa_lang_html('question/unflag_popup'),
				);

			if ($comment['clearflaggable'])
				$buttons['clearflags']=array(
					'tags' => 'name="'.$prefix.'doclearflags"'.$clicksuffix,
					'label' => qa_lang_html('question/clear_flags_button'),
					'popup' => qa_lang_html('question/clear_flags_popup'),
				);

			if ($comment['moderatable']) {
				$buttons['approve']=array(
					'tags' => 'name="'.$prefix.'doapprove"'.$clicksuffix,
					'label' => qa_lang_html('question/approve_button'),
					'popup' => qa_lang_html('question/approve_c_popup'),
				);

				$buttons['reject']=array(
					'tags' => 'name="'.$prefix.'doreject"'.$clicksuffix,
					'label' => qa_lang_html('question/reject_button'),
					'popup' => qa_lang_html('question/reject_c_popup'),
				);
			}

			if ($comment['hideable'])
				$buttons['hide']=array(
					'tags' => 'name="'.$prefix.'dohide"'.$clicksuffix,
					'label' => qa_lang_html('question/hide_button'),
					'popup' => qa_lang_html('question/hide_c_popup'),
				);

			if ($comment['reshowable'])
				$buttons['reshow']=array(
					'tags' => 'name="'.$prefix.'doreshow"'.$clicksuffix,
					'label' => qa_lang_html('question/reshow_button'),
					'popup' => qa_lang_html('question/reshow_c_popup'),
				);

			if ($comment['deleteable'])
				$buttons['delete']=array(
					'tags' => 'name="'.$prefix.'dodelete"'.$clicksuffix,
					'label' => qa_lang_html('question/delete_button'),
					'popup' => qa_lang_html('question/delete_c_popup'),
				);

			if ($comment['claimable'])
				$buttons['claim']=array(
					'tags' => 'name="'.$prefix.'doclaim"'.$clicksuffix,
					'label' => qa_lang_html('question/claim_button'),
					'popup' => qa_lang_html('question/claim_c_popup'),
				);

			if ($parent['commentbutton'] && qa_opt('show_c_reply_buttons') && ($comment['type']=='C'))
				$buttons['comment']=array(
					'tags' => 'name="'.(($parent['basetype']=='Q') ? 'q' : ('a'.qa_html($parent['postid']))).
						'_docomment" onclick="return qa_toggle_element(\'c'.qa_html($parent['postid']).'\')"',
					'label' => qa_lang_html('question/reply_button'),
					'popup' => qa_lang_html('question/reply_c_popup'),
				);

			$c_view['form']=array(
				'style' => 'light',
				'buttons' => $buttons,
			);
		}

		return $c_view;
	}

	function qa_page_q_comment_follow_list($question, $parent, $commentsfollows, $alwaysfull, $usershtml, $formrequested, $formpostid)
/*
	Return an array for $qa_content[...]['c_list'] to display all of the comments and follow-on questions in
	$commentsfollows which belong to post $parent with antecedent $question, as viewed by the current user. If
	$alwaysfull then all comments will be included, otherwise the list may be shortened with a 'show previous x
	comments' link. $usershtml should be an array which maps userids to HTML user representations, including all
	comments' and follow on questions' authors and (if present) last editors. If a form has been explicitly requested
	for the page, set $formrequested to true and pass the postid of the post for the form in $formpostid - this will
	hide the buttons and remove the $formpostid comment from the list.
*/
	{
		$parentid=$parent['postid'];
		$userid=qa_get_logged_in_userid();
		$cookieid=qa_cookie_get();

		$commentlist=array(
			'tags' => 'id="c'.qa_html($parentid).'_list"',
			'cs' => array(),
		);

		$showcomments=array();

		foreach ($commentsfollows as $commentfollowid => $commentfollow)
			if (($commentfollow['parentid']==$parentid) && $commentfollow['viewable'] && ($commentfollowid!=$formpostid) )
				$showcomments[$commentfollowid]=$commentfollow;

		$countshowcomments=count($showcomments);

		if ( (!$alwaysfull) && ($countshowcomments > qa_opt('show_fewer_cs_from')) )
			$skipfirst=$countshowcomments-qa_opt('show_fewer_cs_count');
		else
			$skipfirst=0;

		if ($skipfirst==$countshowcomments) { // showing none
			if ($skipfirst==1)
				$expandtitle=qa_lang_html('question/show_1_comment');
			else
				$expandtitle=qa_lang_html_sub('question/show_x_comments', $skipfirst);

		} else {
			if ($skipfirst==1)
				$expandtitle=qa_lang_html('question/show_1_previous_comment');
			else
				$expandtitle=qa_lang_html_sub('question/show_x_previous_comments', $skipfirst);
		}

		if ($skipfirst>0)
			$commentlist['cs'][$parentid]=array(
				'url' => qa_html('?state=showcomments-'.$parentid.'&show='.$parentid.'#'.urlencode(qa_anchor($parent['basetype'], $parentid))),

				'expand_tags' => 'onclick="return qa_show_comments('.qa_js($question['postid']).', '.qa_js($parentid).', this);"',

				'title' => $expandtitle,
			);

		foreach ($showcomments as $commentfollowid => $commentfollow)
			if ($skipfirst>0)
				$skipfirst--;

			elseif ($commentfollow['basetype']=='C') {
				$commentlist['cs'][$commentfollowid]=qa_page_q_comment_view($question, $parent, $commentfollow, $usershtml, $formrequested);

			} elseif ($commentfollow['basetype']=='Q') {
				$htmloptions=qa_post_html_options($commentfollow);
				$htmloptions['avatarsize']=qa_opt('avatar_q_page_c_size');

				$commentlist['cs'][$commentfollowid]=qa_post_html_fields($commentfollow, $userid, $cookieid, $usershtml, null, $htmloptions);
			}

		if (!count($commentlist['cs']))
			$commentlist['hidden']=true;

		return $commentlist;
	}

	function qa_page_q_add_a_form(&$qa_content, $formid, $captchareason, $question, $in, $errors, $loadnow, $formrequested)
/*
	Return a $qa_content form for adding an answer to $question. Pass an HTML element id to use for the form in $formid
	and the result of qa_user_captcha_reason() in $captchareason. Pass previous inputs from a submitted version of this
	form in the array $in and resulting errors in $errors. If $loadnow is true, the form will be loaded immediately. Set
	$formrequested to true if the user explicitly requested it, as opposed being shown automatically.
*/
	{
		// The 'approve', 'login', 'confirm', 'limit', 'userblock', 'ipblock' permission errors are reported to the user here
		// The other option ('level') prevents the answer button being shown, in qa_page_q_post_rules(...)

		switch (qa_user_post_permit_error('permit_post_a', $question, QA_LIMIT_ANSWERS)) {
			case 'login':
				$form=array(
					'title' => qa_insert_login_links(qa_lang_html('question/answer_must_login'), qa_request())
				);
				break;

			case 'confirm':
				$form=array(
					'title' => qa_insert_login_links(qa_lang_html('question/answer_must_confirm'), qa_request())
				);
				break;

			case 'approve':
				$form=array(
					'title' => qa_lang_html('question/answer_must_be_approved')
				);
				break;

			case 'limit':
				$form=array(
					'title' => qa_lang_html('question/answer_limit')
				);
				break;

			default:
				$form=array(
					'title' => qa_lang_html('users/no_permission')
				);
				break;

			case false:
				$editorname=isset($in['editor']) ? $in['editor'] : qa_opt('editor_for_as');
				$editor=qa_load_editor(@$in['content'], @$in['format'], $editorname);

				if (method_exists($editor, 'update_script'))
					$updatescript=$editor->update_script('a_content');
				else
					$updatescript='';

				$custom=qa_opt('show_custom_answer') ? trim(qa_opt('custom_answer')) : '';

				$form=array(
					'tags' => 'method="post" action="'.qa_self_html().'" name="a_form"',

					'title' => qa_lang_html('question/your_answer_title'),

					'fields' => array(
						'custom' => array(
							'type' => 'custom',
							'note' => $custom,
						),

						'content' => array_merge(
							qa_editor_load_field($editor, $qa_content, @$in['content'], @$in['format'], 'a_content', 12, $formrequested, $loadnow),
							array(
								'error' => qa_html(@$errors['content']),
							)
						),
					),

					'buttons' => array(
						'answer' => array(
							'tags' => 'onclick="'.$updatescript.' return qa_submit_answer('.qa_js($question['postid']).', this);"',
							'label' => qa_lang_html('question/add_answer_button'),
						),
					),

					'hidden' => array(
						'a_editor' => qa_html($editorname),
						'a_doadd' => '1',
						'code' => qa_get_form_security_code('answer-'.$question['postid']),
					),
				);

				if (!strlen($custom))
					unset($form['fields']['custom']);

				if ($formrequested || !$loadnow)
					$form['buttons']['cancel']=array(
						'tags' => 'name="docancel"',
						'label' => qa_lang_html('main/cancel_button'),
					);

				if (!qa_is_logged_in())
					qa_set_up_name_field($qa_content, $form['fields'], @$in['name'], 'a_');

				qa_set_up_notify_fields($qa_content, $form['fields'], 'A', qa_get_logged_in_email(),
					isset($in['notify']) ? $in['notify'] : qa_opt('notify_users_default'), @$in['email'], @$errors['email'], 'a_');

				$onloads=array();

				if ($captchareason) {
					$captchaloadscript=qa_set_up_captcha_field($qa_content, $form['fields'], $errors, qa_captcha_reason_note($captchareason));

					if (strlen($captchaloadscript))
						$onloads[]='document.getElementById('.qa_js($formid).').qa_show=function() { '.$captchaloadscript.' };';
				}

				if (!$loadnow) {
					if (method_exists($editor, 'load_script'))
						$onloads[]='document.getElementById('.qa_js($formid).').qa_load=function() { '.$editor->load_script('a_content').' };';

					$form['buttons']['cancel']['tags'].=' onclick="return qa_toggle_element();"';
				}

				if (!$formrequested) {
					if (method_exists($editor, 'focus_script'))
						$onloads[]='document.getElementById('.qa_js($formid).').qa_focus=function() { '.$editor->focus_script('a_content').' };';
				}

				if (count($onloads))
					$qa_content['script_onloads'][]=$onloads;
				break;
		}

		$form['id']=$formid;
		$form['collapse']=!$loadnow;
		$form['style']='tall';

		return $form;
	}

	function qa_page_q_add_c_form(&$qa_content, $question, $parent, $formid, $captchareason, $in, $errors, $loadfocusnow)
/*
	Returns a $qa_content form for adding a comment to post $parent which is part of $question. Pass an HTML element id
	to use for the form in $formid and the result of qa_user_captcha_reason() in $captchareason. Pass previous inputs
	from a submitted version of this form in the array $in and resulting errors in $errors. If $loadfocusnow is true,
	the form will be loaded and focused immediately.
*/
	{
		// The 'approve', 'login', 'confirm', 'userblock', 'ipblock' permission errors are reported to the user here
		// The other option ('level') prevents the comment button being shown, in qa_page_q_post_rules(...)

		switch (qa_user_post_permit_error('permit_post_c', $parent, QA_LIMIT_COMMENTS)) {
			case 'login':
				$form=array(
					'title' => qa_insert_login_links(qa_lang_html('question/comment_must_login'), qa_request())
				);
				break;

			case 'confirm':
				$form=array(
					'title' => qa_insert_login_links(qa_lang_html('question/comment_must_confirm'), qa_request())
				);
				break;

			case 'approve':
				$form=array(
					'title' => qa_lang_html('question/comment_must_be_approved')
				);
				break;

			case 'limit':
				$form=array(
					'title' => qa_lang_html('question/comment_limit')
				);
				break;

			default:
				$form=array(
					'title' => qa_lang_html('users/no_permission')
				);
				break;

			case false:
				$prefix='c'.$parent['postid'].'_';

				$editorname=isset($in['editor']) ? $in['editor'] : qa_opt('editor_for_cs');
				$editor=qa_load_editor(@$in['content'], @$in['format'], $editorname);

				if (method_exists($editor, 'update_script'))
					$updatescript=$editor->update_script($prefix.'content');
				else
					$updatescript='';

				$custom=qa_opt('show_custom_comment') ? trim(qa_opt('custom_comment')) : '';

				$form=array(
					'tags' => 'method="post" action="'.qa_self_html().'" name="c_form_'.qa_html($parent['postid']).'"',

					'title' => qa_lang_html(($question['postid']==$parent['postid']) ? 'question/your_comment_q' : 'question/your_comment_a'),

					'fields' => array(
						'custom' => array(
							'type' => 'custom',
							'note' => $custom,
						),

						'content' => array_merge(
							qa_editor_load_field($editor, $qa_content, @$in['content'], @$in['format'], $prefix.'content', 4, $loadfocusnow, $loadfocusnow),
							array(
								'error' => qa_html(@$errors['content']),
							)
						),
					),

					'buttons' => array(
						'comment' => array(
							'tags' => 'onclick="'.$updatescript.' return qa_submit_comment('.qa_js($question['postid']).', '.qa_js($parent['postid']).', this);"',
							'label' => qa_lang_html('question/add_comment_button'),
						),

						'cancel' => array(
							'tags' => 'name="docancel"',
							'label' => qa_lang_html('main/cancel_button'),
						),
					),

					'hidden' => array(
						$prefix.'editor' => qa_html($editorname),
						$prefix.'doadd' => '1',
						$prefix.'code' => qa_get_form_security_code('comment-'.$parent['postid']),
					),
				);

				if (!strlen($custom))
					unset($form['fields']['custom']);

				if (!qa_is_logged_in())
					qa_set_up_name_field($qa_content, $form['fields'], @$in['name'], $prefix);

				qa_set_up_notify_fields($qa_content, $form['fields'], 'C', qa_get_logged_in_email(),
					isset($in['notify']) ? $in['notify'] : qa_opt('notify_users_default'), $in['email'], @$errors['email'], $prefix);

				$onloads=array();

				if ($captchareason) {
					$captchaloadscript=qa_set_up_captcha_field($qa_content, $form['fields'], $errors, qa_captcha_reason_note($captchareason));

					if (strlen($captchaloadscript))
						$onloads[]='document.getElementById('.qa_js($formid).').qa_show=function() { '.$captchaloadscript.' };';
				}

				if (!$loadfocusnow) {
					if (method_exists($editor, 'load_script'))
						$onloads[]='document.getElementById('.qa_js($formid).').qa_load=function() { '.$editor->load_script($prefix.'content').' };';
					if (method_exists($editor, 'focus_script'))
						$onloads[]='document.getElementById('.qa_js($formid).').qa_focus=function() { '.$editor->focus_script($prefix.'content').' };';

					$form['buttons']['cancel']['tags'].=' onclick="return qa_toggle_element()"';
				}

				if (count($onloads))
					$qa_content['script_onloads'][]=$onloads;
		}

		$form['id']=$formid;
		$form['collapse']=!$loadfocusnow;
		$form['style']='tall';

		return $form;
	}

/*
	Omit PHP closing tag to help avoid accidental output
*/


text:
import {assert} from "chai";
import {validate, type, count} from "../../main/index";

export default function() {
    describe("Model with a count 2 - 5 property", () => {
        class CountModel {
            @type("any")
            @count(2, 5)
            value: any;
        }

        it("should NOT validate with an array with count of 1", () => {
            let model = new CountModel();
            model.value = ["S"];
            validate(model).then(error => assert.isNull(error)).catch(() => {});
        });

        it("should validate with an array with count of 2", () => {
            let model = new CountModel();
            model.value = ["S", "T"];
            validate(model).then(error => assert.isNull(error)).catch(() => {});
        });

        it("should validate with an array with count of 5", () => {
            let model = new CountModel();
            model.value = ["S", "T", "R", "I", "N"];
            validate(model).then(error => assert.isNull(error)).catch(() => {});
        });

        it("should NOT validate with an array with count of 6", () => {
            let model = new CountModel();
            model.value = ["S", "T", "R", "I", "N", "G"];
            validate(model).then(error => assert.isNotNull(error)).catch(() => {});
        });

        it("should validate with a set with count of 5", () => {
            let model = new CountModel();
            model.value = new Set(["S", "T", "R", "I", "N"]);
            validate(model).then(error => assert.isNull(error)).catch(() => {});
        });

        it("should NOT validate with a set with count of 6", () => {
            let model = new CountModel();
            model.value = new Set(["S", "T", "R", "I", "N", "G"]);
            validate(model).then(error => assert.isNotNull(error)).catch(() => {});
        });

        it("should validate with a map with count of 5", () => {
            let model = new CountModel();

            model.value = new Map([
                ["S", "S"],
                ["T", "T"],
                ["R", "R"],
                ["I", "I"],
                ["N", "N"]
            ]);

            validate(model).then(error => assert.isNull(error)).catch(() => {});
        });

        it("should NOT validate with a map with count of 6", () => {
            let model = new CountModel();

            model.value = new Map([
                ["S", "S"],
                ["T", "T"],
                ["R", "R"],
                ["I", "I"],
                ["N", "N"],
                ["G", "G"]
            ]);

            validate(model).then(error => assert.isNotNull(error)).catch(() => {});
        });
    });
}


text:
run /usr/local/paracoder/startup.m
run /usr/local/ilupack4m/startup.m
run /usr/local/petsc4m/startup.m
run ~/project/numgeom2/ahf-plus/matlab/startup.m


text:
- CoreGraphics
- SystemConfiguration
- StoreKit

//2. Import the ABFramework.h header into your project

//3. Your all set ;)


text:
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using UnityEngine;

/// <summary>
///
/// 地图配置管理
///
/// 1、加载地图配置
/// 2、存储地图配置
/// 3、删除地图配置
///
/// </summary>
namespace Game.MapControlSpace
{

    [XmlRoot("MapManager")]
    [Serializable]
    public class MapXMLManager
    {
        /// <summary>
        /// 空间界限
        /// </summary>
        [XmlElement]
        public SpaceConfine _spaceConfine;
        /// <summary>
        /// 空间对象列表
        /// </summary>
        [XmlArrayItem]
        public List<SpaceObj> _spaceObjList;

        public void ParseXML(string xmlString)
        {
            if (xmlString == null || string.IsNullOrEmpty(xmlString))
            {
                Debug.LogError("MapXMLManager.ParseXML() xml内容是空的!");
                TLogger.Log("xml内容是空的!", "MapXMLManager", "ParseXML");
                return;
            }

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xmlString);

            XmlNode spaceConfine = doc.SelectSingleNode("/MapManager/SpaceConfine");
            if (spaceConfine != null)
            {
                _spaceConfine = new SpaceConfine();
                _spaceConfine.ParseXML(spaceConfine);
            }
            else
            {
                Debug.LogError("MapXMLManager.ParseXML() spaceConfine节点不存在!");
                TLogger.Log("spaceConfine节点不存在!", "MapXMLManager", "ParseXML");
            }

            XmlNode SpaceObjList = doc.SelectSingleNode("/MapManager/SpaceObjList");
            if (SpaceObjList != null)
            {
                _spaceObjList = new List<SpaceObj>();
                for (int i = 0; i < SpaceObjList.ChildNodes.Count; i++)
                {
                    SpaceObj obj = new SpaceObj();
                    obj.ParseXML(SpaceObjList.ChildNodes[i]);
                    _spaceObjList.Add(obj);
                }
            }

        }

    }
}


text:
import React, { useState } from 'react';
import { AmazonCluster, Project } from '../domain';
import { CreateClusterAction } from './actions';
import { AWSInstanceChoiceOption, AWSRegionList } from './domain';
import { ApiFactory } from '../api';
import { ClusterViewHeader } from './ClusterViewHeader';
import { useNotifications } from '../app-notifications';
import { AWSForm } from '../AWSForm';
import { FormikActionsHandler } from '../JMeterConfiguration/domain';

export function NewAWSCluster({ dispatch, activeProject }: {
  dispatch: React.Dispatch<any>;
  activeProject: Project;
}) {
  const [awsRegion, setAwsRegion] = useState<string>();
  const [selectedInstanceType, setSelectedInstanceType] = useState<AWSInstanceChoiceOption>();
  const [baseAMI, setBaseAMI] = useState<string>();
  const {notifySuccess, notifyError} = useNotifications();
  const fetchRegions: () => Promise<AWSRegionList> = () => {
    return ApiFactory().awsRegion().list();
  };

  const handleSubmit: FormikActionsHandler = (values, actions) => {
    actions.setSubmitting(true);
    ApiFactory()
      .clusters()
      .create(activeProject.id, {
        ...values as AmazonCluster,
        type: 'AWS',
        title: '',
        region: awsRegion!,
        instanceType: selectedInstanceType!.instanceType,
        maxThreadsByInstance: selectedInstanceType!.maxThreadsByInstance,
        baseAMI: baseAMI
      })
      .then((createdCluster) => {
        dispatch(new CreateClusterAction(createdCluster));
        notifySuccess(`Saved ${createdCluster.title} cluster configuration`);
      })
      .catch((reason) => notifyError(`Failed to save the AWS ${awsRegion} cluster configuration`, reason))
      .finally(() => actions.setSubmitting(false));
  };

  const onAWSRegionChange: (
    region: string,
    options?: {
      baseAMI?: string;
    }
  ) => void = (region, options) => {
    setAwsRegion(region);
    if (options) {
      setBaseAMI(options.baseAMI);
    }
  };

  return (

      <ClusterViewHeader
        title="Create a new AWS Cluster"
        icon={()}
      />
      <AWSForm {...{
        awsRegion,
        dispatch,
        handleSubmit,
        setSelectedInstanceType,
        fetchRegions,
        onAWSRegionChange
      }}/>

  );
}


text:
using System;

namespace Microsoft.Azure.Commands.Sql.ElasticPool.Model
{
    /// <summary>
    /// Represents an Azure Sql Database
    /// </summary>
    public class AzureSqlElasticPoolActivityModel
    {
        /// <summary>
        /// Gets or sets the operation id
        /// </summary>
        public Guid OperationId { get; set; }

        /// <summary>
        /// Gets or sets the server name
        /// </summary>
        public string ServerName { get; set; }

        /// <summary>
        /// Gets or sets the resource pool name
        /// </summary>
        public string ElasticPoolName { get; set; }

        /// <summary>
        /// Gets or sets the name of the resource group
        /// </summary>
        public string ResourceGroupName { get; set; }

        /// <summary>
        /// Gets or sets the state
        /// </summary>
        public string State { get; set; }

        /// <summary>
        /// Gets or sets operation
        /// </summary>
        public string Operation { get; set; }

        /// <summary>
        /// Gets or sets the error code
        /// </summary>
        public int? ErrorCode { get; set; }

        /// <summary>
        /// Gets or sets the error message
        /// </summary>
        public string ErrorMessage { get; set; }

        /// <summary>
        /// Gets or sets the error severity
        /// </summary>
        public int? ErrorSeverity { get; set; }

        /// <summary>
        /// Gets or sets the start time
        /// </summary>
        public DateTime? StartTime { get; set; }

        /// <summary>
        /// Gets or sets the end time
        /// </summary>
        public DateTime? EndTime { get; set; }

        /// <summary>
        /// Gets or sets the percent complete
        /// </summary>
        public int? PercentComplete { get; set; }

        /// <summary>
        /// Gets or sets the requested resource pool name
        /// </summary>
        public string RequestedElasticPoolName { get; set; }

        /// <summary>
        /// Gets or sets the requested DTU
        /// </summary>
        public int? RequestedDtu { get; set; }

        /// <summary>
        /// Gets or sets the requested DTU max
        /// </summary>
        public int? RequestedDatabaseDtuMax { get; set; }

        /// <summary>
        /// Gets or sets the requested DTU min
        /// </summary>
        public int? RequestedDatabaseDtuMin { get; set; }

        /// <summary>
        /// Gets or sets the requested storage limit in GB
        /// </summary>
        public long? RequestedStorageLimitInGB { get; set; }

        /// <summary>
        /// Gets or sets the estimated completion time of the elastic pool operation
        /// </summary>
        public DateTime? EstimatedCompletionTime { get; set; }

        /// <summary>
        /// Gets or sets the description of the elastic pool operation
        /// </summary>
        public string Description { get; set; }

        /// <summary>
        /// Gets or sets the value to indicate if the elastic pool operation can be cancelled
        /// </summary>
        public bool? IsCancellable { get; set; }
    }
}


text:
from __future__ import print_function
import sched
import argparse
import bisect
import itertools
import logging
import random
import re
import string
import sys
import platform
import time

from math import sqrt
from threading import currentThread, Thread
from time import time

try:
    from httplib import HTTPConnection
except ImportError:
    from http.client import HTTPConnection

try:
    from urllib import urlencode
except ImportError:
    from urllib.parse import urlencode

__program__ = 'pyspeedtest'
__version__ = '1.2.7'
__description__ = 'Test your bandwidth speed using Speedtest.net servers.'

__supported_formats__ = ('default', 'json', 'xml')

class SpeedTest(object):

    USER_AGENTS = {
        'Linux': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:41.0) Gecko/20100101 Firefox/41.0',
        'Darwin': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:41.0) Gecko/20100101 Firefox/41.0',
        'Windows': 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0',
        'Java': 'Java/1.6.0_12',
    }

    DOWNLOAD_FILES = [
        '/speedtest/random350x350.jpg',
        '/speedtest/random500x500.jpg',
        '/speedtest/random1500x1500.jpg'
    ]

    UPLOAD_FILES = [
        132884,
        493638
    ]

    ALPHABET = string.digits + string.ascii_letters

    def __init__(self, host=None, http_debug=0, runs=2):
        self._host = host
        self.http_debug = http_debug
        self.runs = runs

    @property
    def host(self):
        if not self._host:
            self._host = self.chooseserver()
        return self._host

    @host.setter
    def host(self, new_host):
        self._host = new_host

    def connect(self, url):
        try:
            connection = HTTPConnection(url)
            connection.set_debuglevel(self.http_debug)
            connection.connect()
            return connection
        except:
            raise Exception('Unable to connect to %r' % url)

    def downloadthread(self, connection, url):
        connection.request('GET', url, None, {'Connection': 'Keep-Alive'})
        response = connection.getresponse()
        self_thread = currentThread()
        self_thread.downloaded = len(response.read())

    def download(self):
        total_downloaded = 0
        connections = [
            self.connect(self.host) for i in range(self.runs)
        ]
        total_start_time = time()
        for current_file in SpeedTest.DOWNLOAD_FILES:
            threads = []
            for run in range(self.runs):
                thread = Thread(
                    target=self.downloadthread,
                    args=(connections[run],
                          '%s?x=%d' % (current_file, int(time() * 1000))))
                thread.run_number = run + 1
                thread.start()
                threads.append(thread)
            for thread in threads:
                thread.join()
                total_downloaded += thread.downloaded
                LOG.debug('Run %d for %s finished',
                          thread.run_number, current_file)
        total_ms = (time() - total_start_time) * 1000
        for connection in connections:
            connection.close()
        LOG.info('Took %d ms to download %d bytes',
                 total_ms, total_downloaded)
        return total_downloaded * 8000 / total_ms

    def uploadthread(self, connection, data):
        url = '/speedtest/upload.php?x=%d' % randint()
        connection.request('POST', url, data, {
            'Connection': 'Keep-Alive',
            'Content-Type': 'application/x-www-form-urlencoded'
        })
        response = connection.getresponse()
        reply = response.read().decode('utf-8')
        self_thread = currentThread()
        self_thread.uploaded = int(reply.split('=')[1])

    def upload(self):
        connections = [
            self.connect(self.host) for i in range(self.runs)
        ]

        post_data = [
            urlencode({'content0': content(s)}) for s in SpeedTest.UPLOAD_FILES
        ]

        total_uploaded = 0
        total_start_time = time()
        for data in post_data:
            threads = []
            for run in range(self.runs):
                thread = Thread(target=self.uploadthread,
                                args=(connections[run], data))
                thread.run_number = run + 1
                thread.start()
                threads.append(thread)
            for thread in threads:
                thread.join()
                LOG.debug('Run %d for %d bytes finished',
                          thread.run_number, thread.uploaded)
                total_uploaded += thread.uploaded
        total_ms = (time() - total_start_time) * 1000
        for connection in connections:
            connection.close()
        LOG.info('Took %d ms to upload %d bytes',
                 total_ms, total_uploaded)
        return total_uploaded * 8000 / total_ms

    def ping(self, server=None):
        if not server:
            server = self.host

        connection = self.connect(server)
        times = []
        worst = 0
        for _ in range(5):
            total_start_time = time()
            connection.request(
                'GET',
                '/speedtest/latency.txt?x=%d' % randint(),
                None,
                {'Connection': 'Keep-Alive'})
            response = connection.getresponse()
            response.read()
            total_ms = time() - total_start_time
            times.append(total_ms)
            if total_ms > worst:
                worst = total_ms
        times.remove(worst)
        total_ms = sum(times) * 250  # * 1000 / number of tries (4) = 250
        connection.close()
        LOG.debug('Latency for %s - %d', server, total_ms)
        return total_ms

    def chooseserver(self):
        connection = self.connect('www.speedtest.net')
        now = int(time() * 1000)
        # really contribute to speedtest.net OS statistics
        # maybe they won't block us again...
        extra_headers = {
            'Connection': 'Keep-Alive',
            'User-Agent': self.USER_AGENTS.get(platform.system(), self.USER_AGENTS['Linux'])
        }
        connection.request(
            'GET', '/speedtest-config.php?x=%d' % now, None, extra_headers)
        response = connection.getresponse()
        reply = response.read().decode('utf-8')
        match = re.search(
            r'<client ip="([^"]*)" lat="([^"]*)" lon="([^"]*)"', reply)
        location = None
        if match is None:
            LOG.info('Failed to retrieve coordinates')
            return None
        location = match.groups()
        LOG.info('Your IP: %s', location[0])
        LOG.info('Your latitude: %s', location[1])
        LOG.info('Your longitude: %s', location[2])
        connection.request(
            'GET', '/speedtest-servers.php?x=%d' % now, None, extra_headers)
        response = connection.getresponse()
        reply = response.read().decode('utf-8')
        server_list = re.findall(
            r'<server url="([^"]*)" lat="([^"]*)" lon="([^"]*)"', reply)
        my_lat = float(location[1])
        my_lon = float(location[2])
        sorted_server_list = []
        for server in server_list:
            s_lat = float(server[1])
            s_lon = float(server[2])
            distance = sqrt(pow(s_lat - my_lat, 2) + pow(s_lon - my_lon, 2))
            bisect.insort_left(sorted_server_list, (distance, server[0]))
        best_server = (999999, '')
        for server in sorted_server_list[:10]:
            LOG.debug(server[1])
            match = re.search(
                r'http://([^/]+)/speedtest/upload\.php', server[1])
            if match is None:
                continue
            server_host = match.groups()[0]
            latency = self.ping(server_host)
            if latency < best_server[0]:
                best_server = (latency, server_host)
        if not best_server[1]:
            raise Exception('Cannot find a test server')
        LOG.debug('Best server: %s', best_server[1])
        return best_server[1]

def content(length):
    """Return alphanumeric string of indicated length."""
    cycle = itertools.cycle(SpeedTest.ALPHABET)
    return ''.join(next(cycle) for i in range(length))

def init_logging(loglevel=logging.WARNING):
    """Initialize program logger."""

    scriptlogger = logging.getLogger(__program__)

    # ensure logger is not reconfigured
    # it would be nice to use hasHandlers here, but that's Python 3 only
    if not scriptlogger.handlers:

        # set log level
        scriptlogger.setLevel(loglevel)

        # log message format
        fmt = '%(name)s:%(levelname)s: %(message)s'

        # configure terminal log
        streamhandler = logging.StreamHandler()
        streamhandler.setFormatter(logging.Formatter(fmt))
        scriptlogger.addHandler(streamhandler)

def parseargs(args):

    class SmartFormatter(argparse.HelpFormatter):

        def _split_lines(self, text, width):
            """argparse.RawTextHelpFormatter._split_lines"""
            if text.startswith('r|'):
                return text[2:].splitlines()
            return argparse.HelpFormatter._split_lines(self, text, width)

    def positive_int(value):
        try:
            ivalue = int(value)
            if ivalue < 0:
                raise ValueError
            return ivalue
        except ValueError:
            raise argparse.ArgumentTypeError(
                'invalid positive int value: %r' % value)

    def format_enum(value):
        if value.lower() not in __supported_formats__:
            raise argparse.ArgumentTypeError(
                'output format not supported: %r' % value)
        return value

    parser = argparse.ArgumentParser(
        add_help=False,
        description=__description__,
        formatter_class=SmartFormatter,
        usage='%(prog)s [OPTION]...')
    parser.add_argument(
        '-d', '--debug',
        default=0,
        help='set http connection debug level (default is 0)',
        metavar='L',
        type=positive_int)
    parser.add_argument(
        '-h', '--help',
        action='help',
        help=argparse.SUPPRESS)
    parser.add_argument(
        '-m', '--mode',
        choices=range(1, 8),
        default=7,
        help='''r|test mode: 1 - download
           2 - upload
           4 - ping
           1 + 2 + 4 = 7 - all (default)''',
        metavar='M',
        type=int)
    parser.add_argument(
        '-r', '--runs',
        default=2,
        help='use N runs (default is 2)',
        metavar='N',
        type=positive_int)
    parser.add_argument(
        '-s', '--server',
        help='use specific server',
        metavar='H')
    parser.add_argument(
        '-f', '--format',
        default='default',
        help='output format ' + str(__supported_formats__),
        metavar='F',
        type=format_enum)
    parser.add_argument(
        '-v', '--verbose',
        action='store_true',
        dest='verbose',
        help='output additional information')
    parser.add_argument(
        '--version',
        action='version',
        version='%(prog)s ' + __version__)

    return parser.parse_args(args)

def perform_speedtest(opts):
    speedtest = SpeedTest(opts.server, opts.debug, opts.runs)

    if opts.format in __supported_formats__:

        if opts.format == 'default':

            print('Using server: %s' % speedtest.host)

            if opts.mode & 4 == 4:
                print('Ping: %d ms' % speedtest.ping())

            if opts.mode & 1 == 1:
                print('Download speed: %s' % pretty_speed(speedtest.download()))

            if opts.mode & 2 == 2:
                print('Upload speed: %s' % pretty_speed(speedtest.upload()))

        else:
            stats = dict(server=speedtest.host)
            if opts.mode & 4 == 4:
                stats['ping'] = speedtest.ping()
            if opts.mode & 1 == 1:
                stats['download'] = speedtest.download()
            if opts.mode & 2 == 2:
                stats['upload'] = speedtest.upload()
            if opts.format == 'json':
                from json import dumps
                print(dumps(stats))
            elif opts.format == 'xml':
                from xml.etree.ElementTree import Element, tostring
                xml = Element('data')
                for key, val in stats.items():
                    child = Element(key)
                    child.text = str(val)
                    xml.append(child)
                print(tostring(xml).decode('utf-8'))

    else:
        raise Exception('Output format not supported: %s' % opts.format)

def main(args=None):
    opts = parseargs(args)
    init_logging(logging.DEBUG if opts.verbose else logging.WARNING)
    try:
        perform_speedtest(opts)
    except Exception as e:
        if opts.verbose:
            LOG.exception(e)
        else:
            LOG.error(e)
        sys.exit(1)

def pretty_speed(speed):
    units = ['bit/s', 'Kbit/s', 'Mbit/s', 'Gbit/s']
    unit = 0
    while speed >= 1024:
        speed /= 1024
        unit += 1
    return '%0.2f %s' % (speed, units[unit])

def randint():
    """Return a random 12 digit integer."""
    return random.randint(100000000000, 999999999999)

LOG = logging.getLogger(__program__)

if __name__ == '__main__':
    main()


text:
package com.gplucky.user.config;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * Created by ehsy_it on 2017/2/13.
 */
@WebFilter(urlPatterns = "/*", filterName = "simpleCORSFilter")
public class SimpleCORSFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        /*HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");*/
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}


text:
package com.sonova.difian.communication.fittingconnection;

public enum FittingConnectionError
{
    NONE, NETWORK_OPEN_FAILED, NETWORK_READ_FAILED, NETWORK_WRITE_FAILED, SERIAL_OPEN_FAILED, SERIAL_READ_FAILED,
    SERIAL_WRITE_FAILED
}


text:
package game

import (
	"errors"
	"fmt"
	"sort"

	log "github.com/Sirupsen/logrus"
	"github.com/gocaine/go-dart/common"
)

// Gamex01 is a x01 series Game (301, 501-Double-Out, ...)
type Gamex01 struct {
	BaseGame
	score     int
	doubleOut bool
	accu      int
}

// Optionx01 is the struct to handle Gamex01 parameters
type Optionx01 struct {
	Score     int
	DoubleOut bool
}

// NewGamex01 : Gamex01 constructor
func NewGamex01(opts map[string]interface{}) (g *Gamex01, err error) {
	opt, err := newOptionx01(opts)
	if err != nil {
		return
	}
	if opt.Score < 61 {
		err = errors.New("Score should be at least 61")
		return
	}
	g = new(Gamex01)
	g.doubleOut = opt.DoubleOut
	g.score = opt.Score
	g.state = common.NewGameState()

	dStyle := ""
	if opt.DoubleOut {
		dStyle = " Double-Out"
	}
	g.DisplayStyle = fmt.Sprintf("%d%s", opt.Score, dStyle)

	return
}

// Start start the game, Darts will be handled
func (game *Gamex01) Start() (error error) {
	if game.state.Ongoing == common.READY && len(game.state.Players) > 0 && game.score > 0 {
		state := game.state
		state.Ongoing = common.PLAYING
		state.CurrentPlayer = 0
		state.CurrentDart = 0
		for i := range state.Players {
			state.Players[i].Score = game.score
		}
		log.Infof("The game is now started")
	} else {
		error = errors.New("Game cannot start")
	}
	return
}

// HandleDart the implementation has to handle the Dart regarding the current player, the rules of x01, and the context. Return a GameState
func (game *Gamex01) HandleDart(sector common.Sector) (result *common.GameState, error error) {

	error = commonHandleDartChecks(game, sector)
	if error != nil {
		return
	}

	point := sector.Val * sector.Pos
	game.accu += point
	state := game.state

	state.LastSector = sector

	log.WithFields(log.Fields{"player": state.CurrentPlayer, "score": point}).Info("Scored")

	state.Players[state.CurrentPlayer].Score -= point

	log.Info("Current dart ", game.state.CurrentDart)
	state.Players[state.CurrentPlayer].Visits = append(state.Players[state.CurrentPlayer].Visits, sector)

	if state.Players[state.CurrentPlayer].Score > 0 {
		if game.doubleOut && state.Players[state.CurrentPlayer].Score == 1 {
			state.LastMsg = "You should end with a double"
			game.resetVisit()
			game.HoldOrNextPlayer()
		} else {
			game.nextDart()
		}

	} else if state.Players[state.CurrentPlayer].Score == 0 {
		if game.doubleOut && sector.Pos != 2 {
			state.LastMsg = "You should end with a double"
			game.resetVisit()
			game.HoldOrNextPlayer()
		} else {
			game.winner()
			if game.state.Ongoing == common.PLAYING {
				game.HoldOrNextPlayer()
			}
		}

	} else {
		state.LastMsg = "You went beyond the target dude !"
		game.resetVisit()
		game.HoldOrNextPlayer()
	}
	result = state
	return
}

func (game *Gamex01) winner() {
	state := game.state
	state.Players[state.CurrentPlayer].Rank = game.rank + 1
	state.LastMsg = fmt.Sprintf("Player %d end at rank #%d", state.CurrentPlayer, game.rank+1)
	game.rank++
	if game.rank >= len(state.Players)-1 {
		game.state.Ongoing = common.OVER
		sort.Sort(common.ByRank(state.Players))
		if len(state.Players) > 1 {
			state.Players[len(state.Players)-1].Rank = game.rank + 1
		}
	}
}

// HoldOrNextPlayer switch game state between ONHOLD and PLAYING
func (game *Gamex01) HoldOrNextPlayer() {
	commonHoldOrNextPlayer(game)
}

// AddPlayer add a new player to the game
func (game *Gamex01) AddPlayer(board string, name string) error {
	return commonAddPlayer(game, board, name)
}

func (game *Gamex01) nextPlayer() {

	game.accu = 0
	state := game.State()

	// reset visits
	state.Players[state.CurrentPlayer].Visits = make([]common.Sector, 0, 3)

	state.CurrentDart = 0
	state.CurrentPlayer = (state.CurrentPlayer + 1) % len(state.Players)
	for state.Players[state.CurrentPlayer].Score == 0 {
		state.CurrentPlayer = (state.CurrentPlayer + 1) % len(state.Players)
	}
	log.WithFields(log.Fields{"player": state.CurrentPlayer}).Info("Next player")
}

func (game *Gamex01) nextDart() {
	state := game.state
	if state.CurrentDart == 2 {
		game.HoldOrNextPlayer()
	} else {
		state.CurrentDart++
		log.WithFields(log.Fields{"player": state.CurrentPlayer, "dart": state.CurrentDart}).Info("One more dart")
	}
}

func (game *Gamex01) resetVisit() {
	state := game.state
	state.Players[state.CurrentPlayer].Score += game.accu
}

var gsX01Options = []common.GameOption{
	{"Score", "int", "The score from which to reach 0", 501},
	{"DoubleOut", "bool", "If set to true, the players have to end with a double (and so reach 0)", false}}

// GsX01 GameStyle for X01 series
var GsX01 = common.GameStyle{
	"X01 : 301, 501,...",
	"X01",
	"All players start with the same points (301 / 501 / ...) and attempt to reach zero. " +
		"If a player scores more than the total required to reach zero, " +
		"the player \"busts\" and the score returns to the score that was existing at the start of the turn.",
	gsX01Options}

func newOptionx01(opts map[string]interface{}) (o Optionx01, err error) {
	o = Optionx01{}
	err = gameOptionFiller(&o, gsX01Options, opts)

	return
}


text:
param
(
	[Parameter()]
	[Hashtable] $settings = @{}
)

Set-StrictMode -version Latest

$latestBuild = 'https://github.com/downloads/EastPoint/PerfTap/PerfTap-0.1.1.zip'

function Test-IsAdmin
{
	$identity = [Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()
    If (-NOT $identity.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
    {
		throw 'You are not currently running this installation under an Administrator account.  Installation aborted!'
	}
}

function Merge-Parameters()
{
	param
	(
		[Parameter(Mandatory=$true)]
		[Hashtable] $Hash
	)

	$defaults =
	@{
		Key = '';
		Port = 8125;
		SampleInterval = '00:00:05';
		DefinitionPaths = @('CounterDefinitions\system.counters');
		CounterNames = @()
	}

	$allowedKeys = ($defaults | Select -ExpandProperty Keys) + @('HostName','Format')
	$Hash | Select -ExpandProperty Keys |
	% {
		if (-not $allowedKeys -contains $_)
		{
			$msg = "Parameter $_ not expected"
			Write-Error -Message $msg -Category InvalidArgument
			throw $msg
		}
		$defaults.$_ = $Hash.$_
	}

	$defaults
}

function Extract-Zip()
{
    Write-Host "Downloading Latest Package from $latestBuild"
	$path = "${Env:Temp}\perftap.zip"
    (New-Object Net.WebClient).DownloadFile($latestBuild, $path)
	$shellApplication = New-Object -com Shell.Application
	$zipItems = $shellApplication.NameSpace($path).Items()
	$extracted = "${Env:ProgramFiles}\PerfTap"
	if (!(test-path $extracted)) { [Void](New-Item $extracted -type directory) }
	$shellApplication.NameSpace($extracted).CopyHere($zipItems, 0x14)
	Remove-Item $path
}

function Run-ServiceInstaller()
{
	Set-Alias installutil $Env:windir\Microsoft.NET\Framework\v4.0.30319\installutil.exe
	$servicePath = "${Env:ProgramFiles}\PerfTap\PerfTap.WindowsServiceHost.exe"
	if ((Get-Service PerfTap -ErrorAction SilentlyContinue) -ne $null)
	{
		installutil /u """$servicePath"""
	}

	installutil """$servicePath"""
}

function Modify-ConfigFile()
{
	param
	(
	    [Parameter(Mandatory=$true)]
		[AllowEmptyCollection()]
	    [string[]]
	    $CounterNames,

	    [parameter(Mandatory=$true)]
	    [string[]]
	    $DefinitionPaths,

	    [parameter(Mandatory=$true)]
	    [string]
	    $HostName,

	    [parameter(Mandatory=$false)]
	    [int]
	    $Port = 8125,

	    [parameter(Mandatory=$false)]
	    [TimeSpan]
	    [ValidateRange('00:00:01', '00:05:00')] # 1s -> 5m
	    $SampleInterval = [TimeSpan]::FromSeconds(5),

	    [parameter(Mandatory=$false)]
	    [string]
	    [ValidatePattern('^[^!\s;:/\.\(\)\\#%\$\^]+$|^$')]
	    $Key = '',

		[ValidateSet("StatsD","StatSite")]
		[string]
		$Format
	)

	$path = "${Env:ProgramFiles}\PerfTap\PerfTap.WindowsServiceHost.exe.config"
	$xml = New-Object Xml
	$xml.Load($path)

	$xml.configuration.perfTapCounterSampling.SetAttribute('sampleInterval', $SampleInterval)

	$definitionFilePathsNode = $xml.SelectSingleNode('//definitionFilePaths')
	if ($xml.SelectSingleNode('//definitionFilePaths') -ne $null)
	{
		$definitionFilePathsNode.RemoveAll()
	}
	else
	{
		$definitionFilePathsNode = $xml.CreateElement('definitionFilePaths')
		[Void]$xml.configuration.perfTapCounterSampling.AppendChild($definitionFilePathsNode)
	}

	$DefinitionPaths | % {
			$filePath = $xml.CreateElement('definitionFile')
			$filePath.SetAttribute('path', $_)
			[Void]$definitionFilePathsNode.AppendChild($filePath)
		}

	$counterNamesNode = $xml.SelectSingleNode('//counterNames')
	if ($counterNamesNode -ne $null)
	{
		$counterNamesNode.RemoveAll()
	}
	else
	{
		$counterNamesNode = $xml.CreateElement('counterNames')
		[Void]$xml.configuration.perfTapCounterSampling.AppendChild($counterNamesNode)
	}

	$CounterNames | % {
			$name = $xml.CreateElement('counter')
			$name.SetAttribute('name', $_)
			[Void]$counterNamesNode.AppendChild($name)
		}

	$xml.configuration.perfTapPublishing.SetAttribute("prefixKey",$Key)
	$xml.configuration.perfTapPublishing.SetAttribute("port",$Port)
	$xml.configuration.perfTapPublishing.SetAttribute("hostName",$HostName)
	$xml.configuration.perfTapPublishing.SetAttribute("format",$Format)

	$xml.Save($path)
}

function Install-Service()
{
	[CmdletBinding()]
	param
	(
	    [parameter(Mandatory=$true)]
		[AllowEmptyCollection()]
	    [string[]]
	    $CounterNames,

	    [parameter(Mandatory=$true)]
	    [string[]]
	    $DefinitionPaths,

	    [parameter(Mandatory=$true)]
	    [string]
	    $HostName,

	    [parameter(Mandatory=$false)]
	    [int]
	    $Port = 8125,

	    [parameter(Mandatory=$false)]
	    [TimeSpan]
	    [ValidateRange("00:00:01", "00:05:00")] # 1s -> 5m
	    $SampleInterval = [TimeSpan]::FromSeconds(5),

	    [parameter(Mandatory=$false)]
	    [string]
	    [ValidatePattern('^[^!\s;:/\.\(\)\\#%\$\^]+$|^$')]
	    $Key = '',

		[ValidateSet("StatsD","StatSite")]
		[string]
		$Format
	)

    $executionPolicy  = (Get-ExecutionPolicy)
    $executionRestricted = ($executionPolicy -eq "Restricted")
    if ($executionRestricted){
        Write-Warning @"
Your execution policy is $executionPolicy, this means you will not be able import or use any scripts including modules.
To fix this change you execution policy to something like RemoteSigned.

        PS> Set-ExecutionPolicy RemoteSigned

For more information execute:

        PS> Get-Help about_execution_policies

"@
    }
	else
	{
		if ((Get-Service PerfTap -ErrorAction SilentlyContinue) -ne $null)
		{
			Stop-Service PerfTap
		}
		Extract-Zip
		Run-ServiceInstaller
		Modify-ConfigFile -Key $Key -Port $Port -SampleInterval $SampleInterval -HostName $HostName `
			-CounterNames $CounterNames -DefinitionPaths $DefinitionPaths
		Start-Service PerfTap
	}
}

Test-IsAdmin
$mergedSettings = Merge-Parameters -Hash $settings
Install-Service @mergedSettings