text:
import * as types from '../mutation-types'

// init state
const state = {
    'isShowSideBar': false,
    'isShowMask': false
}

// mutations
const mutations = {
    [types.SHOW_SIDEBAR](state, {isShowSideBar,isShowMask}) {
        state.isShowSideBar = isShowSideBar
        state.isShowMask = isShowMask
    }
}

export default {
    state,
    mutations
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef NX_CLOTHING_PHYSICAL_MESH_H
#define NX_CLOTHING_PHYSICAL_MESH_H

#include "NxApexInterface.h"
#include "NxApexUserProgress.h"

namespace physx
{
namespace apex
{

/**
\brief Constrain coefficients of the physical mesh vertices
*/
struct NxClothingConstrainCoefficients
{
	PxF32 maxDistance;				///< \brief Maximum distance a vertex is allowed to move
	PxF32 collisionSphereRadius;	///< \brief Backstop sphere radius
	PxF32 collisionSphereDistance;	///< \brief Backstop sphere distance
};

PX_PUSH_PACK_DEFAULT

/**
\brief Contains the data for handing out statistics about a NxClothingPhysicalMesh
*/
struct NxClothingPhysicalMeshStats
{
	/// the number of bytes allocated for the physical mesh
	PxU32	totalBytes;
	/// the number of vertices
	PxU32	numVertices;
	/// the number of indices
	PxU32	numIndices;
};

/**
\brief Holder for a physical mesh, this can be generated through various ways (see single- and multi-layered clothing) or hand crafted
*/
class NxClothingPhysicalMesh : public NxApexInterface
{
public:
	/**
	\brief returns the number of vertices
	*/
	virtual physx::PxU32 getNumVertices() const = 0;

	/**
	\brief returns the number of incides
	*/
	virtual physx::PxU32 getNumIndices() const = 0;

	/**
	\brief writes the indices to a destination buffer

	\param [out] indexDestination	destination buffer where to write the indices
	\param [in] byteStride			stride of the destination buffer
	\param [in] numIndices			number of indices the buffer can hold. This can be smaller than getNumIndices()
	*/
	virtual void getIndices(void* indexDestination, physx::PxU32 byteStride, physx::PxU32 numIndices) const = 0;

	/**
	\brief returns whether the mesh is built out of tetrahedra or triangles
	*/
	virtual bool isTetrahedralMesh() const = 0;

	/**
	\brief This will simplify the current mesh.

	\param [in] subdivisions	used to derive the maximal length a new edge can get.

								Divide the bounding box diagonal by this value to get the maximal edge length for newly created edges

								Use 0 to not restrict the maximal edge length
	\param [in] maxSteps		The maximum number of edges to be considered for simplification.

								Use 0 to turn off
	\param [in] maxError		The maximal quadric error an edge can cause to be considered simplifyable.

								Use any value < 0 to turn off
	\param [in] progress		Callback class that will be fired every now and then to update a progress bar in the gui.
	\return The number of edges collapsed
	*/
	virtual void simplify(physx::PxU32 subdivisions, physx::PxI32 maxSteps, physx::PxF32 maxError, IProgressListener* progress) = 0;

	/**
	\brief Create a physical mesh from scratch

	Overwrites all vertices/indices, and invalidates all misc vertex buffers. vertices must be physx::PxVec3 and indices physx::PxU32.
	If driveChannels is NULL, all vertices are assigned to all drive channels (initialized to 0xffffffff)
	*/
	virtual void setGeometry(bool tetraMesh, physx::PxU32 numVertices, physx::PxU32 vertexByteStride, const void* vertices, const PxU32* driveChannels, physx::PxU32 numIndices, physx::PxU32 indexByteStride, const void* indices) = 0;

	// direct access to specific buffers
	/**
	\brief writes the indices into a user specified buffer.

	Returns false if the buffer doesn't exist.
	The buffer must be bigger than sizeof(physx::PxU32) * getNumIndices()
	*/
	virtual bool getIndices(physx::PxU32* indices, physx::PxU32 byteStride) const = 0;

	/**
	\brief Writes the vertex positions into a user specified buffer.

	Returns false if the buffer doesn't exist.
	The buffer must be bigger than sizeof(physx::PxVec3) * getNumVertices()
	*/
	virtual bool getVertices(physx::PxVec3* vertices, physx::PxU32 byteStride) const = 0;

	/**
	\brief Writes the normals into a user specified buffer.

	Returns false if the buffer doesn't exist.
	The buffer must be bigger than sizeof(physx::PxVec3) * getNumVertices()
	*/
	virtual bool getNormals(physx::PxVec3* normals, physx::PxU32 byteStride) const = 0;

	/**
	\brief Returns the number of bones per vertex.
	*/
	virtual physx::PxU32 getNumBonesPerVertex() const = 0;

	/**
	\brief Writes the bone indices into a user specified buffer.

	Returns false if the buffer doesn't exist.
	The buffer must be bigger than sizeof(physx::PxU16) * getNumVertices() * getNumBonesPerVertex().
	(numBonesPerVertex is the same as in the graphical mesh for LOD 0)

	The bytestride is applied only after writing numBonesPerVertex and thus must be >= sizoef(physx::PxU16) * numBonesPerVertex
	*/
	virtual bool getBoneIndices(physx::PxU16* boneIndices, physx::PxU32 byteStride) const = 0;

	/**
	\brief Writes the bone weights into a user specified buffer.

	Returns false if the buffer doesn't exist.
	The buffer must be bigger than sizeof(physx::PxF32) * getNumVertices() * getNumBonesPerVertex().
	(numBonesPerVertex is the same as in the graphical mesh for LOD 0)
	The bytestride is applied only after writing numBonesPerVertex and thus must be >= sizoef(physx::PxF32) * numBonesPerVertex
	*/
	virtual bool getBoneWeights(physx::PxF32* boneWeights, physx::PxU32 byteStride) const = 0;

	/**
	\brief Allocates and initializes the drive channels (master flags) of the physics mesh.

	This allows to set the drive channels directly on the physics mesh.
	*/
	virtual void allocateMasterFlagsBuffer() = 0;

	/**
	\brief Returns the masterFlag buffer pointer in order to edit the values.

	This allows to set values directly on the physics mesh.
	*/
	virtual PxU32* getMasterFlagsBuffer() = 0;

	/**
	\brief Allocates and initializes the constrain coefficients of the physics mesh.

	This allows to set the constrain coefficients like maxDistance directly on the physics mesh.
	If this is not called by the authoring tool, the constrain coefficients are read from the
	graphical mesh.
	*/
	virtual void allocateConstrainCoefficientBuffer() = 0;

	/**
	\brief Returns the constrain coefficient buffer pointer in order to edit the values.

	This allows to set the constrain coefficients like maxDistance directly on the physics mesh.
	*/
	virtual NxClothingConstrainCoefficients* getConstrainCoefficientBuffer() const = 0;

	/**
	\brief Writes the cloth constrain coefficients into a user specified buffer.

	Returns false if the buffer doesn't exist. The buffer must be bigger than sizeof(ClothingConstrainCoefficients) * getNumVertices().
	*/
	virtual bool getConstrainCoefficients(NxClothingConstrainCoefficients* coeffs, physx::PxU32 byteStride) const = 0;

	/**
	\brief Returns stats (sizes, counts) for the asset.  See NxClothingPhysicalMeshStats.
	*/
	virtual void getStats(NxClothingPhysicalMeshStats& stats) const = 0;

};

PX_POP_PACK

}
} // namespace physx::apex

#endif // NX_CLOTHING_PHYSICAL_MESH_H


text:
var Filer = require('../..');
var util = require('../lib/test-utils.js');
var expect = require('chai').expect;

describe("fs.Shell", function() {
  beforeEach(util.setup);
  afterEach(util.cleanup);

  it("is a function", function(done) {
    var fs = util.fs();
    expect(typeof fs.Shell).to.equal('function');

    done();
  });

  it('should return a FileSystemShell instance', function(done) {
    var fs = util.fs();
    var sh = new fs.Shell();

    expect(sh.prototype).to.deep.equal((new Filer.Shell(fs)).prototype);
    done();
  });

  it('should reflect changes to the prototype', function(done){
    var fs = util.fs();
    var sh = new fs.Shell();

    Filer.Shell.prototype.test = "foo";

    expect(sh.test).to.equal("foo");
    done();
  });
});


text:
import React, {Component} from 'react';
import HmqLayoutContainer from 'HmqLayout/container.js'
import initialLoad from 'utils/initialLoad'
import {setTheme} from 'store/entities/navigation/actions'

class HmqLayoutRoute extends Component {

  static prepareData(store) {
    if(initialLoad()) return;
    store.dispatch(setTheme('dark'))
  }

  render() {
    return (
      <HmqLayoutContainer >
        {this.props.children}
      </HmqLayoutContainer>
    )
  }
}

export default HmqLayoutRoute;


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

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * The SMS text message multi-factor authentication (MFA) configuration type.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class SmsMfaConfigType implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The SMS authentication message.
     *

     */
    private String smsAuthenticationMessage;
    /**
     *

     * The SMS configuration.
     *

     */
    private SmsConfigurationType smsConfiguration;

    /**
     *

     * The SMS authentication message.
     *

     *
     * @param smsAuthenticationMessage
     *        The SMS authentication message.
     */

    public void setSmsAuthenticationMessage(String smsAuthenticationMessage) {
        this.smsAuthenticationMessage = smsAuthenticationMessage;
    }

    /**
     *

     * The SMS authentication message.
     *

     *
     * @return The SMS authentication message.
     */

    public String getSmsAuthenticationMessage() {
        return this.smsAuthenticationMessage;
    }

    /**
     *

     * The SMS authentication message.
     *

     *
     * @param smsAuthenticationMessage
     *        The SMS authentication message.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public SmsMfaConfigType withSmsAuthenticationMessage(String smsAuthenticationMessage) {
        setSmsAuthenticationMessage(smsAuthenticationMessage);
        return this;
    }

    /**
     *

     * The SMS configuration.
     *

     *
     * @param smsConfiguration
     *        The SMS configuration.
     */

    public void setSmsConfiguration(SmsConfigurationType smsConfiguration) {
        this.smsConfiguration = smsConfiguration;
    }

    /**
     *

     * The SMS configuration.
     *

     *
     * @return The SMS configuration.
     */

    public SmsConfigurationType getSmsConfiguration() {
        return this.smsConfiguration;
    }

    /**
     *

     * The SMS configuration.
     *

     *
     * @param smsConfiguration
     *        The SMS configuration.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public SmsMfaConfigType withSmsConfiguration(SmsConfigurationType smsConfiguration) {
        setSmsConfiguration(smsConfiguration);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getSmsAuthenticationMessage() != null)
            sb.append("SmsAuthenticationMessage: ").append(getSmsAuthenticationMessage()).append(",");
        if (getSmsConfiguration() != null)
            sb.append("SmsConfiguration: ").append(getSmsConfiguration());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof SmsMfaConfigType == false)
            return false;
        SmsMfaConfigType other = (SmsMfaConfigType) obj;
        if (other.getSmsAuthenticationMessage() == null ^ this.getSmsAuthenticationMessage() == null)
            return false;
        if (other.getSmsAuthenticationMessage() != null && other.getSmsAuthenticationMessage().equals(this.getSmsAuthenticationMessage()) == false)
            return false;
        if (other.getSmsConfiguration() == null ^ this.getSmsConfiguration() == null)
            return false;
        if (other.getSmsConfiguration() != null && other.getSmsConfiguration().equals(this.getSmsConfiguration()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getSmsAuthenticationMessage() == null) ? 0 : getSmsAuthenticationMessage().hashCode());
        hashCode = prime * hashCode + ((getSmsConfiguration() == null) ? 0 : getSmsConfiguration().hashCode());
        return hashCode;
    }

    @Override
    public SmsMfaConfigType clone() {
        try {
            return (SmsMfaConfigType) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.cognitoidp.model.transform.SmsMfaConfigTypeMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
package org.sakaiproject.nakamura.connections;

import org.sakaiproject.nakamura.api.connections.ConnectionOperation;

/**
 *
 */
public class TransitionKey {
  private ConnectionOperation operation;
  private StatePair startPair;

  /**
   *
   */
  public TransitionKey(StatePair startPair, ConnectionOperation operation) {
   this.startPair = startPair;
   this.operation = operation;
  }

  /**
   * {@inheritDoc}
   * @see java.lang.Object#hashCode()
   */
  @Override
  public int hashCode() {
    return startPair.hashCode()*1000+operation.hashCode();
  }

  /**
   * {@inheritDoc}
   * @see java.lang.Object#equals(java.lang.Object)
   */
  @Override
  public boolean equals(Object obj) {
    if ( obj instanceof TransitionKey ) {
     TransitionKey tk = (TransitionKey) obj;
     return startPair.equals(tk.startPair) && operation.equals(tk.operation);
    }
    return false;
  }

  /**
   * {@inheritDoc}
   * @see java.lang.Object#toString()
   */
  @Override
  public String toString() {
    return startPair.toString()+" "+operation.toString();
  }

}


text:
package org.biouno.unochoice.model;

import hudson.DescriptorExtensionList;
import hudson.model.Describable;
import hudson.model.Descriptor;
import jenkins.model.Jenkins;

/**
 * Abstract script.
 *
 * @author Bruno P. Kinoshita
 * @since 0.23
 */
public abstract class AbstractScript implements Script, Describable<AbstractScript> {

    /*
     * Serial UID.
     */
    private static final long serialVersionUID = 4027103576278802323L;

    @Override
    @SuppressWarnings("unchecked")
    public Descriptor<AbstractScript> getDescriptor() {
        final Jenkins instance = Jenkins.getInstanceOrNull();
        Descriptor<AbstractScript> descriptor = null;
        if (instance != null) {
            descriptor = instance.getDescriptor(getClass());
        }
        return descriptor;
    }

    public static DescriptorExtensionList<AbstractScript, ScriptDescriptor> all() {
        final Jenkins instance = Jenkins.getInstanceOrNull();
        DescriptorExtensionList<AbstractScript, ScriptDescriptor> all = null;
        if (instance != null) {
            all = instance.getDescriptorList(AbstractScript.class);
        }
        return all;
    }

}


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

<routes xmlns="http://symfony.com/schema/routing"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">

    <route id="shop_shipping_homepage" pattern="/hello/{name}">
        <default key="_controller">ShopShippingBundle:Default:index</default>
    </route>

    <route id="shipping_methods" pattern="/admin/shippingMethods">
        <default key="_controller">ShopShippingBundle:AdminShippingMethod:shippingMethods</default>
        <option key="title">shop.shipping.methods</option>
    </route>

    <route id="shipping_method" pattern="/admin/shippingMethod/{id}">
        <default key="_controller">ShopShippingBundle:AdminShippingMethod:shippingMethod</default>
        <default key="id">null</default>
        <option key="title">{{ shippingMethod.id ? shippingMethod.name : 'shop.shipping.method.add'|trans([],'ShopShippingBundle') }}</option>
        <option key="resourceKey">shippingMethod</option>
        <option key="parent">shipping_methods</option>
    </route>

    <route id="delete_shipping_method" pattern="/admin/deleteShippingMethod/{id}">
        <default key="_controller">ShopShippingBundle:AdminShippingMethod:deleteShippingMethod</default>
    </route>

    <route id="shipping_method_prices" pattern="/admin/shippingMethodPrice/{shippingMethodId}">
        <default key="_controller">ShopShippingBundle:AdminShippingMethod:shippingMethodPrices</default>
        <option key="title">shop.shipping.method.prices</option>
        <option key="resourceKey">shippingMethod||shippingMethodPrice</option>
        <option key="parent">shipping_method</option>
    </route>

    <route id="shipping_method_price" pattern="/admin/shippingMethodPrice/{shippingMethodId}/{id}">
        <default key="_controller">ShopShippingBundle:AdminShippingMethod:shippingMethodPrice</default>
        <default key="id">null</default>
        <option key="title">{{ (shippingMethodPrice.id ? 'shop.shipping.method.price.edit' : 'shop.shipping.method.price.add')|trans([],'ShopShippingBundle') }}</option>
        <option key="resourceKey">shippingMethodPrice</option>
        <option key="parent">shipping_method_prices</option>
    </route>

    <route id="delete_shipping_method_price" pattern="/admin/deleteShippingMethodPrice/{id}">
        <default key="_controller">ShopShippingBundle:AdminShippingMethod:deleteShippingMethodPrice</default>
    </route>

    <route id="shipping_method_lifting_prices" pattern="/admin/shippingMethodLiftingPrices/{shippingMethodId}">
        <default key="_controller">ShopShippingBundle:AdminShippingMethod:shippingMethodLiftingPrices</default>
        <option key="title">shop.shipping.method.lifting_prices</option>
        <option key="resourceKey">shippingMethod||shippingMethodLiftingPrice</option>
        <option key="parent">shipping_method</option>
    </route>

    <route id="shipping_method_lifting_price" pattern="/admin/shippingMethodLiftingPrice/{shippingMethodId}/{id}">
        <default key="_controller">ShopShippingBundle:AdminShippingMethod:shippingMethodLiftingPrice</default>
        <default key="id">null</default>
        <option key="title">{{ (shippingMethodLiftingPrice.id ? 'shop.shipping.method.lifting_price.edit' : 'shop.shipping.method.lifting_price.add')|trans([],'ShopShippingBundle') }}</option>
        <option key="resourceKey">shippingMethodLiftingPrice</option>
        <option key="parent">shipping_method_lifting_prices</option>
    </route>

    <route id="delete_shipping_method_lifting_price" pattern="/admin/deleteShippingMethodLiftingPrice/{id}">
        <default key="_controller">ShopShippingBundle:AdminShippingMethod:deleteShippingMethodLiftingPrice</default>
    </route>

    <route id="shipping_method_assembly_prices" pattern="/admin/shippingMethodAssemblyPrices/{shippingMethodId}">
        <default key="_controller">ShopShippingBundle:AdminShippingMethod:shippingMethodAssemblyPrices</default>
        <option key="title">shop.shipping.method.assembly_prices</option>
        <option key="resourceKey">shippingMethod||shippingMethodAssemblyPrice</option>
        <option key="parent">shipping_method</option>
    </route>

    <route id="shipping_method_assembly_price" pattern="/admin/shippingMethodAssemblyPrice/{shippingMethodId}/{id}">
        <default key="_controller">ShopShippingBundle:AdminShippingMethod:shippingMethodAssemblyPrice</default>
        <default key="id">null</default>
        <option key="title">{{ (shippingMethodAssemblyPrice.id ? 'shop.shipping.method.assembly_price.edit' : 'shop.shipping.method.assembly_price.add')|trans([],'ShopShippingBundle') }}</option>
        <option key="resourceKey">shippingMethodAssemblyPrice</option>
        <option key="parent">shipping_method_assembly_prices</option>
    </route>

    <route id="delete_shipping_method_assembly_price" pattern="/admin/deleteShippingMethodAssemblyPrice/{id}">
        <default key="_controller">ShopShippingBundle:AdminShippingMethod:deleteShippingMethodAssemblyPrice</default>
    </route>

    <route id="shipping_categories" pattern="/admin/shippingCategories/{shippingMethodId}">
        <default key="_controller">ShopShippingBundle:AdminShippingMethodCategory:shippingCategories</default>
        <option key="title">shop.shipping.categories</option>
        <option key="resourceKey">shippingMethod||shippingMethodCategory</option>
        <option key="parent">shipping_method</option>
    </route>

    <route id="shipping_category" pattern="/admin/shippingCategory/{shippingMethodId}/{id}">
        <default key="_controller">ShopShippingBundle:AdminShippingMethodCategory:shippingCategory</default>
        <default key="id">null</default>
        <option key="title">{{ (shippingCategory.id ? 'shop.shipping.category' : 'shop.shipping.category.add')|trans([],'ShopShippingBundle') }}</option>
        <option key="resourceKey">shippingCategory</option>
        <option key="parent">shipping_categories</option>
    </route>

    <route id="delete_shipping_category" pattern="/admin/deleteShippingCategory/{id}">
        <default key="_controller">ShopShippingBundle:AdminShippingMethodCategory:deleteShippingCategory</default>
    </route>

    <route id="shipping_category_price" pattern="/admin/shippingCategoryPrice/{shippingCategoryId}/{id}">
        <default key="_controller">ShopShippingBundle:AdminShippingMethodCategory:shippingCategoryPrice</default>
        <default key="id">null</default>
    </route>

    <route id="delete_shipping_category_price" pattern="/admin/deleteShippingCategoryPrice/{id}">
        <default key="_controller">ShopShippingBundle:AdminShippingMethodCategory:deleteShippingCategoryPrice</default>
    </route>

    <route id="shipping_category_lifting_price" pattern="/admin/shippingCategoryLiftingPrice/{shippingCategoryId}/{id}">
        <default key="_controller">ShopShippingBundle:AdminShippingMethodCategory:shippingCategoryLiftingPrice</default>
        <default key="id">null</default>
    </route>

    <route id="delete_shipping_category_lifting_price" pattern="/admin/deleteShippingCategoryLiftingPrice/{id}">
        <default key="_controller">ShopShippingBundle:AdminShippingMethodCategory:deleteShippingCategoryLiftingPrice</default>
    </route>

    <route id="shipping_category_assembly_price" pattern="/admin/shippingCategoryAssemblyPrice/{shippingCategoryId}/{id}">
        <default key="_controller">ShopShippingBundle:AdminShippingMethodCategory:shippingCategoryAssemblyPrice</default>
        <default key="id">null</default>
    </route>

    <route id="delete_shipping_category_assembly_price" pattern="/admin/deleteShippingCategoryAssemblyPrice/{id}">
        <default key="_controller">ShopShippingBundle:AdminShippingMethodCategory:deleteShippingCategoryAssemblyPrice</default>
    </route>

</routes>


text:
<?php
session_start();
if(isset($_GET['update'])){
    $update = $_GET['update'];
}

// connect to database
define('DB_NAME', 'blue_team_bmw');
define('DB_USER', 'blue_team');
define('DB_PASSWORD', 'bmw');
define('DB_HOST', 'localhost');

$link = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD);

if (!$link) {
    die('Could not connect: ' . mysqli_error($link));
}

$db_selected = mysqli_select_db($link, DB_NAME);

if (!$db_selected) {
    die('Can\'t use ' . DB_NAME . ': ' . mysqli_error($link));
}

//echo 'Connected successfully';

// update general information data
if($update == 'general'){
    $first = $_POST['firstName'];
    $last = $_POST['lastName'];
    $position = $_POST['position'];
    $address = $_POST['address'];
    $city = $_POST['city'];
    $country = $_POST['country'];
    $state = $_POST['state'];
    $zip = $_POST['zip'];
    $email = $_POST['email'];
    $password = $_POST['password'];
	$salary = $_POST['salary'];

    $sql = "update admin_info set first_name = '" . $first . "', last_name = '" . $last . "', position = '" . $position . "', address = '" . $address . "', city = '" . $city . "', country = '" . $country . "', state = '" . $state . "', zip = '" . $zip . "', email = '" . $email . "', pw = '" . $password . "' where cust_num = " . $_SESSION['cust_num'] . ";";

    if(!mysqli_query($link, $sql)) {
        die('Error: ' . mysqli_error($link));
    }

    header('Location: customer_page.php?menu=general');
}

mysqli_close($link);
?>


text:
<?php

/**
 * Notifications.
 *
 * @since 7.10.5
 */
class MonsterInsights_Notifications {

	/**
	 * Source of notifications content.
	 *
	 * @since {VERSION}
	 *
	 * @var string
	 */
	const SOURCE_URL = 'https://plugin-cdn.monsterinsights.com/notifications.json';

	/**
	 * Option value.
	 *
	 * @since {VERSION}
	 *
	 * @var bool|array
	 */
	public $option = false;

	/**
	 * The name of the option used to store the data.
	 *
	 * @var string
	 */
	public $option_name = 'monsterinsights_notifications';

	/**
	 * MonsterInsights_Notifications constructor.
	 */
	public function __construct() {
		$this->init();
	}

	/**
	 * Initialize class.
	 *
	 * @since {VERSION}
	 */
	public function init() {

		$this->hooks();
	}

	/**
	 * Register hooks.
	 *
	 * @since {VERSION}
	 */
	public function hooks() {
		add_action( 'wp_ajax_monsterinsights_notification_dismiss', array( $this, 'dismiss' ) );

		add_action( 'wp_ajax_monsterinsights_vue_get_notifications', array( $this, 'ajax_get_notifications' ) );

		add_action( 'monsterinsights_admin_notifications_update', array( $this, 'update' ) );

	}

	/**
	 * Check if user has access and is enabled.
	 *
	 * @return bool
	 * @since {VERSION}
	 *
	 */
	public function has_access() {

		$access = false;

		if ( current_user_can( 'monsterinsights_view_dashboard' ) && ! monsterinsights_get_option( 'hide_am_notices', false ) ) {
			$access = true;
		}

		return apply_filters( 'monsterinsights_admin_notifications_has_access', $access );
	}

	/**
	 * Get option value.
	 *
	 * @param bool $cache Reference property cache if available.
	 *
	 * @return array
	 * @since {VERSION}
	 *
	 */
	public function get_option( $cache = true ) {

		if ( $this->option && $cache ) {
			return $this->option;
		}

		$option = get_option( $this->option_name, array() );

		$this->option = array(
			'update'    => ! empty( $option['update'] ) ? $option['update'] : 0,
			'events'    => ! empty( $option['events'] ) ? $option['events'] : array(),
			'feed'      => ! empty( $option['feed'] ) ? $option['feed'] : array(),
			'dismissed' => ! empty( $option['dismissed'] ) ? $option['dismissed'] : array(),
		);

		return $this->option;
	}

	/**
	 * Fetch notifications from feed.
	 *
	 * @return array
	 * @since {VERSION}
	 *
	 */
	public function fetch_feed() {

		$res = wp_remote_get( self::SOURCE_URL );

		if ( is_wp_error( $res ) ) {
			return array();
		}

		$body = wp_remote_retrieve_body( $res );

		if ( empty( $body ) ) {
			return array();
		}

		return $this->verify( json_decode( $body, true ) );
	}

	/**
	 * Verify notification data before it is saved.
	 *
	 * @param array $notifications Array of notifications items to verify.
	 *
	 * @return array
	 * @since {VERSION}
	 *
	 */
	public function verify( $notifications ) { // phpcs:ignore Generic.Metrics.CyclomaticComplexity.TooHigh

		$data = array();

		if ( ! is_array( $notifications ) || empty( $notifications ) ) {
			return $data;
		}

		$option = $this->get_option();

		foreach ( $notifications as $notification ) {

			// The message and license should never be empty, if they are, ignore.
			if ( empty( $notification['content'] ) || empty( $notification['type'] ) ) {
				continue;
			}

			// Ignore if license type does not match.
			$license_type = MonsterInsights()->license->get_license_type() ? MonsterInsights()->license->get_license_type() : 'lite';

			if ( ! in_array( $license_type, $notification['type'] ) ) {
				continue;
			}

			// Ignore if expired.
			if ( ! empty( $notification['end'] ) && time() > strtotime( $notification['end'] ) ) {
				continue;
			}

			// Ignore if notification has already been dismissed.
			if ( ! empty( $option['dismissed'] ) && in_array( $notification['id'], $option['dismissed'] ) ) { // phpcs:ignore WordPress.PHP.StrictInArray.MissingTrueStrict
				continue;
			}

			// Ignore if notification existed before installing MonsterInsights.
			// Prevents bombarding the user with notifications after activation.
			$over_time = get_option( 'monsterinsights_over_time', array() );

			if (
				! empty( $over_time['installed_date'] ) &&
				! empty( $notification['start'] ) &&
				$over_time['installed_date'] > strtotime( $notification['start'] )
			) {
				continue;
			}

			$data[] = $notification;
		}

		return $data;
	}

	/**
	 * Verify saved notification data for active notifications.
	 *
	 * @param array $notifications Array of notifications items to verify.
	 *
	 * @return array
	 * @since {VERSION}
	 *
	 */
	public function verify_active( $notifications ) {

		if ( ! is_array( $notifications ) || empty( $notifications ) ) {
			return array();
		}

		// Remove notifications that are not active.
		foreach ( $notifications as $key => $notification ) {
			if (
				( ! empty( $notification['start'] ) && time() < strtotime( $notification['start'] ) ) ||
				( ! empty( $notification['end'] ) && time() > strtotime( $notification['end'] ) )
			) {
				unset( $notifications[ $key ] );
			}
		}

		return $notifications;
	}

	/**
	 * Get notification data.
	 *
	 * @return array
	 * @since {VERSION}
	 *
	 */
	public function get() {

		if ( ! $this->has_access() ) {
			return array();
		}

		$option = $this->get_option();

		// Update notifications using async task.
		if ( empty( $option['update'] ) || time() > $option['update'] + DAY_IN_SECONDS ) {
			if ( false === wp_next_scheduled( 'monsterinsights_admin_notifications_update' ) ) {
				wp_schedule_single_event( time(), 'monsterinsights_admin_notifications_update' );
			}
		}

		$events = ! empty( $option['events'] ) ? $this->verify_active( $option['events'] ) : array();
		$feed   = ! empty( $option['feed'] ) ? $this->verify_active( $option['feed'] ) : array();

		return array_merge( $events, $feed );
	}

	/**
	 * Get notification count.
	 *
	 * @return int
	 * @since {VERSION}
	 *
	 */
	public function get_count() {

		return count( $this->get() );
	}

	/**
	 * Add a manual notification event.
	 *
	 * @param array $notification Notification data.
	 *
	 * @since {VERSION}
	 *
	 */
	public function add( $notification ) {

		if ( empty( $notification['id'] ) ) {
			return;
		}

		$option = $this->get_option();

		if ( in_array( $notification['id'], $option['dismissed'] ) ) { // phpcs:ignore WordPress.PHP.StrictInArray.MissingTrueStrict
			return;
		}

		foreach ( $option['events'] as $item ) {
			if ( $item['id'] === $notification['id'] ) {
				return;
			}
		}

		$notification = $this->verify( array( $notification ) );

		update_option(
			$this->option_name,
			array(
				'update'    => $option['update'],
				'feed'      => $option['feed'],
				'events'    => array_merge( $notification, $option['events'] ),
				'dismissed' => $option['dismissed'],
			)
		);
	}

	/**
	 * Update notification data from feed.
	 *
	 * @since {VERSION}
	 */
	public function update() {

		$feed   = $this->fetch_feed();
		$option = $this->get_option();

		update_option(
			$this->option_name,
			array(
				'update'    => time(),
				'feed'      => $feed,
				'events'    => $option['events'],
				'dismissed' => $option['dismissed'],
			)
		);
	}

	/**
	 * Dismiss notification via AJAX.
	 *
	 * @since {VERSION}
	 */
	public function dismiss() {

		// Run a security check.
		check_ajax_referer( 'mi-admin-nonce', 'nonce' );

		// Check for access and required param.
		if ( ! $this->has_access() || empty( $_POST['id'] ) ) {
			wp_send_json_error();
		}

		$id     = sanitize_text_field( wp_unslash( $_POST['id'] ) );
		$option = $this->get_option();
		$type   = is_numeric( $id ) ? 'feed' : 'events';

		$option['dismissed'][] = $id;
		$option['dismissed']   = array_unique( $option['dismissed'] );

		// Remove notification.
		if ( is_array( $option[ $type ] ) && ! empty( $option[ $type ] ) ) {
			foreach ( $option[ $type ] as $key => $notification ) {
				if ( $notification['id'] == $id ) { // phpcs:ignore WordPress.PHP.StrictComparisons
					unset( $option[ $type ][ $key ] );
					break;
				}
			}
		}

		update_option( $this->option_name, $option );

		wp_send_json_success();
	}

	/**
	 * This generates the markup for the notifications indicator if needed.
	 *
	 * @return string
	 */
	public function get_menu_count() {

		if ( $this->get_count() > 0 ) {
			return '';
		}

		return '';

	}

	/**
	 * Retrieve the notifications via an ajax call.
	 */
	public function ajax_get_notifications() {

		// Run a security check.
		check_ajax_referer( 'mi-admin-nonce', 'nonce' );

		$notifications_data = array(
			'notifications' => $this->get(),
			'view_url'      => $this->get_view_url(),
		);

		wp_send_json_success( $notifications_data );
	}

	/**
	 * Get the URL for the page where users can see/read notifications.
	 *
	 * @return string
	 */
	public function get_view_url() {

		$disabled = monsterinsights_get_option( 'dashboards_disabled', false );

		$url = add_query_arg( 'page', 'monsterinsights_reports', admin_url( 'admin.php' ) );

		if ( false !== $disabled ) {
			$url = is_multisite() ? network_admin_url( 'admin.php?page=monsterinsights_network' ) : admin_url( 'admin.php?page=monsterinsights_settings' );
		}

		return $url;

	}
}


text:
package com.fluentsquare.web;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;

public class Runner
{
	public static void main(String[] args)
	{
		Server server = new Server(8080);

		WebAppContext webAppContext = new WebAppContext();
		webAppContext.setServer(server);
		webAppContext.setContextPath("/");
		webAppContext.setWar("src/main/webapp");

		// START JMX SERVER
		// MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
		// MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer);
		// server.getContainer().addEventListener(mBeanContainer);
		// mBeanContainer.start();

		server.setHandler(webAppContext);

		try
		{
			System.out.println(">>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP");
			server.start();
			while (System.in.available() == 0)
			{
				Thread.sleep(5000);
			}
			server.stop();
			server.join();
		}
		catch (Exception e)
		{
			e.printStackTrace();
			System.exit(100);
		}
	}
}


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

    <title>Hacuchis - Always go forward!</title>
    <meta name="description" content="Hacuchis" />

    <meta name="HandheldFriendly" content="True" />
    <meta name="MobileOptimized" content="320" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="stylesheet" type="text/css" href="/assets/css/screen.css" />
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" />

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

        Home
        Subscribe

Prueba de concepto: MobileFirst Platform, Cloudant, Android y Bluemix

                <time class="post-date" datetime="2016-03-15">15 Mar 2016</time>

                    on IBM

        android
          1

        bluemix
          4

        cloudant
          2

        mfp
          2

Solo para complementar el post anterior aumentaremos el API para Android e intentaremos obtener el mismo resultado.
Para lo antes mencionado se necesitará lo siguiente:

Android Studio (ya con todo instalado incluido un dispositivo para la ejecución)

Post anterior completado

Configurando aplicación Android para interactuar con MFP

Para esto lo primero que se tiene que tener es:

Un proyecto cualquiera en Android Studio creado.

Un servidor MobileFirst Platform en ejecución (para este ejemplo se debera tener el mismo servidor del post anterior).

Como configuraciones a realizar primero dirigirse a Android, Gradle scripts y seleccionar build.gradle (Module: App)

Añadir justo debajo de apply plugin: 'com.android.application':

repositories{
    jcenter()
}

Dentro de android:

packagingOptions {
        pickFirst 'META-INF/ASL2.0'
        pickFirst 'META-INF/LICENSE'
        pickFirst 'META-INF/NOTICE'
}

Dentro de dependencies:

compile group: 'com.ibm.mobile.foundation',
    name: 'ibmmobilefirstplatformfoundation',
    version: '7.1.0.0',
    ext: 'aar',
    transitive: true

Buscar el archivo AndroidManifest.xml

Colocar antes del tag application lo siguiente:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.GET_TASKS" />

Adicionar la actividad MobileFirst UI como sigue, después del cierre del último tag activity

<activity android:name="com.worklight.wlclient.ui.UIActivity" />

Cuando se tenga lo previo con una terminal dirigirse hasta el directorio donde se encuentre el proyecto Android creado y en la raiz ejecutar el siguiente comando:

$ mfp push

Como el servidor de MFP esta en ejecución lo que hará este comando es configurar el proyecto android como si de un API de MFP se tratará y se encargará de hacer el push respectivo a nuestro servidor local.

Si todo va bien en nuestro proyecto Android deberiamos notar que se han adicionado 3 nuevas cosas, las cuales se muestran en la siguiente figura:

Los cuales son importantes por:
- Dentro de la carpeta assets se encuentra el archivo wlclient.properties que viene siendo como el archivo worklight.plist en el proyecto iOS en donde lo que se hacia era configurar la ip, puerto y el nombre del servidor MFP ya sea local o remoto.
- Dentro de la carpeta mobilefirst se encuetra el archivo .wlapp generado de la aplicación para poder subirlo a nuestro servidor remoto y que así MFP en Bluemix reconozca las llamadas de dispositivos Android.
- El archivo application-descriptor.xml es un informativo de la aplicación generada.

Codeando

Al igual que en el proyecto anterior ahora toca codificar tanto la conexión con MFP local o remoto como la interacción con el adaptador de Cloudant que ya se configuró previamente. Para ello abriremos el archivo main generado por Android Studio, en mi caso MainActivity.java y añadiremos las siguiente lineas:

Al inicio de la clase adicionaremos la declaración de un objeto WLClient que se encargará de la conectividad entre la app Android y MFP:

private WLClient client;

En la función onCreate añadiremos la instanciación del objeto antes mencionado así como la conexión y al igual que haciamos los delegate en el proyecto iOS para esta interacción en Android se generará un WLResponseListener con los mismos métodos onSuccess y onFailure, cabe resaltar que en el siguiente código se esta adicionando una llamada a la función callAdapter que se encargará de hacer la llamada al adaptador de Cloudant si y solo si se ha logrado conectar la aplicación con MFP de forma satisfactoria.

client = WLClient.createInstance(this);
client.connect(new WLResponseListener() {
    @Override
    public void onSuccess(WLResponse wlResponse) {
        Log.d("MFP Connection", "Success");
        callAdapter();
    }

    @Override
    public void onFailure(WLFailResponse wlFailResponse) {
        Log.d("MFP Connection", "Fail");
    }
});

Para ir terminando se implementará la función callAdapter

private void callAdapter() {
    URI adapterPath = null;
    try {
        adapterPath = new URI("adapters/PrimaxAdapter/postTransaction");
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

    WLResourceRequest request = new WLResourceRequest(adapterPath, WLResourceRequest.POST);

    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject.put("transaction", "Envio de mensajes desde Android Remoto");
        jsonObject.put("transaction_module", "Santiago");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    request.setQueryParameter("params", "["+jsonObject+"]");

    request.send(new WLResponseListener() {
        @Override
        public void onSuccess(WLResponse wlResponse) {
            Log.d("Invocation status", wlResponse.getResponseText());
        }

        @Override
        public void onFailure(WLFailResponse wlFailResponse) {
            Log.d("Invocation failed", wlFailResponse.getResponseText());
        }
    });
}

Aqui lo que hay que resaltar es:
- Para la llamada al procedimiento se hace mediante un objeto URI el cual ubica el adaptador usando una ruta de la siguiente forma: adapters / nombre del adaptador / procedimiento a llamar
- Mediante un objeto WLResourceRequest se le indica que tipo de verbo se usará GET, POST, etc.
- Para poder enviar información (en el caso de Cloudante se esta solicitando guardar data así que si es necesario esta parte), se declara e inicializa un objeto JSONObject similar al que se hizo en el proyecto iOS y mediante una llamada al método setQueryParameter se le añade la data al objeto request.
- En la llamada al método send se hace lo propio para confirmar la conexión al servicio de Cloudant.

NOTA IMPORTANTE: No se olviden de subir su aplicación y adaptador al MFP de Bluemix eso lo hacen desde el administrador con el boton de Añadir nueva aplicación o adaptador, lo que deberan subir son los archivos .wlapp y .adapter que se encuentran en la carpeta /bin/ de su proyecto, en el caso del proyecto Android se encuentra en la carpeta mobilefirst.

Con esto ejecuten y prueben su aplicación y felicitaciones estan conectados a MFP ya sea local o en Bluemix y enviando a guardar mensajes en Cloudant en Blumix.

                    NuSs's Picture

 NuSs

                        Dame un punto de apoyo y moveré el mundo. Arquimedes

Share this post

        Twitter

        Facebook

        Google+

        Hacuchis ©
               • All rights reserved.

Made with Jekyll using
        Kasper theme


text:
#include "config.h"
#include "core/css/parser/CSSParserValues.h"

#include "core/css/parser/CSSParserTokenRange.h"
#include "core/css/parser/CSSTokenizer.h"
#include <gtest/gtest.h>

namespace blink {

TEST(CSSParserValuesTest, InitWithEmptyString)
{
    String string;

    CSSParserString cssParserString;
    cssParserString.init(string);
    EXPECT_EQ(0u, cssParserString.length());
    EXPECT_EQ(string, String(cssParserString));
    EXPECT_TRUE(String(cssParserString).isNull());

    string = "";
    cssParserString.init(string);
    EXPECT_EQ(0u, cssParserString.length());
    EXPECT_EQ(string, String(cssParserString));
    EXPECT_FALSE(String(cssParserString).isNull());

    string.ensure16Bit();
    cssParserString.init(string);
    EXPECT_EQ(0u, cssParserString.length());
    EXPECT_EQ(string, String(cssParserString));
    EXPECT_FALSE(String(cssParserString).isNull());
}

TEST(CSSParserValuesTest, EqualIgnoringCase8BitsString)
{
    CSSParserString cssParserString;
    String string8bit("sHaDOw");
    cssParserString.init(string8bit);

    ASSERT_TRUE(cssParserString.equalIgnoringCase("shadow"));
    ASSERT_TRUE(cssParserString.equalIgnoringCase("ShaDow"));
    ASSERT_FALSE(cssParserString.equalIgnoringCase("shadow-all"));
    ASSERT_FALSE(cssParserString.equalIgnoringCase("sha"));
    ASSERT_FALSE(cssParserString.equalIgnoringCase("abCD"));
}

TEST(CSSParserValuesTest, EqualIgnoringCase16BitsString)
{
    String string16bit("sHaDOw");
    string16bit.ensure16Bit();

    CSSParserString cssParserString;
    cssParserString.init(string16bit);

    ASSERT_TRUE(cssParserString.equalIgnoringCase("shadow"));
    ASSERT_TRUE(cssParserString.equalIgnoringCase("ShaDow"));
    ASSERT_FALSE(cssParserString.equalIgnoringCase("shadow-all"));
    ASSERT_FALSE(cssParserString.equalIgnoringCase("sha"));
    ASSERT_FALSE(cssParserString.equalIgnoringCase("abCD"));
}

TEST(CSSParserValuesTest, CSSParserValuelistClear)
{
    CSSParserValueList list;
    for (int i = 0; i < 3; ++i) {
        CSSParserValue value;
        value.setFromNumber(3);
        list.addValue(value);
    }
    list.clearAndLeakValues();
    ASSERT_FALSE(list.size());
    ASSERT_FALSE(list.currentIndex());
}

TEST(CSSParserValuesTest, CSSParserTokenUrlConversion)
{
    CSSTokenizer::Scope scope("url(some) uRL('test') UrL(  \"words\" /**/ ) URl( /**/hi/**/ )");
    bool usesRemUnits;
    CSSParserValueList valueList(scope.tokenRange(), usesRemUnits);
    ASSERT_EQ(valueList.size(), 4u);
    ASSERT_EQ(valueList.valueAt(0)->unit, CSSPrimitiveValue::CSS_URI);
    EXPECT_EQ(String(valueList.valueAt(0)->string), "some");
    ASSERT_EQ(valueList.valueAt(1)->unit, CSSPrimitiveValue::CSS_URI);
    EXPECT_EQ(String(valueList.valueAt(1)->string), "test");
    ASSERT_EQ(valueList.valueAt(2)->unit, CSSPrimitiveValue::CSS_URI);
    EXPECT_EQ(String(valueList.valueAt(2)->string), "words");
    ASSERT_EQ(valueList.valueAt(3)->unit, CSSPrimitiveValue::CSS_URI);
    EXPECT_EQ(String(valueList.valueAt(3)->string), "/**/hi/**/");
}

} // namespace blink


text:
Rails.application.routes.draw do

  mount Scheeema::Engine => "/scheeema"
end


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911
// .1802
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.07.16 at 03:24:22 PM EEST
//

package org.ecloudmanager.tmrk.cloudapi.model;

import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;

/**
 *
Java class for RecipientType complex type.
 *

 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <complexType name="RecipientType">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="Name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="Email" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "RecipientType", propOrder = {
    "name",
    "email"
})
public class RecipientType {

    @XmlElementRef(name = "Name", type = JAXBElement.class, required = false)
    protected JAXBElement<String> name;
    @XmlElement(name = "Email", required = true, nillable = true)
    protected String email;

    /**
     * Gets the value of the name property.
     *
     * @return possible object is
     * {@link JAXBElement }{@code <}{@link String }{@code >}
     */
    public JAXBElement<String> getName() {
        return name;
    }

    /**
     * Sets the value of the name property.
     *
     * @param value allowed object is
     *              {@link JAXBElement }{@code <}{@link String }{@code >}
     */
    public void setName(JAXBElement<String> value) {
        this.name = value;
    }

    /**
     * Gets the value of the email property.
     *
     * @return possible object is
     * {@link String }
     */
    public String getEmail() {
        return email;
    }

    /**
     * Sets the value of the email property.
     *
     * @param value allowed object is
     *              {@link String }
     */
    public void setEmail(String value) {
        this.email = value;
    }

}


text:
from biicode.common.exception import InvalidNameException
import re

class BRLUser(str):
    """Biicode Resurce Locator for a user
    """

    base_er = "[a-zA-Z][a-zA-Z0-9_]{1,49}"
    pattern = re.compile("^%s$" % base_er)

    def create_block_name(self, name):
        from block_name import BlockName
        return BlockName('%s/%s' % (self, BRLUser(name)))

    def __new__(cls, name, validate=True):
        """Simple name creation.

        @param name:        string containing the desired name
        @param validate:    checks for valid simple name. default True
        """
        if validate:
            name = BRLUser.validate(name)
        return str.__new__(cls, name)

    @staticmethod
    def validate(name):
        """Check for name compliance with pattern rules. User names can be
           with upper/lower case
        """
        try:
            name = name.strip()
            if BRLUser.pattern.match(name) is None:
                if len(name) > 49:
                    message = "'%s' is too long. Valid names must contain at most 50 characters."
                elif len(name) < 2:
                    message = "'%s' is too short. Valid names must contain at least 2 characters."
                else:
                    message = "'%s' is an invalid name. "\
                              "Valid names should begin with alphanumerical characters."
                raise InvalidNameException(message % name)
            return name
        except AttributeError:
            raise InvalidNameException('Empty name provided', None)


text:
package de.friemelay.am.ui;

import de.friemelay.am.model.AbstractModel;
import de.friemelay.am.resources.ResourceLoader;
import javafx.scene.control.Button;
import javafx.scene.control.Tab;
import javafx.scene.layout.BorderPane;

/**
 *
 */
public abstract class ModelTab<T extends AbstractModel> extends Tab {
  protected T model;
  private boolean dirty;

  private BorderPane root = new BorderPane();

  protected Button saveButton;
  protected Button resetButton;

  public ModelTab(T model) {
    super(model.toString());
    setGraphic(ResourceLoader.getImageView(model.getStatusIcon()));
    this.model = model;
    initTab();
  }

  protected void initTab() {
    this.setContent(root);
    init();
  }

  protected boolean isDirty() {
    return dirty;
  }

  public T getModel() {
    return model;
  }

  protected void setDirty(boolean b) {
    this.dirty = b;
    saveButton.setDisable(!b);
    resetButton.setDisable(!b);
  }

  protected BorderPane getRoot() {
    return root;
  }

  abstract protected void init();
}


text:
@class NSMutableDictionary, NSString;

@interface WCPayNetworkMgr : MMService <PBMessageObserverDelegate, MMService>
{
    NSMutableDictionary *_startedTimeDic;
    NSMutableDictionary *_callerNames;
    NSMutableDictionary *_callbacks;
}

@property(retain, nonatomic) NSMutableDictionary *callbacks; // @synthesize callbacks=_callbacks;
- (void).cxx_destruct;
- (void)debugPrintRequestWithCGIWrap:(id)arg1;
- (void)debugPrintResponseWithCGIWrap:(id)arg1;
- (id)nearestOutsideCallerName;
- (void)cleanForKey:(id)arg1;
- (void)handleErrorAndClean:(id)arg1 forKey:(id)arg2 completion:(CDUnknownBlockType)arg3;
- (void)handleCommonErrorAndCleanForKey:(id)arg1 completion:(CDUnknownBlockType)arg2;
- (unsigned int)sendRequest:(id)arg1 cgi:(unsigned int)arg2 completion:(CDUnknownBlockType)arg3;
- (void)MessageReturn:(id)arg1 Event:(unsigned int)arg2;
- (unsigned int)queryFlowDataWithFuncId:(id)arg1 mobile:(id)arg2 productName:(id)arg3 appId:(id)arg4 remarks:(id)arg5 ticket:(id)arg6 completion:(CDUnknownBlockType)arg7;
- (unsigned int)getIAPOrderDetailWithOrderID:(id)arg1 completion:(CDUnknownBlockType)arg2;
- (unsigned int)deleteSingleOrderWithOrderID:(id)arg1 payType:(long long)arg2 billId:(id)arg3 completion:(CDUnknownBlockType)arg4;
- (unsigned int)commonQueryCmdID:(unsigned int)arg1 bizParams:(id)arg2 wxParams:(id)arg3 completion:(CDUnknownBlockType)arg4;
- (_Bool)cancelRequestForEventId:(unsigned int)arg1;
- (void)onServiceClearData;
- (void)onServiceTerminate;
- (void)onServiceEnterForeground;
- (void)onServiceEnterBackground;
- (void)onServiceReloadData;
- (void)onServiceInit;
- (void)dealloc;

// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;

@end


text:
module Georgia
  class UiAssociationPolicy < WidgetPolicy
  end
end


text:
package com.thoughtworks.go.apiv2.compare.representers;

import com.thoughtworks.go.api.base.OutputWriter;
import com.thoughtworks.go.config.materials.Filter;
import com.thoughtworks.go.config.materials.IgnoredFiles;

import java.util.stream.Collectors;

public class FilterRepresenter {
    public static void toJSON(OutputWriter outputWriter, Filter filter) {
        if (!filter.isEmpty()) {
            outputWriter.addChildList("ignore", filter.stream().map(IgnoredFiles::getPattern).collect(Collectors.toList()));
        }
    }
}


text:
import { ExtensionDefinition } from 'jsreport-core';

declare module 'jsreport-core' {
    interface Template {
        scripts?: JsReportScripts.TemplateScript[];
    }
}

declare namespace JsReportScripts {
    interface TemplateScript {
        shortid?: string;
        name?: string;
        content?: string;
    }

    interface Configuration {
        allowedModules?: string[] | "*";
    }
}

declare function JsReportScripts(cfg?: JsReportScripts.Configuration): ExtensionDefinition;

export = JsReportScripts;


text:
Remote Data Services
====================

As described in Section :doc:`Internal Data Ingestion <bytes>`, various
user-facing functions (such as ``dataframe.read_csv``,
``dataframe.read_parquet``, ``bag.read_text``) and lower level
byte-manipulating functions may point to data
that lives not on the local storage of the workers, but on a remote system
such as Amazon S3.

In this section we describe how to use the various known back-end storage
systems. Below we give some details for interested developers on how further
storage back-ends may be provided for dask's use.

Known Storage Implementations
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

When specifying a storage location, a URL should be provided using the general
form ``protocol://path/to/data``.
If no protocol is provided, the local file-system is assumed (same as
``file://``). Two methods exist for passing parameters to the backend
file-system driver: extending the URL to include username, password, server,
port, etc.; and providing ``storage_options``, a dictionary of parameters
to pass on. Examples:

.. code-block:: python

   df = dd.read_csv('hdfs://user@server:port/path/*.csv')

   df = dd.read_parquet('s3://bucket/path',
        storage_options={'anon': True, 'use_ssl': False})

Further details on how to provide configuration for each backend
is listed next.

Each back-end has additional installation requirements and may not be
available at runtime. The dictionary ``dask.bytes.core._filesystems``
contains the currently available file-systems. Some require
appropriate imports before use.

The following list gives the protocol shorthands and the back-ends they refer
to:

    - ``file:`` - the local file system, default in the absence of any protocol

    - ``hdfs:`` - Hadoop Distributed File System, a for resilient, replicated
      files within a cluster, using the library hdfs3_

    - ``s3:`` - Amazon S3 remote binary store, often used with Amazon EC2,
      using the library s3fs_

    - ``gcs:`` or ``gs:`` - Google Cloud Storage, typically used with Google Compute
      resource, using gcsfs_ (in development)

    .. - # ``adlfs:`` - Azure Data-lake cloud storage, for use with the Microsoft
      Azure platform, using azure-data-lake-store-python_

.. _hdfs3: http://hdfs3.readthedocs.io/
.. _s3fs: http://s3fs.readthedocs.io/
.. .. _azure-data-lake-store-python: https://github.com/Azure/azure-data-lake-store-python
.. _gcsfs: https://github.com/martindurant/gcsfs/

Local File System
-----------------

Local files are always accessible, and all parameters passed as part of the URL
(beyond the path itself) or with the ``storage_options``
dictionary will be ignored.

This is the default back-end, and the one used if no protocol is passed at all.

We assume here that each worker has access to the same file-system - either
the workers are co-located on the same machine, or a network file system
is mounted and referenced at the same path location for every worker node.

Locations specified relative to the current working directory will, in
general, be respected (as they would be with the built-in python ``open``),
but this may fail in the case that the client and worker processes do not
necessarily have the same working directory.

HDFS
----

The Hadoop File System (HDFS) is a widely deployed, distributed, data-local file
system written in Java. This file system backs many clusters running Hadoop and
Spark.

Within dask, HDFS is only available when the module ``distributed.hdfs`` is
explicitly imported, since the usage of HDFS usually only makes sense in a cluster
setting. The distributed scheduler will prefer to allocate tasks
which read from HDFS  to machines which have local copies of the
blocks required for their work, where possible.

By default, hdfs3 attempts to read the default server and port from local
Hadoop configuration files on each node, so it may be that no configuration is
required. However, the server, port and user can be passed as part of the
url: ``hdfs://user:pass@server:port/path/to/data``.

The following parameters may be passed to hdfs3 using ``storage_options``:

    - host, port, user: basic authentication
    - ticket_cache, token: kerberos authentication
    - pars: dictionary of further parameters (e.g., for `high availability`_)

.. _high availability: http://hdfs3.readthedocs.io/en/latest/hdfs.html#high-availability-mode

Important environment variables:

    - HADOOP_CONF_DIR or HADOOP_INSTALL: directory containing ``core-site.xml``
      and/or ``hdfs-site.xml``, containing configuration information

    - LIBHDFS3_CONF: location of a specific xml file with configuration for
      the `libhdfs3 client`_; this may be the same as one of the files above. `Short
      circuit` reads should be defined in this file (`see here`_)

.. _see here: http://hdfs3.readthedocs.io/en/latest/hdfs.html#short-circuit-reads-in-hdfs
.. _libhdfs3 client: https://github.com/Pivotal-Data-Attic/pivotalrd-libhdfs3/wiki/Configure-Parameters

S3
-----

Amazon S3 (Simple Storage Service) is a web service offered by Amazon Web
Services.

The S3 back-end will be available to dask is s3fs is importable when dask is
imported.

Authentication for S3 is provided by the underlying library boto3. As described
in the `auth docs`_ this could be achieved by placing credentials files in one
of several locations on each node: ``~/.aws/credentials``, ``~/.aws/config``,
``/etc/boto.cfg`` and ``~/.boto``. Alternatively, for nodes located
within Amazon EC2, IAM roles can be set up for each node, and then no further
configuration is required. The final authentication option, is for user
credentials can be passed directly in the URL
(``s3://keyID:keySecret/bucket/key/name``) or using ``storage_options``. In
this case, however, the key/secret will be passed to all workers in-the-clear,
so this method is only recommended on well-secured networks.

.. _auth docs: http://boto3.readthedocs.io/en/latest/guide/configuration.html

The following parameters may be passed to s3fs using ``storage_options``:

    - anon: whether access should be anonymous (default False)

    - key, secret: for user authentication

    - token: if authentication has been done with some other S3 client

    - use_ssl: whether connections are encryted and secure (default True)

    - client_kwargs: dict passed to the `boto3 client`_, with keys such
      as `region_name`, `endpoint_url`

    - requester_pays: set True if the authenticated user will assume transfer
      costs, which is required by some providers of bulk data

    - default_block_size, default_fill_cache: these are not of particular
      interest to dask users, as they concern the behaviour of the buffer
      between successive reads

    - kwargs: other parameters are passed to the `boto3 Session`_ object,
      such as `profile_name`, to pick one of the authentication sections from
      the configuration files referred to above (see `here`_)

.. _boto3 client: http://boto3.readthedocs.io/en/latest/reference/core/session.html#boto3.session.Session.client
.. _boto3 Session: http://boto3.readthedocs.io/en/latest/reference/core/session.html
.. _here: http://boto3.readthedocs.io/en/latest/guide/configuration.html#shared-credentials-file

Google Cloud Storage
--------------------

(gcsfs is in early development, expect the details here to change)

Google Cloud Storage is a RESTful online file storage web service for storing
and accessing data on Google's infrastructure.

The GCS backend will be available only after importing gcsfs_. The
protocol identifiers ``gcs`` and ``gs`` are identical in their effect.

Authentication for GCS is based on OAuth2, and designed for user verification.
Interactive authentication is available when ``token==None`` using the local
browser, or by using gcloud_ to produce a JSON token file and passing that.
In either case, gcsfs stores a cache of tokens in a local file, so subsequent
authentication will not be necessary.

.. _gcsfs: https://github.com/martindurant/gcsfs/
.. _gcloud: https://cloud.google.com/sdk/docs/

At the time of writing, ``gcsfs.GCSFileSystem`` instances pickle including the auth token, so sensitive
information is passed between nodes of a dask distributed cluster. This will
be changed to allow the use of either local JSON or pickle files for storing
tokens and authenticating on each node automatically, instead of
passing around an authentication token, similar to S3, above.

Every use of GCS requires the specification of a project to run within - if the
project is left empty, the user will not be able to perform any bucket-level
operations. The project can be defined using the  variable
GCSFS_DEFAULT_PROJECT in the environment of every worker, or by passing
something like the following

.. code-block:: python

   dd.read_parquet('gs://bucket/path', storage_options={'project': 'myproject'}

Possible additional storage options:

   -  access : 'read_only', 'read_write', 'full_control', access privilege
      level (note that the token cache uses a separate token for each level)

   -  token: either an actual dictionary of a google token, or location of
      a JSON file created by gcloud.

Developer API
~~~~~~~~~~~~~

The prototype for any file-system back-end can be found in
``bytes.local.LocalFileSystem``. Any new implementation should provide the
same API, and make itself available as a protocol to dask. For example, the
following would register the protocol "myproto", described by the implementation
class ``MyProtoFileSystem``. URLs of the form ``myproto://`` would thereafter
be dispatched to the methods of this class.

.. code-block:: python

   dask.bytes.core._filesystems['myproto'] = MyProtoFileSystem

For a more complicated example, users may wish to also see
``dask.bytes.s3.DaskS3FileSystem``.

.. currentmodule:: dask.bytes.local

.. autoclass:: LocalFileSystem
   :members:


text:
using System;
using System.Collections.Generic;
using System.Linq;

using ASC.Core;
using ASC.Core.Users;
using ASC.Projects.Core.DataInterfaces;
using ASC.Projects.Core.Domain;
using ASC.Web.Core;
using ASC.Web.Core.Utility.Settings;
using ASC.Web.Projects;
using ASC.Web.Projects.Classes;

using Autofac;

namespace ASC.Projects.Engine
{
    public class ProjectSecurityCommon
    {
        public bool Can(Guid userId)
        {
            return !IsVisitor(userId) && IsProjectsEnabled(userId);
        }

        public bool Can()
        {
            return Can(CurrentUserId);
        }

        public Guid CurrentUserId { get; private set; }

        public bool CurrentUserAdministrator { get; private set; }

        private bool CurrentUserIsVisitor { get; set; }

        internal bool CurrentUserIsOutsider { get; set; }

        public bool CurrentUserIsProjectsEnabled { get; private set; }

        public bool CurrentUserIsCRMEnabled { get; private set; }

        public bool IsPrivateDisabled { get; private set; }

        public IDaoFactory DaoFactory { get; set; }

        public EngineFactory EngineFactory { get; set; }

        public ProjectSecurityCommon()
        {
            CurrentUserId = SecurityContext.CurrentAccount.ID;
            CurrentUserAdministrator = CoreContext.UserManager.IsUserInGroup(CurrentUserId, Constants.GroupAdmin.ID) ||
                   WebItemSecurity.IsProductAdministrator(WebItemManager.ProjectsProductID, CurrentUserId);
            CurrentUserIsVisitor = CoreContext.UserManager.GetUsers(CurrentUserId).IsVisitor();
            CurrentUserIsOutsider = IsOutsider(CurrentUserId);
            IsPrivateDisabled = TenantAccessSettings.Load().Anyone;
            CurrentUserIsProjectsEnabled = IsModuleEnabled(WebItemManager.ProjectsProductID, CurrentUserId);
            CurrentUserIsCRMEnabled = IsModuleEnabled(WebItemManager.CRMProductID, CurrentUserId);
        }

        public bool IsAdministrator(Guid userId)
        {
            if (userId == CurrentUserId) return CurrentUserAdministrator;

            return CoreContext.UserManager.IsUserInGroup(userId, Constants.GroupAdmin.ID) ||
                   WebItemSecurity.IsProductAdministrator(WebItemManager.ProjectsProductID, userId);
        }

        public bool IsProjectsEnabled()
        {
            return IsProjectsEnabled(CurrentUserId);
        }

        public bool IsProjectsEnabled(Guid userID)
        {
            if (userID == CurrentUserId) return CurrentUserIsProjectsEnabled;

            return IsModuleEnabled(WebItemManager.ProjectsProductID, userID);
        }

        public bool IsCrmEnabled()
        {
            return IsCrmEnabled(CurrentUserId);
        }

        public bool IsCrmEnabled(Guid userID)
        {
            if (userID == CurrentUserId) return CurrentUserIsCRMEnabled;

            return IsModuleEnabled(WebItemManager.CRMProductID, userID);
        }

        private bool IsModuleEnabled(Guid module, Guid userId)
        {
            var projects = WebItemManager.Instance[module];

            if (projects != null)
            {
                return !projects.IsDisabled(userId);
            }

            return false;
        }

        public bool IsVisitor(Guid userId)
        {
            if (userId == CurrentUserId) return CurrentUserIsVisitor;

            return CoreContext.UserManager.GetUsers(userId).IsVisitor();
        }

        public bool IsOutsider(Guid userId)
        {
            return CoreContext.UserManager.GetUsers(userId).IsOutsider();
        }

        public bool IsProjectManager(Project project)
        {
            return IsProjectManager(project, CurrentUserId);
        }

        public bool IsProjectManager(Project project, Guid userId)
        {
            return (IsAdministrator(userId) || (project != null && project.Responsible == userId)) &&
                   !CurrentUserIsVisitor;
        }

        public bool IsProjectCreator(Project project)
        {
            return IsProjectCreator(project, CurrentUserId);
        }

        public bool IsProjectCreator(Project project, Guid userId)
        {
            return (project != null && project.CreateBy == userId);
        }

        public bool IsInTeam(Project project)
        {
            return IsInTeam(project, CurrentUserId);
        }

        public bool IsInTeam(Project project, Guid userId, bool includeAdmin = true)
        {
            var isAdmin = includeAdmin && IsAdministrator(userId);
            return isAdmin || (project != null && DaoFactory.ProjectDao.IsInTeam(project.ID, userId));
        }

        public bool IsFollow(Project project, Guid userID)
        {
            var isAdmin = IsAdministrator(userID);
            var isPrivate = project != null && (!project.Private || isAdmin);

            return isPrivate && DaoFactory.ProjectDao.IsFollow(project.ID, userID);
        }

        public bool GetTeamSecurity(Project project, ProjectTeamSecurity security)
        {
            return GetTeamSecurity(project, CurrentUserId, security);
        }

        public bool GetTeamSecurity(Project project, Guid userId, ProjectTeamSecurity security)
        {
            if (IsProjectManager(project, userId) || project == null || !project.Private) return true;
            var dao = DaoFactory.ProjectDao;
            var s = dao.GetTeamSecurity(project.ID, userId);
            return (s & security) != security && dao.IsInTeam(project.ID, userId);
        }

        public bool GetTeamSecurityForParticipants(Project project, Guid userId, ProjectTeamSecurity security)
        {
            if (IsProjectManager(project, userId) || !project.Private) return true;
            var s = DaoFactory.ProjectDao.GetTeamSecurity(project.ID, userId);
            return (s & security) != security;
        }
    }

    public abstract class ProjectSecurityTemplate<T> where T : DomainObject<int>
    {
        public ProjectSecurityCommon Common { get; set; }

        public virtual bool CanCreateEntities(Project project)
        {
            return project != null && project.Status == ProjectStatus.Open && Common.Can();
        }

        public virtual bool CanReadEntities(Project project, Guid userId)
        {
            return Common.IsProjectsEnabled(userId);
        }

        public bool CanReadEntities(Project project)
        {
            return CanReadEntities(project, Common.CurrentUserId);
        }

        public virtual bool CanReadEntity(T entity, Guid userId)
        {
            return entity != null && Common.Can(userId);
        }

        public bool CanReadEntity(T entity)
        {
            return CanReadEntity(entity, Common.CurrentUserId);
        }

        public virtual bool CanUpdateEntity(T entity)
        {
            return Common.Can() && entity != null;
        }

        public virtual bool CanDeleteEntity(T entity)
        {
            return Common.Can() && entity != null;
        }

        public virtual bool CanCreateComment(T entity)
        {
            return false;
        }

        public virtual bool CanEditFiles(T entity)
        {
            return false;
        }

        public virtual bool CanEditComment(T entity, Comment comment)
        {
            return false;
        }

        public virtual bool CanGoToFeed(T entity, Guid userId)
        {
            return false;
        }
    }

    public sealed class ProjectSecurityProject : ProjectSecurityTemplate<Project>
    {
        public override bool CanCreateEntities(Project project)
        {
            return Common.Can() && (Common.CurrentUserAdministrator || ProjectsCommonSettings.Load().EverebodyCanCreate);
        }

        public override bool CanReadEntity(Project project, Guid userId)
        {
            if (!Common.IsProjectsEnabled(userId)) return false;
            if (project == null) return false;
            if (project.Private && Common.IsPrivateDisabled) return false;
            return !project.Private || Common.IsProjectCreator(project, userId) || Common.IsInTeam(project, userId);
        }

        public override bool CanUpdateEntity(Project project)
        {
            return base.CanUpdateEntity(project) && Common.IsProjectManager(project) || Common.IsProjectCreator(project);
        }

        public override bool CanDeleteEntity(Project project)
        {
            return base.CanDeleteEntity(project) && Common.CurrentUserAdministrator || Common.IsProjectCreator(project);
        }

        public override bool CanGoToFeed(Project project, Guid userId)
        {
            if (project == null || !Common.IsProjectsEnabled(userId))
            {
                return false;
            }
            return WebItemSecurity.IsProductAdministrator(EngineFactory.ProductId, userId)
                   || Common.IsInTeam(project, userId, false)
                   || Common.IsFollow(project, userId)
                   || Common.IsProjectCreator(project, userId);
        }

        public bool CanEditTeam(Project project)
        {
            return Common.Can() && (Common.IsProjectManager(project) || Common.IsProjectCreator(project));
        }

        public bool CanReadFiles(Project project)
        {
            return CanReadFiles(project, SecurityContext.CurrentAccount.ID);
        }

        public bool CanReadFiles(Project project, Guid userId)
        {
            return Common.IsProjectsEnabled(userId) && Common.GetTeamSecurity(project, userId, ProjectTeamSecurity.Files);
        }

        public override bool CanEditComment(Project project, Comment comment)
        {
            if (!Common.IsProjectsEnabled()) return false;
            if (project == null || comment == null) return false;
            return comment.CreateBy == Common.CurrentUserId || Common.IsProjectManager(project);
        }

        public bool CanReadContacts(Project project)
        {
            return Common.IsCrmEnabled() && Common.IsProjectsEnabled() &&
                   Common.GetTeamSecurity(project, ProjectTeamSecurity.Contacts);
        }

        public bool CanLinkContact(Project project)
        {
            return Common.IsProjectsEnabled() && CanUpdateEntity(project);
        }
    }

    public sealed class ProjectSecurityTask : ProjectSecurityTemplate<Task>
    {
        public ProjectSecurityProject ProjectSecurityProject { get; set; }

        public ProjectSecurityMilestone ProjectSecurityMilestone { get; set; }

        public override bool CanCreateEntities(Project project)
        {
            if (!base.CanCreateEntities(project)) return false;
            if (Common.IsProjectManager(project)) return true;
            return Common.IsInTeam(project) && CanReadEntities(project);
        }

        public override bool CanReadEntities(Project project, Guid userId)
        {
            return base.CanReadEntities(project, userId) && Common.GetTeamSecurity(project, userId, ProjectTeamSecurity.Tasks);
        }

        public override bool CanReadEntity(Task task, Guid userId)
        {
            if (task == null || !ProjectSecurityProject.CanReadEntity(task.Project, userId)) return false;

            if (task.Responsibles.Contains(userId)) return true;

            if (!CanReadEntities(task.Project, userId)) return false;

            if (task.Milestone != 0 && !ProjectSecurityMilestone.CanReadEntities(task.Project, userId))
            {
                var m = Common.DaoFactory.MilestoneDao.GetById(task.Milestone);
                if (!ProjectSecurityMilestone.CanReadEntity(m, userId)) return false;
            }

            return true;
        }

        public override bool CanUpdateEntity(Task task)
        {
            if (!base.CanUpdateEntity(task)) return false;
            if (task.Project.Status == ProjectStatus.Closed) return false;
            if (Common.IsProjectManager(task.Project)) return true;

            return Common.IsInTeam(task.Project) &&
                   (task.CreateBy == Common.CurrentUserId ||
                    !task.Responsibles.Any() ||
                    task.Responsibles.Contains(Common.CurrentUserId));
        }

        public override bool CanDeleteEntity(Task task)
        {
            if (!base.CanDeleteEntity(task)) return false;
            if (Common.IsProjectManager(task.Project)) return true;

            return Common.IsInTeam(task.Project) && task.CreateBy == Common.CurrentUserId;
        }

        public override bool CanCreateComment(Task entity)
        {
            return CanReadEntity(entity) &&
                Common.IsProjectsEnabled() &&
                SecurityContext.IsAuthenticated &&
                !Common.CurrentUserIsOutsider;
        }

        public bool CanEdit(Task task, Subtask subtask)
        {
            if (subtask == null || !Common.Can()) return false;
            if (CanUpdateEntity(task)) return true;

            return Common.IsInTeam(task.Project) &&
                   (subtask.CreateBy == Common.CurrentUserId ||
                    subtask.Responsible == Common.CurrentUserId);
        }

        public override bool CanGoToFeed(Task task, Guid userId)
        {
            if (task == null || !Common.IsProjectsEnabled(userId)) return false;
            if (task.CreateBy == userId) return true;
            if (!Common.IsInTeam(task.Project, userId, false) && !Common.IsFollow(task.Project, userId)) return false;
            if (task.Responsibles.Contains(userId)) return true;
            if (task.Milestone != 0 && !ProjectSecurityMilestone.CanReadEntities(task.Project, userId))
            {
                var milestone = Common.DaoFactory.MilestoneDao.GetById(task.Milestone);
                if (milestone.Responsible == userId)
                {
                    return true;
                }
            }
            return Common.GetTeamSecurityForParticipants(task.Project, userId, ProjectTeamSecurity.Tasks);
        }

        public override bool CanEditFiles(Task entity)
        {
            if (!Common.IsProjectsEnabled()) return false;
            if (entity.Project.Status == ProjectStatus.Closed) return false;
            if (Common.IsProjectManager(entity.Project)) return true;

            return CanUpdateEntity(entity);
        }

        public override bool CanEditComment(Task entity, Comment comment)
        {
            if (entity == null) return false;

            return ProjectSecurityProject.CanEditComment(entity.Project, comment);
        }

        public bool CanCreateSubtask(Task task)
        {
            if (task == null || !Common.Can()) return false;
            if (Common.IsProjectManager(task.Project)) return true;

            return Common.IsInTeam(task.Project) &&
                   ((task.CreateBy == Common.CurrentUserId) ||
                    !task.Responsibles.Any() ||
                    task.Responsibles.Contains(Common.CurrentUserId));
        }

        public bool CanCreateTimeSpend(Task task)
        {
            if (task == null || !Common.Can()) return false;
            if (task.Project.Status != ProjectStatus.Open) return false;
            if (Common.IsInTeam(task.Project)) return true;

            return task.Responsibles.Contains(Common.CurrentUserId) ||
                   task.SubTasks.Select(r => r.Responsible).Contains(Common.CurrentUserId);
        }
    }

    public sealed class ProjectSecurityMilestone : ProjectSecurityTemplate<Milestone>
    {
        public ProjectSecurityProject ProjectSecurityProject { get; set; }

        public override bool CanCreateEntities(Project project)
        {
            return base.CanCreateEntities(project) && Common.IsProjectManager(project);
        }

        public override bool CanReadEntities(Project project, Guid userId)
        {
            return base.CanReadEntities(project, userId) && Common.GetTeamSecurity(project, userId, ProjectTeamSecurity.Milestone);
        }

        public override bool CanReadEntity(Milestone entity, Guid userId)
        {
            if (entity == null || !ProjectSecurityProject.CanReadEntity(entity.Project, userId)) return false;
            if (entity.Responsible == userId) return true;

            return CanReadEntities(entity.Project, userId);
        }

        public override bool CanUpdateEntity(Milestone milestone)
        {
            if (!base.CanUpdateEntity(milestone)) return false;
            if (milestone.Project.Status == ProjectStatus.Closed) return false;
            if (Common.IsProjectManager(milestone.Project)) return true;
            if (!CanReadEntity(milestone)) return false;

            return Common.IsInTeam(milestone.Project) &&
                   (milestone.CreateBy == Common.CurrentUserId ||
                    milestone.Responsible == Common.CurrentUserId);
        }

        public override bool CanDeleteEntity(Milestone milestone)
        {
            if (!base.CanDeleteEntity(milestone)) return false;
            if (Common.IsProjectManager(milestone.Project)) return true;

            return Common.IsInTeam(milestone.Project) && milestone.CreateBy == Common.CurrentUserId;
        }

        public override bool CanGoToFeed(Milestone milestone, Guid userId)
        {
            if (milestone == null || !Common.IsProjectsEnabled(userId)) return false;
            if (!Common.IsInTeam(milestone.Project, userId, false) && !Common.IsFollow(milestone.Project, userId)) return false;
            return milestone.Responsible == userId || Common.GetTeamSecurityForParticipants(milestone.Project, userId, ProjectTeamSecurity.Milestone);
        }
    }

    public sealed class ProjectSecurityMessage : ProjectSecurityTemplate<Message>
    {
        public ProjectSecurityProject ProjectSecurityProject { get; set; }

        public override bool CanCreateEntities(Project project)
        {
            if (!base.CanCreateEntities(project)) return false;
            if (Common.IsProjectManager(project)) return true;
            return Common.IsInTeam(project) && CanReadEntities(project);
        }

        public override bool CanReadEntities(Project project, Guid userId)
        {
            return base.CanReadEntities(project, userId) && Common.GetTeamSecurity(project, userId, ProjectTeamSecurity.Messages);
        }

        public override bool CanReadEntity(Message entity, Guid userId)
        {
            if (entity == null || !ProjectSecurityProject.CanReadEntity(entity.Project, userId)) return false;

            return CanReadEntities(entity.Project, userId);
        }

        public override bool CanUpdateEntity(Message message)
        {
            if (!base.CanUpdateEntity(message)) return false;
            if (Common.IsProjectManager(message.Project)) return true;
            if (!CanReadEntity(message)) return false;

            return Common.IsInTeam(message.Project) && message.CreateBy == Common.CurrentUserId;
        }

        public override bool CanDeleteEntity(Message message)
        {
            return CanUpdateEntity(message);
        }

        public override bool CanCreateComment(Message message)
        {
            return CanReadEntity(message) &&
                (message == null || message.Status == MessageStatus.Open) &&
                Common.IsProjectsEnabled() &&
                SecurityContext.IsAuthenticated &&
                !Common.CurrentUserIsOutsider;
        }

        public override bool CanGoToFeed(Message message, Guid userId)
        {
            if (message == null || !Common.IsProjectsEnabled(userId)) return false;
            if (message.CreateBy == userId) return true;
            if (!Common.IsInTeam(message.Project, userId, false) && !Common.IsFollow(message.Project, userId)) return false;

            var isSubscriber = Common.EngineFactory.MessageEngine.GetSubscribers(message).Any(r => new Guid(r.ID).Equals(userId));
            return isSubscriber && Common.GetTeamSecurityForParticipants(message.Project, userId, ProjectTeamSecurity.Messages);
        }

        public override bool CanEditComment(Message message, Comment comment)
        {
            return message.Status == MessageStatus.Open && ProjectSecurityProject.CanEditComment(message.Project, comment);
        }

        public override bool CanEditFiles(Message entity)
        {
            if (!Common.IsProjectsEnabled()) return false;
            if (entity.Status == MessageStatus.Archived || entity.Project.Status == ProjectStatus.Closed) return false;
            if (Common.IsProjectManager(entity.Project)) return true;

            return Common.IsInTeam(entity.Project);
        }
    }

    public sealed class ProjectSecurityTimeTracking : ProjectSecurityTemplate<TimeSpend>
    {
        public ProjectSecurityTask ProjectSecurityTask { get; set; }

        public override bool CanCreateEntities(Project project)
        {
            if (!base.CanCreateEntities(project)) return false;
            if (project.Status == ProjectStatus.Closed) return false;
            return Common.IsInTeam(project);
        }

        public override bool CanReadEntities(Project project, Guid userId)
        {
            return ProjectSecurityTask.CanReadEntities(project, userId);
        }

        public override bool CanReadEntity(TimeSpend entity, Guid userId)
        {
            return ProjectSecurityTask.CanReadEntity(entity.Task, userId);
        }

        public override bool CanUpdateEntity(TimeSpend timeSpend)
        {
            if (!base.CanUpdateEntity(timeSpend)) return false;
            if (Common.IsProjectManager(timeSpend.Task.Project)) return true;
            if (timeSpend.PaymentStatus == PaymentStatus.Billed) return false;

            return timeSpend.Person == Common.CurrentUserId || timeSpend.CreateBy == Common.CurrentUserId;
        }

        public override bool CanDeleteEntity(TimeSpend timeSpend)
        {
            if (!base.CanDeleteEntity(timeSpend)) return false;
            if (Common.IsProjectManager(timeSpend.Task.Project)) return true;
            if (timeSpend.PaymentStatus == PaymentStatus.Billed) return false;

            return Common.IsInTeam(timeSpend.Task.Project) &&
                   (timeSpend.CreateBy == Common.CurrentUserId || timeSpend.Person == Common.CurrentUserId);
        }

        public bool CanEditPaymentStatus(TimeSpend timeSpend)
        {
            return timeSpend != null && Common.Can() && Common.IsProjectManager(timeSpend.Task.Project);
        }
    }

    public class ProjectSecurity
    {
        public ILifetimeScope Scope { get; set; }

        public bool CanCreate<T>(Project project) where T : DomainObject<int>
        {
            return Scope.Resolve<ProjectSecurityTemplate<T>>().CanCreateEntities(project);
        }

        public bool CanEdit<T>(T entity) where T : DomainObject<int>
        {
            return Scope.Resolve<ProjectSecurityTemplate<T>>().CanUpdateEntity(entity);
        }

        public bool CanRead<T>(T entity) where T : DomainObject<int>
        {
            return Scope.Resolve<ProjectSecurityTemplate<T>>().CanReadEntity(entity);
        }

        public bool CanRead<T>(T entity, Guid userId) where T : DomainObject<int>
        {
            return Scope.Resolve<ProjectSecurityTemplate<T>>().CanReadEntity(entity, userId);
        }

        public bool CanRead<T>(Project project) where T : DomainObject<int>
        {
            return Scope.Resolve<ProjectSecurityTemplate<T>>().CanReadEntities(project);
        }

        public bool CanDelete<T>(T entity) where T : DomainObject<int>
        {
            return Scope.Resolve<ProjectSecurityTemplate<T>>().CanDeleteEntity(entity);
        }

        public bool CanEditComment(ProjectEntity entity, Comment comment)
        {
            var task = entity as Task;
            if (task != null)
            {
                return Scope.Resolve<ProjectSecurityTask>().CanEditComment(task, comment);
            }

            var message = entity as Message;
            return Scope.Resolve<ProjectSecurityMessage>().CanEditComment(message, comment);
        }

        public bool CanEditComment(Project entity, Comment comment)
        {
            return Scope.Resolve<ProjectSecurityProject>().CanEditComment(entity, comment);
        }

        public bool CanCreateComment(ProjectEntity entity)
        {
            var task = entity as Task;
            if (task != null)
            {
                return Scope.Resolve<ProjectSecurityTask>().CanCreateComment(task);
            }

            var message = entity as Message;
            return Scope.Resolve<ProjectSecurityMessage>().CanCreateComment(message);
        }

        public bool CanCreateComment(Project project)
        {
            return Scope.Resolve<ProjectSecurityProject>().CanCreateComment(project);
        }

        public bool CanEdit(Task task, Subtask subtask)
        {
            return Scope.Resolve<ProjectSecurityTask>().CanEdit(task, subtask);
        }

        public bool CanReadFiles(Project project, Guid userId)
        {
            return Scope.Resolve<ProjectSecurityProject>().CanReadFiles(project, userId);
        }

        public bool CanReadFiles(Project project)
        {
            return Scope.Resolve<ProjectSecurityProject>().CanReadFiles(project);
        }

        public bool CanEditFiles<T>(T entity) where T : DomainObject<int>
        {
            return Scope.Resolve<ProjectSecurityTemplate<T>>().CanEditFiles(entity);
        }

        public bool CanEditTeam(Project project)
        {
            return Scope.Resolve<ProjectSecurityProject>().CanEditTeam(project);
        }

        public bool CanLinkContact(Project project)
        {
            return Scope.Resolve<ProjectSecurityProject>().CanLinkContact(project);
        }

        public bool CanReadContacts(Project project)
        {
            return Scope.Resolve<ProjectSecurityProject>().CanReadContacts(project);
        }

        public bool CanEditPaymentStatus(TimeSpend timeSpend)
        {
            return Scope.Resolve<ProjectSecurityTimeTracking>().CanEditPaymentStatus(timeSpend);
        }

        public bool CanCreateSubtask(Task task)
        {
            return Scope.Resolve<ProjectSecurityTask>().CanCreateSubtask(task);
        }

        public bool CanCreateTimeSpend(Task task)
        {
            return Scope.Resolve<ProjectSecurityTask>().CanCreateTimeSpend(task);
        }

        public bool CanEditTemplate(Template template)
        {
            return CurrentUserAdministrator || template.CreateBy.Equals(SecurityContext.CurrentAccount.ID);
        }

        public bool CanGoToFeed<T>(T entity, Guid userId) where T : DomainObject<int>
        {
            return Scope.Resolve<ProjectSecurityTemplate<T>>().CanGoToFeed(entity, userId);
        }

        public bool CanGoToFeed(ParticipantFull participant, Guid userId)
        {
            var common = Scope.Resolve<ProjectSecurityCommon>();
            if (participant == null || !IsProjectsEnabled(userId)) return false;
            return common.IsInTeam(participant.Project, userId, false) || common.IsFollow(participant.Project, userId);
        }

        public bool IsInTeam(Project project, Guid userId, bool includeAdmin = true)
        {
            return Scope.Resolve<ProjectSecurityCommon>().IsInTeam(project, userId, includeAdmin);
        }

        public void DemandCreate<T>(Project project) where T : DomainObject<int>
        {
            if (!CanCreate<T>(project)) throw CreateSecurityException();
        }

        public void DemandEdit<T>(T entity) where T : DomainObject<int>
        {
            if (!CanEdit(entity)) throw CreateSecurityException();
        }

        public void DemandEdit(Task task, Subtask subtask)
        {
            if (!CanEdit(task, subtask)) throw CreateSecurityException();
        }

        public void DemandCreateSubtask(Task task)
        {
            if (!CanCreateSubtask(task)) throw CreateSecurityException();
        }

        public void DemandDelete<T>(T entity) where T : DomainObject<int>
        {
            if (!CanDelete(entity)) throw CreateSecurityException();
        }

        public void DemandEditComment(ProjectEntity entity, Comment comment)
        {
            if (!CanEditComment(entity, comment)) throw CreateSecurityException();
        }

        public void DemandEditComment(Project entity, Comment comment)
        {
            if (!CanEditComment(entity, comment)) throw CreateSecurityException();
        }

        public void DemandCreateComment(Project project)
        {
            if (!CanCreateComment(project)) throw CreateSecurityException();
        }

        public void DemandCreateComment(ProjectEntity entity)
        {
            if (!CanCreateComment(entity)) throw CreateSecurityException();
        }

        public void DemandLinkContact(Project project)
        {
            if (!Scope.Resolve<ProjectSecurityProject>().CanLinkContact(project))
            {
                throw CreateSecurityException();
            }
        }

        public void DemandEditTeam(Project project)
        {
            if (!CanEditTeam(project)) throw CreateSecurityException();
        }

        public void DemandReadFiles(Project project)
        {
            if (!CanReadFiles(project)) throw CreateSecurityException();
        }

        public static void DemandAuthentication()
        {
            if (!SecurityContext.CurrentAccount.IsAuthenticated)
            {
                throw CreateSecurityException();
            }
        }

        public bool CurrentUserAdministrator
        {
            get
            {
                return Scope.Resolve<ProjectSecurityCommon>().CurrentUserAdministrator;
            }
        }

        public bool IsPrivateDisabled
        {
            get
            {
                return Scope.Resolve<ProjectSecurityCommon>().IsPrivateDisabled;
            }
        }

        public bool IsVisitor()
        {
            return IsVisitor(SecurityContext.CurrentAccount.ID);
        }

        public bool IsVisitor(Guid userId)
        {
            return Scope.Resolve<ProjectSecurityCommon>().IsVisitor(userId);
        }

        public bool IsAdministrator()
        {
            return IsAdministrator(SecurityContext.CurrentAccount.ID);
        }

        public bool IsAdministrator(Guid userId)
        {
            return Scope.Resolve<ProjectSecurityCommon>().IsAdministrator(userId);
        }

        public bool IsProjectsEnabled()
        {
            return IsProjectsEnabled(SecurityContext.CurrentAccount.ID);
        }

        public bool IsProjectsEnabled(Guid userId)
        {
            return Scope.Resolve<ProjectSecurityCommon>().IsProjectsEnabled(userId);
        }

        public void GetProjectSecurityInfo(Project project)
        {
            var projectSecurity = Scope.Resolve<ProjectSecurityProject>();
            var milestoneSecurity = Scope.Resolve<ProjectSecurityMilestone>();
            var messageSecurity = Scope.Resolve<ProjectSecurityMessage>();
            var taskSecurity = Scope.Resolve<ProjectSecurityTask>();
            var timeSpendSecurity = Scope.Resolve<ProjectSecurityTimeTracking>();

            project.Security = GetProjectSecurityInfoWithSecurity(project, projectSecurity, milestoneSecurity, messageSecurity, taskSecurity, timeSpendSecurity);
        }

        public void GetProjectSecurityInfo(IEnumerable<Project> projects)
        {
            var projectSecurity = Scope.Resolve<ProjectSecurityProject>();
            var milestoneSecurity = Scope.Resolve<ProjectSecurityMilestone>();
            var messageSecurity = Scope.Resolve<ProjectSecurityMessage>();
            var taskSecurity = Scope.Resolve<ProjectSecurityTask>();
            var timeSpendSecurity = Scope.Resolve<ProjectSecurityTimeTracking>();

            foreach (var project in projects)
            {
                project.Security = GetProjectSecurityInfoWithSecurity(project, projectSecurity, milestoneSecurity, messageSecurity, taskSecurity, timeSpendSecurity);
            }
        }

        public void GetTaskSecurityInfo(Task task)
        {
            var projectSecurity = Scope.Resolve<ProjectSecurityProject>();
            var taskSecurity = Scope.Resolve<ProjectSecurityTask>();

            task.Security = GetTaskSecurityInfoWithSecurity(task, projectSecurity, taskSecurity);
        }

        public void GetTaskSecurityInfo(IEnumerable<Task> tasks)
        {
            var projectSecurity = Scope.Resolve<ProjectSecurityProject>();
            var taskSecurity = Scope.Resolve<ProjectSecurityTask>();

            foreach (var task in tasks)
            {
                task.Security = GetTaskSecurityInfoWithSecurity(task, projectSecurity, taskSecurity);
            }
        }

        private ProjectSecurityInfo GetProjectSecurityInfoWithSecurity(Project project, ProjectSecurityProject projectSecurity, ProjectSecurityMilestone milestoneSecurity, ProjectSecurityMessage messageSecurity, ProjectSecurityTask taskSecurity, ProjectSecurityTimeTracking timeSpendSecurity)
        {
            return new ProjectSecurityInfo
            {
                CanCreateMilestone = milestoneSecurity.CanCreateEntities(project),
                CanCreateMessage = messageSecurity.CanCreateEntities(project),
                CanCreateTask = taskSecurity.CanCreateEntities(project),
                CanCreateTimeSpend = timeSpendSecurity.CanCreateEntities(project),

                CanEditTeam = projectSecurity.CanEditTeam(project),
                CanReadFiles = projectSecurity.CanReadFiles(project),
                CanReadMilestones = milestoneSecurity.CanReadEntities(project),
                CanReadMessages = messageSecurity.CanReadEntities(project),
                CanReadTasks = taskSecurity.CanReadEntities(project),
                IsInTeam = milestoneSecurity.Common.IsInTeam(project, SecurityContext.CurrentAccount.ID, false),
                CanLinkContact = projectSecurity.CanLinkContact(project),
                CanReadContacts = projectSecurity.CanReadContacts(project),

                CanEdit = projectSecurity.CanUpdateEntity(project),
                CanDelete = projectSecurity.CanDeleteEntity(project),
            };
        }

        private TaskSecurityInfo GetTaskSecurityInfoWithSecurity(Task task, ProjectSecurityProject projectSecurity, ProjectSecurityTask taskSecurity)
        {
            return new TaskSecurityInfo
            {
                CanEdit = taskSecurity.CanUpdateEntity(task),
                CanCreateSubtask = taskSecurity.CanCreateSubtask(task),
                CanCreateTimeSpend = taskSecurity.CanCreateTimeSpend(task),
                CanDelete = taskSecurity.CanDeleteEntity(task),
                CanReadFiles = projectSecurity.CanReadFiles(task.Project)
            };
        }

        public static Exception CreateSecurityException()
        {
            throw new System.Security.SecurityException("Access denied.");
        }

        public static Exception CreateGuestSecurityException()
        {
            throw new System.Security.SecurityException("A guest cannot be appointed as responsible.");
        }

    }
}