text:
package net.roboconf.core.errors;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import net.roboconf.core.Constants;
import net.roboconf.core.dsl.ParsingConstants;

/**
 * All the error codes that can be encountered with a Roboconf model.
 * @author Vincent Zurczak - Linagora
 */
public enum ErrorCode {

	// Parsing Errors
	P_IO_ERROR( ErrorLevel.SEVERE, ErrorCategory.PARSING ),
	P_ONE_BLOCK_PER_LINE( ErrorLevel.SEVERE, ErrorCategory.PARSING ),
	P_PROPERTY_ENDS_WITH_SEMI_COLON( ErrorLevel.SEVERE, ErrorCategory.PARSING ),
	P_IMPORT_ENDS_WITH_SEMI_COLON( ErrorLevel.SEVERE, ErrorCategory.PARSING ),
	P_O_C_BRACKET_EXTRA_CHARACTERS( ErrorLevel.SEVERE, ErrorCategory.PARSING ),
	P_C_C_BRACKET_EXTRA_CHARACTERS( ErrorLevel.SEVERE, ErrorCategory.PARSING ),
	P_O_C_BRACKET_MISSING( ErrorLevel.SEVERE, ErrorCategory.PARSING ),
	P_C_C_BRACKET_MISSING( ErrorLevel.SEVERE, ErrorCategory.PARSING ),
	P_UNRECOGNIZED_BLOCK( ErrorLevel.SEVERE, ErrorCategory.PARSING ),
	P_INVALID_PROPERTY( ErrorLevel.SEVERE, ErrorCategory.PARSING ),
	P_INVALID_PROPERTY_OR_INSTANCE( ErrorLevel.SEVERE, ErrorCategory.PARSING ),
	P_INVALID_FILE_TYPE( ErrorLevel.SEVERE, ErrorCategory.PARSING ),
	P_EMPTY_FILE( ErrorLevel.WARNING, ErrorCategory.PARSING ),

	// Parsing Model Errors
	PM_INVALID_BLOCK_TYPE( ErrorLevel.SEVERE, ErrorCategory.PARSING_MODEL ),
	PM_UNKNOWN_PROPERTY_NAME( ErrorLevel.WARNING, ErrorCategory.PARSING_MODEL ),
	PM_FORBIDDEN_NAME( ErrorLevel.SEVERE, ErrorCategory.PARSING_MODEL ),
	PM_EMPTY_PROPERTY_VALUE( ErrorLevel.SEVERE, ErrorCategory.PARSING_MODEL ),
	PM_EMPTY_IMPORT_LOCATION( ErrorLevel.SEVERE, ErrorCategory.PARSING_MODEL ),
	PM_EMPTY_FACET_NAME( ErrorLevel.SEVERE, ErrorCategory.PARSING_MODEL ),
	PM_EMPTY_REFERENCED_NAME( ErrorLevel.SEVERE, ErrorCategory.PARSING_MODEL ),
	PM_EMPTY_COMPONENT_NAME( ErrorLevel.SEVERE, ErrorCategory.PARSING_MODEL ),
	PM_EMPTY_VARIABLE_NAME( ErrorLevel.SEVERE, ErrorCategory.PARSING_MODEL ),

	PM_INVALID_CHILD_NAME( ErrorLevel.SEVERE, ErrorCategory.PARSING_MODEL, ParsingConstants.PATTERN_ID ),
	PM_INVALID_NAME( ErrorLevel.SEVERE, ErrorCategory.PARSING_MODEL, ParsingConstants.PATTERN_ID ),
	PM_INVALID_EXPORT_COMPLEX_VALUE( ErrorLevel.SEVERE, ErrorCategory.PARSING_MODEL ),
	PM_INVALID_EXPORTED_VAR_NAME( ErrorLevel.SEVERE, ErrorCategory.PARSING_MODEL ),
	PM_EXTERNAL_IS_KEYWORD_FOR_IMPORTS( ErrorLevel.SEVERE, ErrorCategory.PARSING_MODEL, ParsingConstants.PROPERTY_COMPONENT_EXTERNAL_IMPORT ),
	PM_INVALID_IMPORTED_VAR_NAME( ErrorLevel.SEVERE, ErrorCategory.PARSING_MODEL ),
	PM_INVALID_INSTALLER_NAME( ErrorLevel.SEVERE, ErrorCategory.PARSING_MODEL, ParsingConstants.PATTERN_FLEX_ID ),
	PM_INVALID_INSTANCE_ELEMENT( ErrorLevel.SEVERE, ErrorCategory.PARSING_MODEL ),
	PM_INVALID_INSTANCE_COUNT( ErrorLevel.SEVERE, ErrorCategory.PARSING_MODEL ),
	PM_USELESS_INSTANCE_COUNT( ErrorLevel.WARNING, ErrorCategory.PARSING_MODEL ),

	PM_PROPERTY_NOT_APPLIABLE( ErrorLevel.SEVERE, ErrorCategory.PARSING_MODEL ),
	PM_DUPLICATE_PROPERTY( ErrorLevel.SEVERE, ErrorCategory.PARSING_MODEL ),
	PM_MISSING_INSTANCE_NAME( ErrorLevel.SEVERE, ErrorCategory.PARSING_MODEL ),
	PM_INVALID_INSTANCE_NAME( ErrorLevel.SEVERE, ErrorCategory.PARSING_MODEL, ParsingConstants.PATTERN_FLEX_ID ),

	PM_DOT_IS_NOT_ALLOWED( ErrorLevel.SEVERE, ErrorCategory.PARSING_MODEL ),
	PM_INCOMPLETE_IMPORTED_VAR_NAME( ErrorLevel.SEVERE, ErrorCategory.PARSING_MODEL ),
	PM_MALFORMED_COMMENT( ErrorLevel.WARNING, ErrorCategory.PARSING_MODEL ),
	PM_MALFORMED_BLANK( ErrorLevel.WARNING, ErrorCategory.PARSING_MODEL ),

	// Conversion Errors
	CO_NOT_A_GRAPH( ErrorLevel.SEVERE, ErrorCategory.CONVERSION ),
	CO_NOT_INSTANCES( ErrorLevel.SEVERE, ErrorCategory.CONVERSION ),
	CO_UNREACHABLE_FILE( ErrorLevel.SEVERE, ErrorCategory.CONVERSION ),
	CO_ALREADY_DEFINED_FACET( ErrorLevel.SEVERE, ErrorCategory.CONVERSION ),
	CO_ALREADY_DEFINED_COMPONENT( ErrorLevel.SEVERE, ErrorCategory.CONVERSION ),
	CO_CYCLE_IN_COMPONENTS_INHERITANCE( ErrorLevel.SEVERE, ErrorCategory.CONVERSION ),
	CO_ALREADY_DEFINED_INSTANCE( ErrorLevel.SEVERE, ErrorCategory.CONVERSION ),
	CO_CONFLICTING_INFERRED_INSTANCE( ErrorLevel.SEVERE, ErrorCategory.CONVERSION ),
	CO_INEXISTING_CHILD( ErrorLevel.SEVERE, ErrorCategory.CONVERSION ),
	CO_INEXISTING_COMPONENT( ErrorLevel.SEVERE, ErrorCategory.CONVERSION ),
	CO_INEXISTING_FACET( ErrorLevel.SEVERE, ErrorCategory.CONVERSION ),
	CO_CONFLICTING_NAME( ErrorLevel.SEVERE, ErrorCategory.CONVERSION ),
	CO_GRAPH_COULD_NOT_BE_BUILT( ErrorLevel.SEVERE, ErrorCategory.CONVERSION ),

	// Runtime Model Errors
	RM_MISSING_APPLICATION_NAME( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL ),
	RM_INVALID_APPLICATION_NAME( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL, ParsingConstants.PATTERN_APP_NAME ),
	RM_MISSING_APPLICATION_DSL_ID( ErrorLevel.WARNING, ErrorCategory.RUNTIME_MODEL ),
	RM_MISSING_APPLICATION_VERSION( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL ),
	RM_MISSING_APPLICATION_GEP( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL ),
	RM_MISSING_APPLICATION_GRAPHS( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL ),
	RM_MISSING_APPLICATION_EXPORT_PREFIX( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL ),
	RM_INVALID_APPLICATION_VERSION( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL ),

	RM_DOT_IS_NOT_ALLOWED( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL ),
	RM_EMPTY_COMPONENT_NAME( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL ),
	RM_EMPTY_FACET_NAME( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL ),
	RM_INVALID_COMPONENT_NAME( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL, ParsingConstants.PATTERN_FLEX_ID ),
	RM_INVALID_FACET_NAME( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL, ParsingConstants.PATTERN_FLEX_ID ),
	RM_EMPTY_COMPONENT_INSTALLER( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL ),
	RM_INVALID_COMPONENT_INSTALLER( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL, ParsingConstants.PATTERN_FLEX_ID ),
	RM_COMPONENT_IMPORTS_EXPORTS( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL ),
	RM_ROOT_INSTALLER_MUST_BE_TARGET( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL ),

	RM_EMPTY_VARIABLE_NAME( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL ),
	RM_INVALID_VARIABLE_NAME( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL, ParsingConstants.PATTERN_ID ),
	RM_INVALID_APPLICATION_EXPORT_PREFIX( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL, ParsingConstants.PATTERN_FLEX_ID ),
	RM_MAGIC_INSTANCE_VARIABLE( ErrorLevel.WARNING, ErrorCategory.RUNTIME_MODEL ),
	RM_MISSING_VARIABLE_VALUE( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL ),
	RM_AMBIGUOUS_OVERRIDING( ErrorLevel.WARNING, ErrorCategory.RUNTIME_MODEL ),
	RM_INVALID_EXTERNAL_EXPORT( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL ),
	RM_ALREADY_DEFINED_EXTERNAL_EXPORT( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL ),
	RM_INVALID_RANDOM_KIND( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL ),
	RM_NO_VALUE_FOR_RANDOM( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL ),

	RM_CYCLE_IN_COMPONENTS( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL ),
	RM_CYCLE_IN_COMPONENTS_INHERITANCE( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL ),
	RM_CYCLE_IN_FACETS_INHERITANCE( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL ),
	RM_NO_ROOT_COMPONENT( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL ),
	RM_NOT_A_ROOT_COMPONENT( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL ),
	RM_UNRESOLVABLE_VARIABLE( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL ),
	RM_UNRESOLVABLE_FACET_VARIABLE( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL ),

	RM_EMPTY_INSTANCE_NAME( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL ),
	RM_INVALID_INSTANCE_NAME( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL, ParsingConstants.PATTERN_FLEX_ID ),
	RM_EMPTY_INSTANCE_COMPONENT( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL ),
	RM_MISSING_INSTANCE_PARENT( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL ),
	RM_INVALID_INSTANCE_PARENT( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL ),
	RM_UNREACHABLE_COMPONENT( ErrorLevel.SEVERE, ErrorCategory.RUNTIME_MODEL ),
	RM_ORPHAN_FACET( ErrorLevel.WARNING, ErrorCategory.RUNTIME_MODEL ),
	RM_ORPHAN_FACET_WITH_CHILDREN( ErrorLevel.WARNING, ErrorCategory.RUNTIME_MODEL ),

	// Projects Errors
	PROJ_NO_GRAPH_DIR( ErrorLevel.SEVERE, ErrorCategory.PROJECT ),
	PROJ_NO_DESC_DIR( ErrorLevel.SEVERE, ErrorCategory.PROJECT ),
	PROJ_NO_DESC_FILE( ErrorLevel.SEVERE, ErrorCategory.PROJECT ),
	PROJ_MISSING_GRAPH_EP( ErrorLevel.SEVERE, ErrorCategory.PROJECT ),
	PROJ_MISSING_INSTANCE_EP( ErrorLevel.SEVERE, ErrorCategory.PROJECT ),
	PROJ_EXTRACT_TEMP( ErrorLevel.SEVERE, ErrorCategory.PROJECT ),
	PROJ_EXTRACT_ZIP( ErrorLevel.SEVERE, ErrorCategory.PROJECT ),
	PROJ_DELETE_TEMP( ErrorLevel.WARNING, ErrorCategory.PROJECT ),
	PROJ_READ_DESC_FILE( ErrorLevel.SEVERE, ErrorCategory.PROJECT ),
	PROJ_INVALID_EXTERNAL_EXPORTS( ErrorLevel.SEVERE, ErrorCategory.PROJECT ),
	PROJ_NO_RESOURCE_DIRECTORY( ErrorLevel.WARNING, ErrorCategory.PROJECT ),
	PROJ_APPLICATION_TEMPLATE_NOT_FOUND( ErrorLevel.SEVERE, ErrorCategory.PROJECT ),
	PROJ_INVALID_COMMAND_EXT( ErrorLevel.SEVERE, ErrorCategory.PROJECT, Constants.FILE_EXT_COMMANDS ),
	PROJ_INVALID_RULE_EXT( ErrorLevel.SEVERE, ErrorCategory.PROJECT, Constants.FILE_EXT_RULE ),
	PROJ_UNREACHABLE_FILE( ErrorLevel.WARNING, ErrorCategory.PROJECT ),
	PROJ_INVALID_FILE_LOCATION( ErrorLevel.WARNING, ErrorCategory.PROJECT ),

	// Recipes Errors
	REC_PUPPET_DISLIKES_WILDCARD_IMPORTS( ErrorLevel.WARNING, ErrorCategory.RECIPES ),
	REC_PUPPET_HAS_NO_RBCF_MODULE( ErrorLevel.SEVERE, ErrorCategory.RECIPES ),
	REC_PUPPET_HAS_TOO_MANY_RBCF_MODULES( ErrorLevel.SEVERE, ErrorCategory.RECIPES ),
	REC_PUPPET_MISSING_PARAM_IMPORT_DIFF( ErrorLevel.SEVERE, ErrorCategory.RECIPES ),
	REC_PUPPET_MISSING_PARAM_RUNNING_STATE( ErrorLevel.SEVERE, ErrorCategory.RECIPES ),
	REC_PUPPET_MISSING_PARAM_FROM_IMPORT( ErrorLevel.WARNING, ErrorCategory.RECIPES ),
	REC_PUPPET_SYNTAX_ERROR( ErrorLevel.SEVERE, ErrorCategory.RECIPES ),
	REC_SCRIPT_NO_SCRIPTS_DIR( ErrorLevel.SEVERE, ErrorCategory.RECIPES ),
	REC_ARTIFACT_ID_IN_LOWER_CASE( ErrorLevel.WARNING, ErrorCategory.RECIPES ),
	REC_MISSING_README( ErrorLevel.WARNING, ErrorCategory.RECIPES ),
	REC_OFFICIAL_GROUP_ID( ErrorLevel.WARNING, ErrorCategory.RECIPES, Constants.OFFICIAL_RECIPES_GROUP_ID ),
	REC_NON_MATCHING_ARTIFACT_ID( ErrorLevel.WARNING, ErrorCategory.RECIPES ),
	REC_AVOID_INSTANCES( ErrorLevel.WARNING, ErrorCategory.RECIPES ),
	REC_TARGET_NO_ID( ErrorLevel.SEVERE, ErrorCategory.RECIPES ),
	REC_TARGET_NO_HANDLER( ErrorLevel.SEVERE, ErrorCategory.RECIPES ),
	REC_TARGET_INVALID_FILE_OR_CONTENT( ErrorLevel.SEVERE, ErrorCategory.RECIPES ),
	REC_TARGET_CONFLICTING_ID( ErrorLevel.SEVERE, ErrorCategory.RECIPES ),
	REC_TARGET_NO_NAME( ErrorLevel.WARNING, ErrorCategory.RECIPES ),
	REC_TARGET_NO_PROPERTIES( ErrorLevel.SEVERE, ErrorCategory.RECIPES ),

	// Commands Errors
	CMD_INVALID_TARGET_ID( ErrorLevel.SEVERE, ErrorCategory.COMMANDS ),
	CMD_NO_MATCHING_INSTANCE( ErrorLevel.SEVERE, ErrorCategory.COMMANDS ),
	CMD_NOT_AN_ACCEPTABLE_PARENT( ErrorLevel.SEVERE, ErrorCategory.COMMANDS ),
	CMD_CANNOT_HAVE_ANY_PARENT( ErrorLevel.SEVERE, ErrorCategory.COMMANDS ),
	CMD_NOT_A_SCOPED_INSTANCE( ErrorLevel.SEVERE, ErrorCategory.COMMANDS ),
	CMD_NOT_A_ROOT_INSTANCE( ErrorLevel.SEVERE, ErrorCategory.COMMANDS ),
	CMD_UNRECOGNIZED_INSTRUCTION( ErrorLevel.SEVERE, ErrorCategory.COMMANDS ),
	CMD_INVALID_INSTANCE_STATUS( ErrorLevel.SEVERE, ErrorCategory.COMMANDS ),
	CMD_INSTABLE_INSTANCE_STATUS( ErrorLevel.SEVERE, ErrorCategory.COMMANDS ),
	CMD_EMPTY_VARIABLE_NAME( ErrorLevel.SEVERE, ErrorCategory.COMMANDS ),
	CMD_MISSING_INSTANCE_NAME( ErrorLevel.SEVERE, ErrorCategory.COMMANDS ),
	CMD_INVALID_INSTANCE_NAME( ErrorLevel.SEVERE, ErrorCategory.COMMANDS, ParsingConstants.PATTERN_FLEX_ID ),
	CMD_MISSING_COMPONENT_NAME( ErrorLevel.SEVERE, ErrorCategory.COMMANDS ),
	CMD_INEXISTING_COMPONENT( ErrorLevel.SEVERE, ErrorCategory.COMMANDS ),
	CMD_MISSING_PARENT_INSTANCE( ErrorLevel.SEVERE, ErrorCategory.COMMANDS ),
	CMD_CONFLICTING_INSTANCE_NAME( ErrorLevel.SEVERE, ErrorCategory.COMMANDS ),
	CMD_EMAIL_NO_MESSAGE( ErrorLevel.SEVERE, ErrorCategory.COMMANDS ),
	CMD_NO_INSTRUCTION( ErrorLevel.WARNING, ErrorCategory.COMMANDS ),
	CMD_UNRESOLVED_VARIABLE( ErrorLevel.SEVERE, ErrorCategory.COMMANDS ),
	CMD_INVALID_SYNTAX( ErrorLevel.SEVERE, ErrorCategory.COMMANDS ),
	CMD_MISSING_TARGET_FILE( ErrorLevel.SEVERE, ErrorCategory.COMMANDS ),
	CMD_MISSING_COMMAND_NAME( ErrorLevel.SEVERE, ErrorCategory.COMMANDS ),
	CMD_INEXISTING_COMMAND( ErrorLevel.SEVERE, ErrorCategory.COMMANDS ),
	CMD_INEXISTING_COMMAND_FILE( ErrorLevel.SEVERE, ErrorCategory.COMMANDS ),
	CMD_LOOPING_COMMAND( ErrorLevel.SEVERE, ErrorCategory.COMMANDS ),
	CMD_NASTY_LOOPING_COMMAND( ErrorLevel.SEVERE, ErrorCategory.COMMANDS ),
	CMD_INVALID_DATE_PATTERN( ErrorLevel.SEVERE, ErrorCategory.COMMANDS ),
	CMD_NO_MIX_FOR_PATTERNS( ErrorLevel.SEVERE, ErrorCategory.COMMANDS ),
	CMD_INVALID_INDEX_PATTERN( ErrorLevel.SEVERE, ErrorCategory.COMMANDS ),

	// Rule errors
	RULE_IO_ERROR( ErrorLevel.SEVERE, ErrorCategory.RULES ),
	RULE_EMPTY_NAME( ErrorLevel.SEVERE, ErrorCategory.RULES ),
	RULE_INVALID_SYNTAX( ErrorLevel.SEVERE, ErrorCategory.RULES ),
	RULE_EMPTY_WHEN( ErrorLevel.SEVERE, ErrorCategory.RULES ),
	RULE_EMPTY_THEN( ErrorLevel.SEVERE, ErrorCategory.RULES ),
	RULE_UNKNOWN_COMMAND( ErrorLevel.SEVERE, ErrorCategory.RULES ),

	// REST Errors
	REST_TARGET_CONTAINS_ERROR( ErrorLevel.SEVERE, ErrorCategory.REST ),
	REST_TARGET_ASSOCIATION_ERROR( ErrorLevel.SEVERE, ErrorCategory.REST ),
	REST_TARGET_HINT_ERROR( ErrorLevel.SEVERE, ErrorCategory.REST ),

	REST_AUTH_NO_MNGR( ErrorLevel.SEVERE, ErrorCategory.REST ),
	REST_AUTH_FAILED( ErrorLevel.SEVERE, ErrorCategory.REST ),
	REST_SCHEDULER_IS_UNAVAILABLE( ErrorLevel.SEVERE, ErrorCategory.REST ),

	REST_INEXISTING( ErrorLevel.SEVERE, ErrorCategory.REST ),
	REST_MISSING_PROPERTY( ErrorLevel.SEVERE, ErrorCategory.REST ),
	REST_DELETION_ERROR( ErrorLevel.SEVERE, ErrorCategory.REST ),
	REST_IO_ERROR( ErrorLevel.SEVERE, ErrorCategory.REST ),
	REST_UNDETAILED_ERROR( ErrorLevel.SEVERE, ErrorCategory.REST ),
	REST_MESSAGING_ERROR( ErrorLevel.SEVERE, ErrorCategory.REST ),
	REST_SAVE_ERROR( ErrorLevel.SEVERE, ErrorCategory.REST ),

	REST_MNGMT_ZIP_ERROR( ErrorLevel.SEVERE, ErrorCategory.REST ),
	REST_MNGMT_INVALID_TPL( ErrorLevel.SEVERE, ErrorCategory.REST ),
	REST_MNGMT_INVALID_URL( ErrorLevel.SEVERE, ErrorCategory.REST ),
	REST_MNGMT_CONFLICT( ErrorLevel.SEVERE, ErrorCategory.REST ),
	REST_MNGMT_APP_SHUTDOWN_ERROR( ErrorLevel.SEVERE, ErrorCategory.REST ),
	REST_MNGMT_INVALID_IMAGE( ErrorLevel.SEVERE, ErrorCategory.REST ),

	REST_APP_EXEC_ERROR( ErrorLevel.SEVERE, ErrorCategory.REST ),
	REST_DEBUG_AGENT_KO( ErrorLevel.SEVERE, ErrorCategory.REST ),
	REST_DEBUG_MSG_SENT( ErrorLevel.SEVERE, ErrorCategory.REST ),
	;

	/**
	 * RoboconfError categories.
	 */
	public enum ErrorCategory {
		PARSING, PARSING_MODEL, CONVERSION, RUNTIME_MODEL, PROJECT, RECIPES, COMMANDS, RULES, EXECUTION, REST;
	}

	/**
	 * RoboconfError levels.
	 */
	public enum ErrorLevel {
		SEVERE, WARNING;
	}

	// These instructions are called after the enumeration items have been created.
	private static final Map<ErrorCategory,AtomicInteger> CAT_TO_ID = new HashMap<> ();
	static {
		for( ErrorCategory cat : ErrorCategory.values())
			CAT_TO_ID.put( cat, new AtomicInteger( 0 ));

		for( ErrorCode code : values())
			code.errorId = CAT_TO_ID.get( code.category ).getAndIncrement();
	}

	private final ErrorCategory category;
	private final ErrorLevel level;
	private int errorId;
	private String[] i18nProperties;

	/**
	 * @param level
	 * @param category
	 * @param i18nProperties
	 */
	private ErrorCode( ErrorLevel level, ErrorCategory category, String... i18nProperties ) {
		this.category = category;
		this.level = level;
		this.i18nProperties = i18nProperties;
	}

	/**
	 * @return the category
	 */
	public ErrorCategory getCategory() {
		return this.category;
	}

	/**
	 * @return the level
	 */
	public ErrorLevel getLevel() {
		return this.level;
	}

	/**
	 * @return the errorId
	 */
	public int getErrorId() {
		return this.errorId;
	}

	/**
	 * @return the i18nProperties (never null)
	 */
	public String[] getI18nProperties() {
		// Return a copy of the properties
		return Arrays.asList( this.i18nProperties ).toArray( new String[ this.i18nProperties.length ]);
	}
}


text:
/*
 *   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 3 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.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 *    InformationRetrievalEvaluationMetric.java
 *    Copyright (C) 2011-2012 University of Waikato, Hamilton, New Zealand
 *
 */

package weka.classifiers.evaluation;

import weka.core.Instance;

/**
 * An interface for information retrieval evaluation metrics to implement.
 * Allows the command line interface to display these metrics or not based on
 * user-supplied options. These statistics will be displayed as new columns in
 * the table of information retrieval statistics. As such, a toSummaryString()
 * formatted representation is not required.
 *
 * @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
 * @version $Revision: 9320 $
 */
public interface InformationRetrievalEvaluationMetric {

  /**
   * Updates the statistics about a classifiers performance for the current test
   * instance. Implementers need only implement this method if it is not
   * possible to compute their statistics from what is stored in the base
   * Evaluation object.
   *
   * @param predictedDistribution the probabilities assigned to each class
   * @param instance the instance to be classified
   * @throws Exception if the class of the instance is not set
   */
  void updateStatsForClassifier(double[] predictedDistribution,
      Instance instance) throws Exception;

  /**
   * Get the value of the named statistic for the given class index.
   *
   * If the implementing class is extending AbstractEvaluationMetric then the
   * implementation of getStatistic(String statName) should just call this
   * method with a classIndex of 0.
   *
   * @param statName the name of the statistic to compute the value for
   * @param classIndex the class index for which to compute the statistic
   * @return the value of the named statistic for the given class index or
   *         Utils.missingValue() if the statistic can't be computed for some
   *         reason
   */
  double getStatistic(String statName, int classIndex);

  /**
   * Get the weighted (by class) average for this statistic.
   *
   * @param statName the name of the statistic to compute
   * @return the weighted (by class) average value of the statistic or
   *         Utils.missingValue() if this can't be computed (or isn't
   *         appropriate).
   */
  double getClassWeightedAverageStatistic(String statName);
}

redpajama_set_name: RedPajamaGithub


text:
PASSWORD_RESET_MAPPING = {
    'password_reset_send': {
        'resource': 'session/forgot_password',
        'docs': ('http://docs.discourse.org/#tag/'
                 'Password-Reset%2Fpaths%2F~1session~1forgot_password%2Fpost'),
        'methods': ['POST'],
    },
    'password_reset_create': {
        'resource': 'users/password-reset/{token}',
        'docs': ('http://docs.discourse.org/#tag/'
                 'Password-Reset%2Fpaths%2F~1users~1password-reset~1'
                 '%7Btoken%7D%2Fput'),
        'methods': ['PUT'],
    },
}


text:
<?php

namespace J2t\Rewardpoints\Controller\Adminhtml\Customer;

use Magento\Customer\Controller\RegistryConstants;

class Points extends \Magento\Customer\Controller\Adminhtml\Index
{
    /**
     * Customer point's grid
     *
     * @return \Magento\Framework\View\Result\Layout
     */
    public function execute()
    {
        //$this->_initCustomer();
        $customerId = $this->initCurrentCustomer();
        //$customerId = $this->_coreRegistry->registry(RegistryConstants::CURRENT_CUSTOMER_ID);
        /** @var  \Magento\Newsletter\Model\Subscriber $subscriber */
        /*$subscriber = $this->_objectManager
            ->create('Magento\Newsletter\Model\Subscriber')
            ->loadByCustomerId($customerId);

        $this->_coreRegistry->register('subscriber', $subscriber);*/
        $resultLayout = $this->resultLayoutFactory->create();
        return $resultLayout;
    }
}


text:
RSpec.describe RedisRepository do
  let(:redis_repo) { RedisRepository.new }
  let(:code) { 'my_code' }
  let(:url) { 'http://myurl.com'}
  let(:expected) { { url: url, start_date: Time.now.iso8601, redirect_count: 0, last_seen_date: nil } }

  before { Timecop.freeze(Time.now) }
  after { Timecop.return }

  describe '#create_short_code' do
    it 'creates the attribues for that code' do
      expect(redis_repo.create_short_code(code, url)).to eq expected
    end
  end

  describe '#find' do
    before { redis_repo.create_short_code(code, url) }

    context 'when code does not exists' do
      it 'returns nil' do
        expect(redis_repo.find('another_code')).to be_nil
      end
    end

    context 'when code exists' do
      it 'correctly finds the attributes for that code' do
        expect(redis_repo.find(code)).to eq expected
      end
    end
  end

  describe '#exists?' do
    before { redis_repo.create_short_code(code, url) }

    context 'when code does not exists' do
      it { expect(redis_repo.exists?('another_code')).to be_falsey }
    end

    context 'when code exists' do
      it { expect(redis_repo.exists?(code)).to be_truthy }
    end
  end

  describe '#update' do
    let(:updated) { { url: url, start_date: Time.now.iso8601, redirect_count: 1, last_seen_date: nil } }

    before do
      redis_repo.create_short_code(code, url)
      redis_repo.update(code, updated)
    end

    context 'when code does not exists' do
      it { expect(redis_repo.find(code)).to eq updated }
    end
  end

end


text:
namespace ash {

bool NullMouseWarpController::WarpMouseCursor(ui::MouseEvent* event) {
  return false;
}

void NullMouseWarpController::SetEnabled(bool enable) {}

}  // namespace ash


text:
from __future__ import absolute_import, division, print_function
__metaclass__ = type

ANSIBLE_METADATA = {
    'metadata_version': '1.1',
    'status': ['preview'],
    'supported_by': 'community'
}

DOCUMENTATION = r'''
---
module: vmware_host
short_description: Add, remove, or move an ESXi host to, from, or within vCenter
description:
- This module can be used to add, reconnect, or remove an ESXi host to or from vCenter.
- This module can also be used to move an ESXi host to a cluster or folder, or vice versa, within the same datacenter.
version_added: '2.0'
author:
- Joseph Callen (@jcpowermac)
- Russell Teague (@mtnbikenc)
- Maxime de Roucy (@tchernomax)
- Christian Kotte (@ckotte)
notes:
- Tested on vSphere 5.5, 6.0, 6.5 and 6.7
requirements:
- python >= 2.6
- PyVmomi
- ssl
- socket
- hashlib
options:
  datacenter_name:
    description:
    - Name of the datacenter to add the host.
    - Aliases added in version 2.6.
    required: yes
    aliases: ['datacenter']
    type: str
  cluster_name:
    description:
    - Name of the cluster to add the host.
    - If C(folder) is not set, then this parameter is required.
    - Aliases added in version 2.6.
    aliases: ['cluster']
    type: str
  folder:
    description:
    - Name of the folder under which host to add.
    - If C(cluster_name) is not set, then this parameter is required.
    - "For example, if there is a datacenter 'dc1' under folder called 'Site1' then, this value will be '/Site1/dc1/host'."
    - "Here 'host' is an invisible folder under VMware Web Client."
    - "Another example, if there is a nested folder structure like '/myhosts/india/pune' under
       datacenter 'dc2', then C(folder) value will be '/dc2/host/myhosts/india/pune'."
    - "Other Examples: "
    - "  - '/Site2/dc2/Asia-Cluster/host'"
    - "  - '/dc3/Asia-Cluster/host'"
    version_added: "2.6"
    aliases: ['folder_name']
    type: str
  add_connected:
    description:
    - If set to C(True), then the host should be connected as soon as it is added.
    - This parameter is ignored if state is set to a value other than C(present).
    default: True
    type: bool
    version_added: "2.6"
  esxi_hostname:
    description:
    - ESXi hostname to manage.
    required: yes
    type: str
  esxi_username:
    description:
    - ESXi username.
    - Required for adding a host.
    - Optional for reconnect. If both C(esxi_username) and C(esxi_password) are used
    - Unused for removing.
    - No longer a required parameter from version 2.5.
    type: str
  esxi_password:
    description:
    - ESXi password.
    - Required for adding a host.
    - Optional for reconnect.
    - Unused for removing.
    - No longer a required parameter from version 2.5.
    type: str
  state:
    description:
    - If set to C(present), add the host if host is absent.
    - If set to C(present), update the location of the host if host already exists.
    - If set to C(absent), remove the host if host is present.
    - If set to C(absent), do nothing if host already does not exists.
    - If set to C(add_or_reconnect), add the host if it's absent else reconnect it and update the location.
    - If set to C(reconnect), then reconnect the host if it's present and update the location.
    default: present
    choices: ['present', 'absent', 'add_or_reconnect', 'reconnect']
    type: str
  esxi_ssl_thumbprint:
    description:
    - "Specifying the hostsystem certificate's thumbprint."
    - "Use following command to get hostsystem certificate's thumbprint - "
    - "# openssl x509 -in /etc/vmware/ssl/rui.crt -fingerprint -sha1 -noout"
    - Only used if C(fetch_thumbprint) isn't set to C(true).
    version_added: 2.5
    default: ''
    type: str
    aliases: ['ssl_thumbprint']
  fetch_ssl_thumbprint:
    description:
    - Fetch the thumbprint of the host's SSL certificate.
    - This basically disables the host certificate verification (check if it was signed by a recognized CA).
    - Disable this option if you want to allow only hosts with valid certificates to be added to vCenter.
    - If this option is set to C(false) and the certificate can't be verified, an add or reconnect will fail.
    - Unused when C(esxi_ssl_thumbprint) is set.
    - Optional for reconnect, but only used if C(esxi_username) and C(esxi_password) are used.
    - Unused for removing.
    type: bool
    version_added: 2.8
    default: True
  force_connection:
    description:
    - Force the connection if the host is already being managed by another vCenter server.
    type: bool
    version_added: 2.8
    default: True
  reconnect_disconnected:
    description:
    - Reconnect disconnected hosts.
    - This is only used if C(state) is set to C(present) and if the host already exists.
    type: bool
    version_added: 2.8
    default: True
extends_documentation_fragment: vmware.documentation
'''

EXAMPLES = r'''
- name: Add ESXi Host to vCenter
  vmware_host:
    hostname: '{{ vcenter_hostname }}'
    username: '{{ vcenter_username }}'
    password: '{{ vcenter_password }}'
    datacenter: datacenter_name
    cluster: cluster_name
    esxi_hostname: '{{ esxi_hostname }}'
    esxi_username: '{{ esxi_username }}'
    esxi_password: '{{ esxi_password }}'
    state: present
  delegate_to: localhost

- name: Add ESXi Host to vCenter under a specific folder
  vmware_host:
    hostname: '{{ vcenter_hostname }}'
    username: '{{ vcenter_username }}'
    password: '{{ vcenter_password }}'
    datacenter: datacenter_name
    folder: '/Site2/Asia-Cluster/host'
    esxi_hostname: '{{ esxi_hostname }}'
    esxi_username: '{{ esxi_username }}'
    esxi_password: '{{ esxi_password }}'
    state: present
    add_connected: True
  delegate_to: localhost

- name: Reconnect ESXi Host (with username/password set)
  vmware_host:
    hostname: '{{ vcenter_hostname }}'
    username: '{{ vcenter_username }}'
    password: '{{ vcenter_password }}'
    datacenter: datacenter_name
    cluster: cluster_name
    esxi_hostname: '{{ esxi_hostname }}'
    esxi_username: '{{ esxi_username }}'
    esxi_password: '{{ esxi_password }}'
    state: reconnect
  delegate_to: localhost

- name: Reconnect ESXi Host (with default username/password)
  vmware_host:
    hostname: '{{ vcenter_hostname }}'
    username: '{{ vcenter_username }}'
    password: '{{ vcenter_password }}'
    datacenter: datacenter_name
    cluster: cluster_name
    esxi_hostname: '{{ esxi_hostname }}'
    state: reconnect
  delegate_to: localhost

- name: Add ESXi Host with SSL Thumbprint to vCenter
  vmware_host:
    hostname: '{{ vcenter_hostname }}'
    username: '{{ vcenter_username }}'
    password: '{{ vcenter_password }}'
    datacenter: datacenter_name
    cluster: cluster_name
    esxi_hostname: '{{ esxi_hostname }}'
    esxi_username: '{{ esxi_username }}'
    esxi_password: '{{ esxi_password }}'
    esxi_ssl_thumbprint: "3C:A5:60:6F:7A:B7:C4:6C:48:28:3D:2F:A5:EC:A3:58:13:88:F6:DD"
    state: present
  delegate_to: localhost
'''

RETURN = r'''
result:
    description: metadata about the new host system added
    returned: on successful addition
    type: str
    sample: "Host already connected to vCenter 'vcenter01' in cluster 'cluster01'"
'''

try:
    from pyVmomi import vim, vmodl
    import ssl
    import socket
    import hashlib
except ImportError:
    pass

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible.module_utils.vmware import (
    PyVmomi, TaskError, vmware_argument_spec,
    wait_for_task, find_host_by_cluster_datacenter, find_hostsystem_by_name
)

class VMwareHost(PyVmomi):
    """Class to manage vCenter connection"""
    def __init__(self, module):
        super(VMwareHost, self).__init__(module)
        self.vcenter = module.params['hostname']
        self.datacenter_name = module.params['datacenter_name']
        self.cluster_name = module.params['cluster_name']
        self.folder_name = module.params['folder']
        self.esxi_hostname = module.params['esxi_hostname']
        self.esxi_username = module.params['esxi_username']
        self.esxi_password = module.params['esxi_password']
        self.state = module.params['state']
        self.esxi_ssl_thumbprint = module.params.get('esxi_ssl_thumbprint', '')
        self.force_connection = module.params.get('force_connection')
        self.fetch_ssl_thumbprint = module.params.get('fetch_ssl_thumbprint')
        self.reconnect_disconnected = module.params.get('reconnect_disconnected')
        self.host_update = self.host = self.cluster = self.folder = self.host_parent_compute_resource = None

    def process_state(self):
        """Check the current state"""
        host_states = {
            'absent': {
                'present': self.state_remove_host,
                'update': self.state_remove_host,
                'absent': self.state_exit_unchanged,
            },
            'present': {
                'present': self.state_exit_unchanged,
                'update': self.state_update_host,
                'absent': self.state_add_host,
            },
            'add_or_reconnect': {
                'present': self.state_reconnect_host,
                'update': self.state_update_host,
                'absent': self.state_add_host,
            },
            'reconnect': {
                'present': self.state_reconnect_host,
                'update': self.state_update_host,
            }
        }

        try:
            host_states[self.state][self.check_host_state()]()
        except vmodl.RuntimeFault as runtime_fault:
            self.module.fail_json(msg=to_native(runtime_fault.msg))
        except vmodl.MethodFault as method_fault:
            self.module.fail_json(msg=to_native(method_fault.msg))
        except Exception as e:
            self.module.fail_json(msg=to_native(e))

    def check_host_state(self):
        """Check current state"""
        # Check if the host is already connected to vCenter
        self.host_update = find_hostsystem_by_name(self.content, self.esxi_hostname)
        if self.host_update:
            # The host name is unique in vCenter; A host with the same name cannot exist in another datacenter
            # However, the module will fail later if the target folder/cluster is in another datacenter as the host
            # Check if the host is connected under the target cluster
            if self.cluster_name:
                self.host, self.cluster = self.search_cluster(self.datacenter_name, self.cluster_name, self.esxi_hostname)
                if self.host:
                    state = 'present'
                else:
                    state = 'update'
            # Check if the host is connected under the target folder
            elif self.folder_name:
                self.folder = self.search_folder(self.folder_name)
                for child in self.folder.childEntity:
                    if not child or not isinstance(child, vim.ComputeResource):
                        continue
                    try:
                        if isinstance(child.host[0], vim.HostSystem) and child.name == self.esxi_hostname:
                            self.host_parent_compute_resource = child
                            self.host = child.host[0]
                            break
                    except IndexError:
                        continue
                if self.host:
                    state = 'present'
                else:
                    state = 'update'
        else:
            state = 'absent'
        return state

    def search_folder(self, folder_name):
        """
            Search folder in vCenter
            Returns: folder object
        """
        search_index = self.content.searchIndex
        folder_obj = search_index.FindByInventoryPath(folder_name)
        if not (folder_obj and isinstance(folder_obj, vim.Folder)):
            self.module.fail_json(msg="Folder '%s' not found" % folder_name)
        return folder_obj

    def search_cluster(self, datacenter_name, cluster_name, esxi_hostname):
        """
            Search cluster in vCenter
            Returns: host and cluster object
        """
        return find_host_by_cluster_datacenter(
            self.module, self.content, datacenter_name, cluster_name, esxi_hostname
        )

    def state_exit_unchanged(self):
        """Exit with status message"""
        if not self.host_update:
            result = "Host already disconnected"
        elif self.reconnect_disconnected and self.host_update.runtime.connectionState == 'disconnected':
            self.state_reconnect_host()
        else:
            if self.folder_name:
                result = "Host already connected to vCenter '%s' in folder '%s'" % (self.vcenter, self.folder_name)
            elif self.cluster_name:
                result = "Host already connected to vCenter '%s' in cluster '%s'" % (self.vcenter, self.cluster_name)
        self.module.exit_json(changed=False, result=str(result))

    def state_add_host(self):
        """Add ESXi host to a cluster of folder in vCenter"""
        changed = True
        result = None

        if self.module.check_mode:
            result = "Host would be connected to vCenter '%s'" % self.vcenter
        else:
            host_connect_spec = self.get_host_connect_spec()
            as_connected = self.params.get('add_connected')
            esxi_license = None
            resource_pool = None
            task = None
            if self.folder_name:
                self.folder = self.search_folder(self.folder_name)
                try:
                    task = self.folder.AddStandaloneHost(
                        spec=host_connect_spec, compResSpec=resource_pool,
                        addConnected=as_connected, license=esxi_license
                    )
                except vim.fault.InvalidLogin as invalid_login:
                    self.module.fail_json(
                        msg="Cannot authenticate with the host : %s" % to_native(invalid_login)
                    )
                except vim.fault.HostConnectFault as connect_fault:
                    self.module.fail_json(
                        msg="An error occurred during connect : %s" % to_native(connect_fault)
                    )
                except vim.fault.DuplicateName as duplicate_name:
                    self.module.fail_json(
                        msg="The folder already contains a host with the same name : %s" %
                        to_native(duplicate_name)
                    )
                except vmodl.fault.InvalidArgument as invalid_argument:
                    self.module.fail_json(
                        msg="An argument was specified incorrectly : %s" % to_native(invalid_argument)
                    )
                except vim.fault.AlreadyBeingManaged as already_managed:
                    self.module.fail_json(
                        msg="The host is already being managed by another vCenter server : %s" %
                        to_native(already_managed)
                    )
                except vmodl.fault.NotEnoughLicenses as not_enough_licenses:
                    self.module.fail_json(
                        msg="There are not enough licenses to add this host : %s" % to_native(not_enough_licenses)
                    )
                except vim.fault.NoHost as no_host:
                    self.module.fail_json(
                        msg="Unable to contact the host : %s" % to_native(no_host)
                    )
                except vmodl.fault.NotSupported as not_supported:
                    self.module.fail_json(
                        msg="The folder is not a host folder : %s" % to_native(not_supported)
                    )
                except vim.fault.NotSupportedHost as host_not_supported:
                    self.module.fail_json(
                        msg="The host is running a software version that is not supported : %s" %
                        to_native(host_not_supported)
                    )
                except vim.fault.AgentInstallFailed as agent_install:
                    self.module.fail_json(
                        msg="Error during vCenter agent installation : %s" % to_native(agent_install)
                    )
                except vim.fault.AlreadyConnected as already_connected:
                    self.module.fail_json(
                        msg="The host is already connected to the vCenter server : %s" % to_native(already_connected)
                    )
                except vim.fault.SSLVerifyFault as ssl_fault:
                    self.module.fail_json(
                        msg="The host certificate could not be authenticated : %s" % to_native(ssl_fault)
                    )
            elif self.cluster_name:
                self.host, self.cluster = self.search_cluster(
                    self.datacenter_name,
                    self.cluster_name,
                    self.esxi_hostname
                )
                try:
                    task = self.cluster.AddHost_Task(
                        spec=host_connect_spec, asConnected=as_connected,
                        resourcePool=resource_pool, license=esxi_license
                    )
                except vim.fault.InvalidLogin as invalid_login:
                    self.module.fail_json(
                        msg="Cannot authenticate with the host : %s" % to_native(invalid_login)
                    )
                except vim.fault.HostConnectFault as connect_fault:
                    self.module.fail_json(
                        msg="An error occurred during connect : %s" % to_native(connect_fault)
                    )
                except vim.fault.DuplicateName as duplicate_name:
                    self.module.fail_json(
                        msg="The cluster already contains a host with the same name : %s" %
                        to_native(duplicate_name)
                    )
                except vim.fault.AlreadyBeingManaged as already_managed:
                    self.module.fail_json(
                        msg="The host is already being managed by another vCenter server : %s" %
                        to_native(already_managed)
                    )
                except vmodl.fault.NotEnoughLicenses as not_enough_licenses:
                    self.module.fail_json(
                        msg="There are not enough licenses to add this host : %s" % to_native(not_enough_licenses)
                    )
                except vim.fault.NoHost as no_host:
                    self.module.fail_json(
                        msg="Unable to contact the host : %s" % to_native(no_host)
                    )
                except vim.fault.NotSupportedHost as host_not_supported:
                    self.module.fail_json(
                        msg="The host is running a software version that is not supported; "
                        "It may still be possible to add the host as a stand-alone host : %s" %
                        to_native(host_not_supported)
                    )
                except vim.fault.TooManyHosts as too_many_hosts:
                    self.module.fail_json(
                        msg="No additional hosts can be added to the cluster : %s" % to_native(too_many_hosts)
                    )
                except vim.fault.AgentInstallFailed as agent_install:
                    self.module.fail_json(
                        msg="Error during vCenter agent installation : %s" % to_native(agent_install)
                    )
                except vim.fault.AlreadyConnected as already_connected:
                    self.module.fail_json(
                        msg="The host is already connected to the vCenter server : %s" % to_native(already_connected)
                    )
                except vim.fault.SSLVerifyFault as ssl_fault:
                    self.module.fail_json(
                        msg="The host certificate could not be authenticated : %s" % to_native(ssl_fault)
                    )
            try:
                changed, result = wait_for_task(task)
                result = "Host connected to vCenter '%s'" % self.vcenter
            except TaskError as task_error:
                self.module.fail_json(
                    msg="Failed to add host to vCenter '%s' : %s" % (self.vcenter, to_native(task_error))
                )

        self.module.exit_json(changed=changed, result=result)

    def get_host_connect_spec(self):
        """
        Function to return Host connection specification
        Returns: host connection specification
        """
        host_connect_spec = vim.host.ConnectSpec()
        host_connect_spec.hostName = self.esxi_hostname
        host_connect_spec.userName = self.esxi_username
        host_connect_spec.password = self.esxi_password
        host_connect_spec.force = self.force_connection
        # Get the thumbprint of the SSL certificate
        if self.fetch_ssl_thumbprint and self.esxi_ssl_thumbprint == '':
            # We need to grab the thumbprint manually because it's not included in
            # the task error via an SSLVerifyFault exception anymore
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(1)
            wrapped_socket = ssl.wrap_socket(sock)
            try:
                wrapped_socket.connect((self.esxi_hostname, 443))
            except socket.error as socket_error:
                self.module.fail_json(msg="Cannot connect to host : %s" % socket_error)
            else:
                der_cert_bin = wrapped_socket.getpeercert(True)
                # thumb_md5 = hashlib.md5(der_cert_bin).hexdigest()
                thumb_sha1 = self.format_number(hashlib.sha1(der_cert_bin).hexdigest())
                # thumb_sha256 = hashlib.sha256(der_cert_bin).hexdigest()
            wrapped_socket.close()
            host_connect_spec.sslThumbprint = thumb_sha1
        else:
            host_connect_spec.sslThumbprint = self.esxi_ssl_thumbprint
        return host_connect_spec

    @staticmethod
    def format_number(number):
        """Format number"""
        string = str(number)
        return ':'.join(a + b for a, b in zip(string[::2], string[1::2]))

    def state_reconnect_host(self):
        """Reconnect host to vCenter"""
        changed = True
        result = None

        if self.module.check_mode:
            result = "Host would be reconnected to vCenter '%s'" % self.vcenter
        else:
            self.reconnect_host(self.host)
            result = "Host reconnected to vCenter '%s'" % self.vcenter
        self.module.exit_json(changed=changed, result=str(result))

    def reconnect_host(self, host_object):
        """Reconnect host to vCenter"""
        reconnecthost_args = {}
        reconnecthost_args['reconnectSpec'] = vim.HostSystem.ReconnectSpec()
        reconnecthost_args['reconnectSpec'].syncState = True

        if self.esxi_username and self.esxi_password:
            # Build the connection spec as well and fetch thumbprint if enabled
            # Usefull if you reinstalled a host and it uses a new self-signed certificate
            reconnecthost_args['cnxSpec'] = self.get_host_connect_spec()
        try:
            task = host_object.ReconnectHost_Task(**reconnecthost_args)
        except vim.fault.InvalidLogin as invalid_login:
            self.module.fail_json(
                msg="Cannot authenticate with the host : %s" % to_native(invalid_login)
            )
        except vim.fault.InvalidState as invalid_state:
            self.module.fail_json(
                msg="The host is not disconnected : %s" % to_native(invalid_state)
            )
        except vim.fault.InvalidName as invalid_name:
            self.module.fail_json(
                msg="The host name is invalid : %s" % to_native(invalid_name)
            )
        except vim.fault.HostConnectFault as connect_fault:
            self.module.fail_json(
                msg="An error occurred during reconnect : %s" % to_native(connect_fault)
            )
        except vmodl.fault.NotSupported as not_supported:
            self.module.fail_json(
                msg="No host can be added to this group : %s" % to_native(not_supported)
            )
        except vim.fault.AlreadyBeingManaged as already_managed:
            self.module.fail_json(
                msg="The host is already being managed by another vCenter server : %s" % to_native(already_managed)
            )
        except vmodl.fault.NotEnoughLicenses as not_enough_licenses:
            self.module.fail_json(
                msg="There are not enough licenses to add this host : %s" % to_native(not_enough_licenses)
            )
        except vim.fault.NoHost as no_host:
            self.module.fail_json(
                msg="Unable to contact the host : %s" % to_native(no_host)
            )
        except vim.fault.NotSupportedHost as host_not_supported:
            self.module.fail_json(
                msg="The host is running a software version that is not supported : %s" %
                to_native(host_not_supported)
            )
        except vim.fault.SSLVerifyFault as ssl_fault:
            self.module.fail_json(
                msg="The host certificate could not be authenticated : %s" % to_native(ssl_fault)
            )
        try:
            changed, result = wait_for_task(task)
        except TaskError as task_error:
            self.module.fail_json(
                msg="Failed to reconnect host to vCenter '%s' due to %s" %
                (self.vcenter, to_native(task_error))
            )

    def state_remove_host(self):
        """Remove host from vCenter"""
        changed = True
        result = None
        if self.module.check_mode:
            result = "Host would be removed from vCenter '%s'" % self.vcenter
        else:
            # Check parent type
            parent_type = self.get_parent_type(self.host_update)
            if parent_type == 'cluster':
                self.put_host_in_maintenance_mode(self.host_update)
            try:
                if self.folder_name:
                    task = self.host_parent_compute_resource.Destroy_Task()
                elif self.cluster_name:
                    task = self.host.Destroy_Task()
            except vim.fault.VimFault as vim_fault:
                self.module.fail_json(msg=vim_fault)
            try:
                changed, result = wait_for_task(task)
                result = "Host removed from vCenter '%s'" % self.vcenter
            except TaskError as task_error:
                self.module.fail_json(
                    msg="Failed to remove the host from vCenter '%s' : %s" % (self.vcenter, to_native(task_error))
                )
        self.module.exit_json(changed=changed, result=str(result))

    def put_host_in_maintenance_mode(self, host_object):
        """Put host in maintenance mode, if not already"""
        if not host_object.runtime.inMaintenanceMode:
            try:
                try:
                    maintenance_mode_task = host_object.EnterMaintenanceMode_Task(300, True, None)
                except vim.fault.InvalidState as invalid_state:
                    self.module.fail_json(
                        msg="The host is already in maintenance mode : %s" % to_native(invalid_state)
                    )
                except vim.fault.Timedout as timed_out:
                    self.module.fail_json(
                        msg="The maintenance mode operation timed out : %s" % to_native(timed_out)
                    )
                except vim.fault.Timedout as timed_out:
                    self.module.fail_json(
                        msg="The maintenance mode operation was canceled : %s" % to_native(timed_out)
                    )
                wait_for_task(maintenance_mode_task)
            except TaskError as task_err:
                self.module.fail_json(
                    msg="Failed to put the host in maintenance mode : %s" % to_native(task_err)
                )

    def get_parent_type(self, host_object):
        """
            Get the type of the parent object
            Returns: string with 'folder' or 'cluster'
        """
        object_type = None
        # check 'vim.ClusterComputeResource' first because it's also an
        # instance of 'vim.ComputeResource'
        if isinstance(host_object.parent, vim.ClusterComputeResource):
            object_type = 'cluster'
        elif isinstance(host_object.parent, vim.ComputeResource):
            object_type = 'folder'
        return object_type

    def state_update_host(self):
        """Move host to a cluster or a folder, or vice versa"""
        changed = True
        result = None
        reconnect = False

        # Check if the host is disconnected if reconnect disconnected hosts is true
        if self.reconnect_disconnected and self.host_update.runtime.connectionState == 'disconnected':
            reconnect = True

        # Check parent type
        parent_type = self.get_parent_type(self.host_update)

        if self.folder_name:
            if self.module.check_mode:
                if reconnect or self.state == 'add_or_reconnect' or self.state == 'reconnect':
                    result = "Host would be reconnected and moved to folder '%s'" % self.folder_name
                else:
                    result = "Host would be moved to folder '%s'" % self.folder_name
            else:
                # Reconnect the host if disconnected or if specified by state
                if reconnect or self.state == 'add_or_reconnect' or self.state == 'reconnect':
                    self.reconnect_host(self.host_update)
                try:
                    try:
                        if parent_type == 'folder':
                            # Move ESXi host from folder to folder
                            task = self.folder.MoveIntoFolder_Task([self.host_update.parent])
                        elif parent_type == 'cluster':
                            self.put_host_in_maintenance_mode(self.host_update)
                            # Move ESXi host from cluster to folder
                            task = self.folder.MoveIntoFolder_Task([self.host_update])
                    except vim.fault.DuplicateName as duplicate_name:
                        self.module.fail_json(
                            msg="The folder already contains an object with the specified name : %s" %
                            to_native(duplicate_name)
                        )
                    except vim.fault.InvalidFolder as invalid_folder:
                        self.module.fail_json(
                            msg="The parent of this folder is in the list of objects : %s" %
                            to_native(invalid_folder)
                        )
                    except vim.fault.InvalidState as invalid_state:
                        self.module.fail_json(
                            msg="Failed to move host, this can be due to either of following :"
                            " 1. The host is not part of the same datacenter, 2. The host is not in maintenance mode : %s" %
                            to_native(invalid_state)
                        )
                    except vmodl.fault.NotSupported as not_supported:
                        self.module.fail_json(
                            msg="The target folder is not a host folder : %s" %
                            to_native(not_supported)
                        )
                    except vim.fault.DisallowedOperationOnFailoverHost as failover_host:
                        self.module.fail_json(
                            msg="The host is configured as a failover host : %s" %
                            to_native(failover_host)
                        )
                    except vim.fault.VmAlreadyExistsInDatacenter as already_exists:
                        self.module.fail_json(
                            msg="The host's virtual machines are already registered to a host in "
                            "the destination datacenter : %s" % to_native(already_exists)
                        )
                    changed, result = wait_for_task(task)
                except TaskError as task_error_exception:
                    task_error = task_error_exception.args[0]
                    self.module.fail_json(
                        msg="Failed to move host %s to folder %s due to %s" %
                        (self.esxi_hostname, self.folder_name, to_native(task_error))
                    )
                if reconnect or self.state == 'add_or_reconnect' or self.state == 'reconnect':
                    result = "Host reconnected and moved to folder '%s'" % self.folder_name
                else:
                    result = "Host moved to folder '%s'" % self.folder_name
        elif self.cluster_name:
            if self.module.check_mode:
                result = "Host would be moved to cluster '%s'" % self.cluster_name
            else:
                if parent_type == 'cluster':
                    # Put host in maintenance mode if moved from another cluster
                    self.put_host_in_maintenance_mode(self.host_update)
                resource_pool = None
                try:
                    try:
                        task = self.cluster.MoveHostInto_Task(
                            host=self.host_update, resourcePool=resource_pool
                        )
                    except vim.fault.TooManyHosts as too_many_hosts:
                        self.module.fail_json(
                            msg="No additional hosts can be added to the cluster : %s" % to_native(too_many_hosts)
                        )
                    except vim.fault.InvalidState as invalid_state:
                        self.module.fail_json(
                            msg="The host is already part of a cluster and is not in maintenance mode : %s" %
                            to_native(invalid_state)
                        )
                    except vmodl.fault.InvalidArgument as invalid_argument:
                        self.module.fail_json(
                            msg="Failed to move host, this can be due to either of following :"
                            " 1. The host is is not a part of the same datacenter as the cluster,"
                            " 2. The source and destination clusters are the same : %s" %
                            to_native(invalid_argument)
                        )
                    changed, result = wait_for_task(task)
                except TaskError as task_error_exception:
                    task_error = task_error_exception.args[0]
                    self.module.fail_json(
                        msg="Failed to move host to cluster '%s' due to : %s" %
                        (self.cluster_name, to_native(task_error))
                    )
                if reconnect or self.state == 'add_or_reconnect' or self.state == 'reconnect':
                    result = "Host reconnected and moved to cluster '%s'" % self.cluster_name
                else:
                    result = "Host moved to cluster '%s'" % self.cluster_name

        self.module.exit_json(changed=changed, msg=str(result))

def main():
    """Main"""
    argument_spec = vmware_argument_spec()
    argument_spec.update(
        datacenter_name=dict(type='str', required=True, aliases=['datacenter']),
        cluster_name=dict(type='str', aliases=['cluster']),
        esxi_hostname=dict(type='str', required=True),
        esxi_username=dict(type='str'),
        esxi_password=dict(type='str', no_log=True),
        esxi_ssl_thumbprint=dict(type='str', default='', aliases=['ssl_thumbprint']),
        fetch_ssl_thumbprint=dict(type='bool', default=True),
        state=dict(default='present',
                   choices=['present', 'absent', 'add_or_reconnect', 'reconnect'],
                   type='str'),
        folder=dict(type='str', aliases=['folder_name']),
        add_connected=dict(type='bool', default=True),
        force_connection=dict(type='bool', default=True),
        reconnect_disconnected=dict(type='bool', default=True),
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=[
            ['state', 'present', ['esxi_username', 'esxi_password']],
            ['state', 'add_or_reconnect', ['esxi_username', 'esxi_password']]
        ],
        required_one_of=[
            ['cluster_name', 'folder'],
        ],
        mutually_exclusive=[
            ['cluster_name', 'folder'],
        ]
    )

    vmware_host = VMwareHost(module)
    vmware_host.process_state()

if __name__ == '__main__':
    main()


text:
module SessionsHelper
    # Logs in the given account.
    def log_in(account)
        session[:account_id] = account.id
    end

    # Returns the current logged-in user (if any).
    def current_account
        @current_account ||= Account.find_by(id: session[:account_id])
    end

    # Returns true if the account is logged in, false otherwise.
    def logged_in?
        !current_account.nil?
    end

    # Logs out the current account.
    def log_out
        session.delete(:account_id)
        @current_account = nil
    end
end


text:
<?php
/**
 * This file tests Ganalytics.
 */

namespace SendGrid\Tests\Unit;

use PHPUnit\Framework\TestCase;
use SendGrid\Mail\Ganalytics;
use SendGrid\Mail\TypeException;

/**
 * This file tests Ganalytics.
 *
 * @package SendGrid\Tests
 */
class GanalyticsTest extends TestCase
{
    public function testConstructor()
    {
        $ganalytics = new Ganalytics(true, 'utm_source', 'utm_medium', 'utm_term', 'utm_content', 'utm_campaign');

        $this->assertInstanceOf(Ganalytics::class, $ganalytics);
        $this->assertTrue($ganalytics->getEnable());
        $this->assertSame('utm_source', $ganalytics->getCampaignSource());
        $this->assertSame('utm_medium', $ganalytics->getCampaignMedium());
        $this->assertSame('utm_term', $ganalytics->getCampaignTerm());
        $this->assertSame('utm_content', $ganalytics->getCampaignContent());
        $this->assertSame('utm_campaign', $ganalytics->getCampaignName());
    }

    public function testSetEnable()
    {
        $ganalytics = new Ganalytics();
        $ganalytics->setEnable(true);

        $this->assertTrue($ganalytics->getEnable());
    }

    public function testSetEnableOnInvalidType()
    {
        $this->expectException(TypeException::class);
        $this->expectExceptionMessageMatches('/"\$enable" must be a boolean/');

        $ganalytics = new Ganalytics();
        $ganalytics->setEnable('invalid_bool');
    }

    public function testSetCampaignContent()
    {
        $ganalytics = new Ganalytics();
        $ganalytics->setCampaignContent('utm_content');

        $this->assertSame('utm_content', $ganalytics->getCampaignContent());
    }

    public function testSetCampaignContentOnInvalidType()
    {
        $this->expectException(TypeException::class);
        $this->expectExceptionMessageMatches('/"\$utm_content" must be a string/');

        $ganalytics = new Ganalytics();
        $ganalytics->setCampaignContent(123);
    }

    public function testSetCampaignTerm()
    {
        $ganalytics = new Ganalytics();
        $ganalytics->setCampaignTerm('utm_term');

        $this->assertSame('utm_term', $ganalytics->getCampaignTerm());
    }

    public function testSetCampaignTermOnInvalidType()
    {
        $this->expectException(TypeException::class);
        $this->expectExceptionMessageMatches('/"\$utm_term" must be a string/');

        $ganalytics = new Ganalytics();
        $ganalytics->setCampaignTerm(123);
    }

    public function testSetCampaignMedium()
    {
        $ganalytics = new Ganalytics();
        $ganalytics->setCampaignMedium('utm_medium');

        $this->assertSame('utm_medium', $ganalytics->getCampaignMedium());
    }

    public function testSetCampaignMediumOnInvalidType()
    {
        $this->expectException(TypeException::class);
        $this->expectExceptionMessageMatches('/"\$utm_medium" must be a string/');

        $ganalytics = new Ganalytics();
        $ganalytics->setCampaignMedium(123);
    }

    public function testSetCampaignSource()
    {
        $ganalytics = new Ganalytics();
        $ganalytics->setCampaignSource('utm_campaign');

        $this->assertSame('utm_campaign', $ganalytics->getCampaignSource());
    }

    public function testSetCampaignSourceOnInvalidType()
    {
        $this->expectException(TypeException::class);
        $this->expectExceptionMessageMatches('/"\$utm_source" must be a string/');

        $ganalytics = new Ganalytics();
        $ganalytics->setCampaignSource(123);
    }

    public function testSetCampaignName()
    {
        $ganalytics = new Ganalytics();
        $ganalytics->setCampaignName('utm_campaign_name');

        $this->assertSame('utm_campaign_name', $ganalytics->getCampaignName());
    }

    public function testSetCampaignNameOnInvalidType()
    {
        $this->expectException(TypeException::class);
        $this->expectExceptionMessageMatches('/"\$utm_campaign" must be a string/');

        $ganalytics = new Ganalytics();
        $ganalytics->setCampaignName(123);
    }
}


text:
<?php

namespace BitsTheater\costumes\CursorCloset;
use BitsTheater\costumes\WornForPagerManagement;
{//namespace begin

/**
 * Acts as a container for, and iterator over, a set of paged records.
 * Created a new class to descend from in case existing ARecordSet descendants
 * already implement WornForPagerManagement trait. Reason is that trait defines
 * some properties and if a descendant also defines that trait, PHP throws
 * an error about having properties already defined in it. By creating a new
 * class to descend from, classes can choose whether or not they inherit
 * the trait and therefore we avoid breaking existing code.
 *
 * <pre>
 * $theSet = RecordSet::create($this->getDirector())
 *     ->setDataFromPDO($pdo)
 *     ;
 * </pre>
 *
 * @since BitsTheater v4.1.0
 */
abstract class ARecordSetPaged extends ARecordSet
{
	use WornForPagerManagement {
		setPagerEnabled as protected traitSetPagerEnabled;
		setPagerTotalRowCount as protected traitSetPagerTotalRowCount;
	}

	/**
	 * Enable/disable the pager.
	 * @param boolean $aEnabled - desired state of pager.
	 * @return $this Returns $this for chaining.
	 */
	public function setPagerEnabled( $aEnabled )
	{
		$this->traitSetPagerEnabled($aEnabled);
		if ( !$this->isPagerEnabled() )
			$this->total_count = null;
		return $this;
	}

	/**
	 * Set the query total regardless of paging.
	 * @param number $aTotalRowCount - the total.
	 * @return $this Returns $this for chaining.
	 */
	public function setPagerTotalRowCount( $aTotalRowCount )
	{
		$this->traitSetPagerTotalRowCount($aTotalRowCount);
		$this->total_count = $this->getPagerTotalRowCount();
		return $this;
	}

}//end class

}//end namespace


text:
<!DOCTYPE html><html><head><meta charset="utf-8" />
<meta http-equiv="refresh" content="0;url=/place/luxembourg/weather/" />
</head></html>


text:
package com.amazonaws.services.iotsitewise.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.iotsitewise.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * AssetModelStatus JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AssetModelStatusJsonUnmarshaller implements Unmarshaller<AssetModelStatus, JsonUnmarshallerContext> {

    public AssetModelStatus unmarshall(JsonUnmarshallerContext context) throws Exception {
        AssetModelStatus assetModelStatus = new AssetModelStatus();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("state", targetDepth)) {
                    context.nextToken();
                    assetModelStatus.setState(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("error", targetDepth)) {
                    context.nextToken();
                    assetModelStatus.setError(ErrorDetailsJsonUnmarshaller.getInstance().unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return assetModelStatus;
    }

    private static AssetModelStatusJsonUnmarshaller instance;

    public static AssetModelStatusJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new AssetModelStatusJsonUnmarshaller();
        return instance;
    }
}


text:
require 'rails_helper'

RSpec.describe "Endpoints", type: :request do
  describe "GET /endpoints" do
    it "works! (now write some real specs)" do
      get root_path
      expect(response).to have_http_status(200)
    end
  end

  describe "GET /api/endpoints/graph" do

    before do
      FactoryBot.create_list(:endpoint, 100)
      FactoryBot.create_list(:relation, 50)
    end

    it "works! (now write some real specs)" do
      get api_endpoints_graph_path

      expect(response).to have_http_status(200)
    end

    it "returns json data" do
      get api_endpoints_graph_path

      json = JSON.parse(response.body)

      expect(json.size).to eq 150
      expect(response).to have_http_status(200)
    end
  end
end


text:
A PHP client for the [Sift Science][1] REST API.

Note: Sift Science now offer their own PHP bindings [here][2].

[![Build Status](https://travis-ci.org/99designs/sipht.png)](https://travis-ci.org/99designs/sipht)

This client supports the three basic operations exposed by the Sift API: posting
events, labelling users and fetching scores.

The currently supported API version is **`v203`**.

## Instantiating a client

Interactions with the API occur via `Sift\Client`. You instantiate a client by
passing your API key to its constructor:
```php
$client = new Sift\Client('my-api-key');
```

The following errors may be thrown by any client request:

 * `Sift\Exception\BadRequestException`: HTTP 40x; the request was rejected by
    the API

 * `Sift\Exception\ServerErrorException`: HTTP 50x; the API endpoint suffered
    some internal problem

 * `Sift\Exception\HttpException`: any other exception generated in the course
    of making the HTTP request (e.g. too many redirects)

## Posting events

Create instances of `Sift\Event`, e.g.:
```php
$event = new Sift\Event(array(
    '$type' => Sift\Event::TYPE_TRANSACTION,
    '$user_id' => '1234',
    // ...
));
```

Alternatively, factory constructors are provided for each event type:
```php
$event = Sift\Event::transactionEvent(array(
    '$user_id' => '1234',
    // ...
));
```

Then post the event via `Sift\Client::postEvent()`:
```php
$response = $client->postEvent($event);
```

See https://siftscience.com/docs/references/events-api for more information on
posting event data.

## Labelling users

Create label objects using the factory methods of `Sift\Label`, e.g.:
```php
// Label a user as fraudulent, optionally specifying reason codes and an explanation:
$reasons = array(Sift\Label::REASON_SPAM);
$label = Sift\Label::bad($reasons, 'User engaged in phishing attack')

// Alternatively, correct a false positive by labelling a user as non-fraudulent:
$good = Sift\Label::good('Mistakenly identified as fraudulent');
```

Then post the event via `Sift\Client::labelUser()`:
```php
$response = $client->labelUser('some-user-id', $label);
```

See https://siftscience.com/docs/references/labels-api for more information on
labelling users.

## Fetching scores

Fetch fraud score data for a user via `Sift\Client::userScore()`:
```php
$score = $client->userScore('some-user-id');
```

This returns an instance of `Sift\Score`. Note that if no events have been
captured for the given user, a `Sift\Exception\ScoreException` will be thrown.

See https://siftscience.com/docs/getting-scores for more information on fetching
user fraud scores.

 [1]: https://siftscience.com/
 [2]: https://github.com/SiftScience/sift-php


text:
[![Build Status](https://travis-ci.org/goglue/eventmanager.svg?branch=master)](https://travis-ci.org/goglue/eventmanager)

This library implements an event manager for common usages

### How to use

#### Interfaces
- The subscriber interface

```go
type Subscriber interface {
    Update(interface{})
}

// Example for a subscriber
type Subscriber int

func (s Subscriber) Update(eventState interface{}) {
    // Do whatever with the event-state you've received
}
```

- Recorder: After dispatching an event a single snapshot will be taken for th

```go
type Recorder interface{
    Snapshot(eventName string, eventState interface{}, on time.Time)
}
```

#### Example

```go
memory := NewMemoryStorage()
dispatcher := NewDispatcher()

var subscriber Subscriber = 1

eventManager := NewEventManager(memory, dispatcher, nil)
eventManager.Attach("randomEventName", subscriber)
eventManager.Dispatch("randomEventName", "any value can be dispatched")
```

There is also another method to dispatch the event for the subscribers in go routines:

```go
eventManager.GoDispatch("randomEventName", "any value can be dispatched")
```


text:
<!DOCTYPE html><html><head><meta charset="utf-8" />
<meta http-equiv="refresh" content="0;url=/place/ecuador/emissions/" />
</head></html>


text:
package mapdemo;

import java.util.*;

public class VerjaardagsKalender {
    private Map<String, Collection<Verjaardag>> verjaardagen;

    // Vul de onderstaande methoden aan!

    public VerjaardagsKalender() {
        this.verjaardagen = new HashMap<>();
    }

    public void voegToe(Verjaardag verjaardag) {
        // Calc key
        String sleutel = getSleutel(verjaardag);

        // Check if we don't got the key
        if (!this.verjaardagen.containsKey(sleutel)) {
            verjaardagen.put(sleutel, new ArrayList<Verjaardag>());
        }

        this.verjaardagen.get(sleutel).add(verjaardag);
    }

    public void verwijder(Verjaardag verjaardag) {
        // Calc key
        String sleutel = getSleutel(verjaardag);

        if (this.verjaardagen.get(sleutel) != null) {
            if (this.verjaardagen.get(sleutel).contains(verjaardag)) {
                this.verjaardagen.get(sleutel).remove(verjaardag);
            }

            // Check if count is 0
            if (this.verjaardagen.get(sleutel).isEmpty()) {
                this.verjaardagen.remove(sleutel);
            }
        }
    }

    public Collection<Verjaardag> zoekOpVerjaardag(String sleutel) {
        Collection<Verjaardag> results = this.verjaardagen.get(sleutel);

        if (results != null) {
            return results;
        }

        return null;
    }

    @Override
    public String toString() {
        return "" + verjaardagen;
    }

    private String getSleutel(Verjaardag verjaardag) {
        String dag = "" + verjaardag.getDag();
        String maand = "" + verjaardag.getMaand();

        if (verjaardag.getDag() < 10) {
            dag = "0" + verjaardag.getDag();
        }

        if (verjaardag.getMaand() < 10) {
            maand = "0" + verjaardag.getMaand();
        }

        return String.format("%s/%s", dag, maand);
    }
}


text:
type LocaleData = Record<string, never>
type ConvertLocaleConfig<T extends LocaleData = LocaleData> = Record<
  string,
  T
>;
type LocaleConfig<T extends LocaleData = LocaleData> = Record<string, Partial<T>>;

export interface GetLocalesOptions<T extends LocaleData> {
    app: unknown;
    default: ConvertLocaleConfig<T>;
    config?: LocaleConfig<T> | undefined;
    name?: string;
}

export const getLocales = <T extends LocaleData>({
    app,
    name,
    default: defaultLocalesConfig,
    config: userLocalesConfig = {},
}: GetLocalesOptions<T>): ConvertLocaleConfig<T> => {
    return defaultLocalesConfig;
};


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.sitebkns.display.SecondActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="16dp" />
</android.support.constraint.ConstraintLayout>


text:
package com.americanminion;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;

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

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * A login screen that offers login via phone/password.
 */
public class LoginActivity extends AppCompatActivity implements Constants{

    // UI references.
    private Handler mHandler;
    private EditText mPhoneView;
    private EditText mPasswordView;
    private SharedPreferences mSharedPreferences;
    ProgressDialog progress;
    SharedPreferences sharedPreferences;
    public String API_LINK;
    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        // Set up the login form.
        mPhoneView = (EditText) findViewById(R.id.phone);
        mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        mPasswordView = (EditText) findViewById(R.id.password);
        imageView = (ImageView) findViewById(R.id.imageView);

        progress = new ProgressDialog(this);

        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        API_LINK = sharedPreferences.getString(API_LINK_TEXT, "http://192.168.1.6:5000/");

        if(mSharedPreferences.getString(USER_ID, null) != null){

            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        }

        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });

        imageView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                new MaterialDialog.Builder(LoginActivity.this)
                        .title("Enter IP")
                        .content("for eg http://192.168.1.120:5000/")
                        .inputType(InputType.TYPE_CLASS_TEXT)
                        .input("for eg http://192.168.1.120:5000/", "", new MaterialDialog.InputCallback() {
                            @Override
                            public void onInput(MaterialDialog dialog, CharSequence input) {
                                // Do something
                                sharedPreferences.
                                        edit().
                                        putString(API_LINK_TEXT, input.toString()).apply();
                            }
                        }).show();

            }
        });

        Button mphoneSignInButton = (Button) findViewById(R.id.phone_sign_in_button);
        mphoneSignInButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });

        mHandler = new Handler(Looper.getMainLooper());

        getSupportActionBar().hide();
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid phone, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {

        // Reset errors.
        mPhoneView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        String phone = mPhoneView.getText().toString();
        String password = mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid phone address.
        if (TextUtils.isEmpty(phone)) {
            mPhoneView.setError(getString(R.string.error_field_required));
            focusView = mPhoneView;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            Login(phone, password);
        }
    }

    /**
     * Upload data to server
     */
    public void Login(String mphone, String mPassword) {

        progress.setTitle("Please wait");
        progress.setMessage("Logging In...");
        progress.show();

        // to fetch city names
        String uri = API_LINK +"add-user?"+ "name="+ mphone + "&password=" + mPassword;
        Log.e("CALLING : ", uri);

        //Set up client
        OkHttpClient client = new OkHttpClient();
        //Execute request
        final Request request = new Request.Builder()
                .url(uri)
                .build();

        //Setup callback
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("Request Failed", "Message : " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {

                final String res = response.body().string();
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {

                        Log.e("result", res);
                        try {
                            JSONObject object = new JSONObject(res);
                            String status = object.getString("success");

                            if (status.equals("true")) {
                                String access_token = object.getString("user_id");
                                mSharedPreferences
                                        .edit()
                                        .putString(USER_ID, access_token)
                                        .apply();
                                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                startActivity(intent);
                                finish();
                            } else {
                                mPasswordView.setError(status);
                                mPasswordView.requestFocus();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Toast.makeText(LoginActivity.this, "Some error occurred", Toast.LENGTH_LONG).show();

                        }
                        progress.dismiss();

                    }
                });
            }
        });
    }
}


text:
define([
    'dojo/_base/declare',
    'dojo/_base/array',
    'dojo/_base/lang',
    'dojo/_base/html',
    'dojo/dom-style',
    'dojo/on',
    'dojo/query',
    'dijit/form/Select',
    'dijit/form/ValidationTextBox',
    'dijit/_WidgetsInTemplateMixin',
    './FeaturelayerSource',
    './FieldPicker',
    'jimu/BaseWidgetSetting',
    'jimu/dijit/Message',
    'jimu/dijit/Popup',
    'jimu/LayerInfos/LayerInfos',
    'jimu/dijit/SimpleTable'
  ],
  function(
    declare, array, lang, html, domStyle, on, query,
    Select, ValidationTextBox, _WidgetsInTemplateMixin,
    FeaturelayerSource, FieldPicker, BaseWidgetSetting, Message, Popup, LayerInfos
  ) {
    return declare([BaseWidgetSetting, _WidgetsInTemplateMixin], {

      //these two properties is defined in the BaseWidget
      baseClass: 'jimu-widget-IMT-setting',
      opLayers: [],
      curRow: null,

      postCreate: function() {
        this.inherited(arguments);
        // this._setLayers();
        // this._setTypes();
        this._getAllLayers();
        this.own(on(this.btnAddTab, 'click', lang.hitch(this, this._addTabRow)));
        this.own(on(this.tabTable, 'actions-edit', lang.hitch(this, function(tr) {
          this._onEditLayerClicked(tr);
        })));
      },

      startup: function() {
        this.inherited(arguments);
        //this.setConfig(this.config);
      },

      setConfig: function(config) {
        this.config = config;

        if (this.config.distanceUnits) {
          this.selectUnits.set("value", this.config.distanceUnits);
        }

        if (this.config.maxDistance) {
          this.txt_maximumDistance.set("value", this.config.maxDistance);
        }

        if (this.config.enableRouting) {
          this.chk_routing.set('value', true);
        }

        this.tabTable.clear();
        for (var i = 0; i < this.config.tabs.length; i++) {
          var aTab = this.config.tabs[i];
          if (aTab.type === this.config.special_layer.value) {
            this.chk_weather.set('value', true);
            this.weatherTabAdditionalLayers = aTab.layers;
            this.currentlySelectedLayer.innerHTML = this.weatherTabAdditionalLayers;
          } else {
            this._populateTabTableRow(aTab);
          }
        }

        this.buffer_lbl.set("value", this.config.bufferLabel ?
          this.config.bufferLabel : this.nls.buffer_lbl);

        this.buffer_max.set("value", this.config.bufferRange.maximum);
        this.buffer_min.set("value", this.config.bufferRange.minimum);

        if (this.config.disableLayerManagement) {
          this.chk_disable.set('value', true);
        }
      },

      getConfig: function() {

        this.config.distanceUnits = this.selectUnits.value;

        if (this.txt_maximumDistance.value) {
          this.config.maxDistance = this.txt_maximumDistance.value;
        }

        if (this.chk_routing.checked) {
          this.config.enableRouting = true;
        } else {
          this.config.enableRouting = false;
        }

        var tabs = [];

        var aTab = {};
        if (this.chk_weather.checked) {
          aTab.label = this.config.special_layer.label;
          aTab.type = this.config.special_layer.value;
          aTab.layers = this.weatherTabAdditionalLayers;
          aTab.url = this.config.special_layer.url;
          tabs.push(aTab);
        }

        //solutions: added to check fields then append to the tab struct object.
        //this.updateSummaryFields();

        var trs = this.tabTable.getRows();
        array.forEach(trs, lang.hitch(this, function(tr) {
          var selectLayers = tr.selectLayers;
          var selectTypes = tr.selectTypes;
          var labelText = tr.labelText;
          aTab = {};
          aTab.label = labelText.value;
          aTab.type = selectTypes.value;
          aTab.layers = selectLayers.value;
          if (tr.tabInfo && tr.tabInfo.advConfig) {
            aTab.advConfig = tr.tabInfo.advConfig;
          }
          tabs.push(aTab);
        }));

        this.config.tabs = tabs;
        this.config.bufferLabel = this.buffer_lbl.value;
        this.config.bufferRange.maximum = this.buffer_max.value;
        this.config.bufferRange.minimum = this.buffer_min.value;

        if (this.chk_disable.checked) {
          this.config.disableLayerManagement = true;
        } else {
          this.config.disableLayerManagement = false;
        }

        return this.config;
      },

      _getAllLayers: function() {
        if (this.map.itemId) {
          LayerInfos.getInstance(this.map, this.map.itemInfo)
            .then(lang.hitch(this, function(operLayerInfos) {
              this.opLayers = operLayerInfos;
              this._setLayers();
              this._setTypes();
              this.setConfig(this.config);
            }));
        }
      },

      _setLayers: function() {
        var options = [];
        array.forEach(this.opLayers._layerInfos, lang.hitch(this, function(OpLyr) {
          if (OpLyr.newSubLayers.length > 0) {
            this._recurseOpLayers(OpLyr.newSubLayers, options);
          } else {
            if (this._validateLayer(OpLyr)) {
              options.push({
                label: OpLyr.title,
                value: OpLyr.title
              });
            }
          }
        }));

        if (options.length === 0) {
          domStyle.set(this.btnAddTab, "display", "none");
          new Message({
            message: this.nls.missingLayerInWebMap
          });
          return;
        }

        this.layer_options = lang.clone(options);
      },

      _recurseOpLayers: function(pNode, pOptions) {
        var nodeGrp = pNode;
        array.forEach(nodeGrp, lang.hitch(this, function(Node) {
          if (Node.newSubLayers.length > 0) {
            this._recurseOpLayers(Node.newSubLayers, pOptions);
          } else {
            if (this._validateLayer(Node)) {
              pOptions.push({
                label: Node.title,
                value: Node.title
              });
            }
          }
        }));
      },

      _validateLayer: function(lyr) {
        var validUrl = null;
        if (lyr.layerObject && lyr.layerObject.url) {
          var url = lyr.layerObject.url;
          if (url.indexOf('MapServer') > -1 || url.indexOf('FeatureServer') > -1) {
            validUrl = url;
          }
        }
        return validUrl;
      },

      _setTypes: function() {
        this.analysis_options = [{
          value: 'closest',
          label: this.nls.closest
        }, {
          value: 'proximity',
          label: this.nls.proximity
        }, {
          value: 'summary',
          label: this.nls.summary
        }];
      },

      _populateTabTableRow: function(tabInfo) {
        var result = this.tabTable.addRow({});
        if (result.success && result.tr) {
          var tr = result.tr;
          this._addTabLayers(tr);
          this._addTabTypes(tr);
          this._addTabLabel(tr);
          tr.selectLayers.set("value", tabInfo.layers);
          tr.selectTypes.set("value", tabInfo.type);
          tr.labelText.set("value", tabInfo.label);
          tr.tabInfo = tabInfo;
        }
      },

      _addTabRow: function() {
        var result = this.tabTable.addRow({});
        if (result.success && result.tr) {
          var tr = result.tr;
          this._addTabLayers(tr);
          this._addTabTypes(tr);
          this._addTabLabel(tr);
        }
      },

      _addTabLayers: function(tr) {
        var lyrOptions = lang.clone(this.layer_options);
        var td = query('.simple-table-cell', tr)[0];
        if (td) {
          html.setStyle(td, "verticalAlign", "middle");
          var tabLayers = new Select({
            style: {
              width: "100%",
              height: "30px"
            },
            options: lyrOptions
          });
          tabLayers.placeAt(td);
          tabLayers.startup();
          tr.selectLayers = tabLayers;
        }
      },

      _addTabTypes: function(tr) {
        var typeOptions = lang.clone(this.analysis_options);
        var td = query('.simple-table-cell', tr)[1];
        if (td) {
          html.setStyle(td, "verticalAlign", "middle");
          var tabTypes = new Select({
            style: {
              width: "100%",
              height: "30px"
            },
            options: typeOptions
          });
          tabTypes.placeAt(td);
          tabTypes.startup();
          tr.selectTypes = tabTypes;
        }
      },

      _addTabLabel: function(tr) {
        var td = query('.simple-table-cell', tr)[2];
        html.setStyle(td, "verticalAlign", "middle");
        var labelTextBox = new ValidationTextBox({
          style: {
            width: "100%",
            height: "30px"
          }
        });
        labelTextBox.placeAt(td);
        labelTextBox.startup();
        tr.labelText = labelTextBox;
      },

      _onBtnSelectLayersClicked: function() {
        var args = {
          nls: this.nls,
          map: this.map,
          config: this.config,
          weatherTabAdditionalLayers: this.weatherTabAdditionalLayers,
          appConfig: this.appConfig
        };

        var sourceDijit = new FeaturelayerSource(args);

        var popup = new Popup({
          width: 830,
          height: 560,
          content: sourceDijit,
          titleLabel: this.nls.selectLayers
        });

        this.own(on(sourceDijit, 'ok', lang.hitch(this, function(items) {
          this.weatherTabAdditionalLayers = items;
          this.currentlySelectedLayer.innerHTML = this.weatherTabAdditionalLayers;
          sourceDijit.destroy();
          sourceDijit = null;
          popup.close();

        })));

        this.own(on(sourceDijit, 'cancel', lang.hitch(this, function() {
          sourceDijit.destroy();
          sourceDijit = null;
          popup.close();
        })));
      },

      _onEditLayerClicked: function(tr) {

        // var parameters = tr.selectLayers;
        // for (var i = 0; i < this.config.tabs.length; i++) {
        //   var aTab = this.config.tabs[i];
        //   if (aTab.type === tr.selectTypes.value && aTab.layers === tr.selectLayers.value) {
        //     parameters = aTab;
        //     break;
        //   }
        // }
        this.curRow = tr;

        var aTab = tr.tabInfo;
        if (!aTab) {
          aTab = {};
          aTab.label = tr.labelText.value;
          aTab.type = tr.selectTypes.value;
          aTab.layers = tr.selectLayers.value;
          aTab.advConfig = {};
          tr.tabInfo = aTab;
        }
        if (aTab.type !== tr.selectTypes.value || aTab.layers !== tr.selectLayers.value) {
          aTab.type = tr.selectTypes.value;
          aTab.layers = tr.selectLayers.value;
          aTab.advConfig = {};
        }

        var args = {
          nls: this.nls,
          callerLayer: tr.selectLayers.value,
          callerTab: aTab,
          callerOpLayers: this.opLayers._layerInfos
        };

        var sourceDijit = new FieldPicker(args);

        var popup = new Popup({
          width: 830,
          height: 560,
          content: sourceDijit,
          titleLabel: this.nls.selectFields + ": " + tr.selectLayers.value
        });

        this.own(on(sourceDijit, 'ok', lang.hitch(this, function(data) {
          this.curRow.tabInfo.advConfig = data;
          this.curRow = null;
          //this.summaryFields.push(items);
          sourceDijit.destroy();
          sourceDijit = null;
          popup.close();
        })));

        this.own(on(sourceDijit, 'cancel', lang.hitch(this, function() {
          this.curRow = null;
          sourceDijit.destroy();
          sourceDijit = null;
          popup.close();
        })));

      }

    });
  });


text:
layout: post
date: 2016-10-09
title: "Enzoani Hadley Sleeveless Chapel Train Mermaid/Trumpet"
category: Enzoani
tags: [Enzoani,Mermaid/Trumpet,Sweetheart,Chapel Train,Sleeveless]
---
### Enzoani Hadley
Just **$279.99**
###   Sleeveless Chapel Train Mermaid/Trumpet

BRANDS	Enzoani

Silhouette	Mermaid/Trumpet

Neckline	Sweetheart

Hemline/Train	Chapel Train

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/enzoani/5101-enzoani-hadley.html](https://www.readybrides.com/en/enzoani/5101-enzoani-hadley.html)


text:
<?php

class ImagePointOfInterestExtension extends DataExtension
{
    private static $has_one = array(
        'POIImage' => 'Image',
    );
}


text:
<!DOCTYPE html>

    <title>Array-Based List Insertion Proficiency Exercise</title>

        <var id="arr_size">Khan.randRange(4, 6)</var>
        <var id="insert_value">Khan.randRange(0, 999)</var>
        <var id="insert_pos">Khan.randRange(0, arr_size-1)</var>
        <var id="JSAV">alistInsertPRO.initJSAV(arr_size, insert_pos,insert_value)</var>

Your task in this exercise is to show the
            behavior for array-based list insertion.
            In the array displayed below, the "current" position is
            <var>insert_pos</var>.

The value to insert is <var>insert_value</var>,
              and it is to be inserted into the "current" position.

To move an element, click on it (to highlight it), then
              click on where you want it to go. You can insert the new
              value <var>insert_value</var> into a highlighted
              array position by clicking the "Insert" button.

            <input id="reset" type="button" value="Reset" />
            <input id="insert" type="button" value="Insert" />

 [alistInsertPRO.userInput]

              if (!alistInsertPRO.checkAnswer() && !guess[0]) {
                return ""; // User did not click, and correct answer is not
                           // initial array state
              } else { return alistInsertPRO.checkAnswer(); }

To shift elements after "current" one position to the
              right, the first step could be swapping element
              <var>arr_size - 1</var> with position <var>arr_size</var>

Then, keep swapping element i with i+1 until you make
              "current" empty for insertion

Insert value to "current" position